Bug Summary

File:llvm/include/llvm/IR/Instructions.h
Warning:line 1713, column 19
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstCombineSelect.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

1//===- InstCombineSelect.cpp ----------------------------------------------===//
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 the visitSelect function.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/Optional.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/CmpInstAnalysis.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/Constant.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/IRBuilder.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Operator.h"
33#include "llvm/IR/PatternMatch.h"
34#include "llvm/IR/Type.h"
35#include "llvm/IR/User.h"
36#include "llvm/IR/Value.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/KnownBits.h"
40#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
41#include <cassert>
42#include <utility>
43
44using namespace llvm;
45using namespace PatternMatch;
46
47#define DEBUG_TYPE"instcombine" "instcombine"
48
49static Value *createMinMax(InstCombiner::BuilderTy &Builder,
50 SelectPatternFlavor SPF, Value *A, Value *B) {
51 CmpInst::Predicate Pred = getMinMaxPred(SPF);
52 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate")((CmpInst::isIntPredicate(Pred) && "Expected integer predicate"
) ? static_cast<void> (0) : __assert_fail ("CmpInst::isIntPredicate(Pred) && \"Expected integer predicate\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 52, __PRETTY_FUNCTION__))
;
53 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
54}
55
56/// Replace a select operand based on an equality comparison with the identity
57/// constant of a binop.
58static Instruction *foldSelectBinOpIdentity(SelectInst &Sel,
59 const TargetLibraryInfo &TLI) {
60 // The select condition must be an equality compare with a constant operand.
61 Value *X;
62 Constant *C;
63 CmpInst::Predicate Pred;
64 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
65 return nullptr;
66
67 bool IsEq;
68 if (ICmpInst::isEquality(Pred))
69 IsEq = Pred == ICmpInst::ICMP_EQ;
70 else if (Pred == FCmpInst::FCMP_OEQ)
71 IsEq = true;
72 else if (Pred == FCmpInst::FCMP_UNE)
73 IsEq = false;
74 else
75 return nullptr;
76
77 // A select operand must be a binop.
78 BinaryOperator *BO;
79 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
80 return nullptr;
81
82 // The compare constant must be the identity constant for that binop.
83 // If this a floating-point compare with 0.0, any zero constant will do.
84 Type *Ty = BO->getType();
85 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
86 if (IdC != C) {
87 if (!IdC || !CmpInst::isFPPredicate(Pred))
88 return nullptr;
89 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
90 return nullptr;
91 }
92
93 // Last, match the compare variable operand with a binop operand.
94 Value *Y;
95 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
96 return nullptr;
97 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
98 return nullptr;
99
100 // +0.0 compares equal to -0.0, and so it does not behave as required for this
101 // transform. Bail out if we can not exclude that possibility.
102 if (isa<FPMathOperator>(BO))
103 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
104 return nullptr;
105
106 // BO = binop Y, X
107 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
108 // =>
109 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
110 Sel.setOperand(IsEq ? 1 : 2, Y);
111 return &Sel;
112}
113
114/// This folds:
115/// select (icmp eq (and X, C1)), TC, FC
116/// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117/// To something like:
118/// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
119/// Or:
120/// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121/// With some variations depending if FC is larger than TC, or the shift
122/// isn't needed, or the bit widths don't match.
123static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp,
124 InstCombiner::BuilderTy &Builder) {
125 const APInt *SelTC, *SelFC;
126 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127 !match(Sel.getFalseValue(), m_APInt(SelFC)))
128 return nullptr;
129
130 // If this is a vector select, we need a vector compare.
131 Type *SelType = Sel.getType();
132 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
133 return nullptr;
134
135 Value *V;
136 APInt AndMask;
137 bool CreateAnd = false;
138 ICmpInst::Predicate Pred = Cmp->getPredicate();
139 if (ICmpInst::isEquality(Pred)) {
140 if (!match(Cmp->getOperand(1), m_Zero()))
141 return nullptr;
142
143 V = Cmp->getOperand(0);
144 const APInt *AndRHS;
145 if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
146 return nullptr;
147
148 AndMask = *AndRHS;
149 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
150 Pred, V, AndMask)) {
151 assert(ICmpInst::isEquality(Pred) && "Not equality test?")((ICmpInst::isEquality(Pred) && "Not equality test?")
? static_cast<void> (0) : __assert_fail ("ICmpInst::isEquality(Pred) && \"Not equality test?\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 151, __PRETTY_FUNCTION__))
;
152 if (!AndMask.isPowerOf2())
153 return nullptr;
154
155 CreateAnd = true;
156 } else {
157 return nullptr;
158 }
159
160 // In general, when both constants are non-zero, we would need an offset to
161 // replace the select. This would require more instructions than we started
162 // with. But there's one special-case that we handle here because it can
163 // simplify/reduce the instructions.
164 APInt TC = *SelTC;
165 APInt FC = *SelFC;
166 if (!TC.isNullValue() && !FC.isNullValue()) {
167 // If the select constants differ by exactly one bit and that's the same
168 // bit that is masked and checked by the select condition, the select can
169 // be replaced by bitwise logic to set/clear one bit of the constant result.
170 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
171 return nullptr;
172 if (CreateAnd) {
173 // If we have to create an 'and', then we must kill the cmp to not
174 // increase the instruction count.
175 if (!Cmp->hasOneUse())
176 return nullptr;
177 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
178 }
179 bool ExtraBitInTC = TC.ugt(FC);
180 if (Pred == ICmpInst::ICMP_EQ) {
181 // If the masked bit in V is clear, clear or set the bit in the result:
182 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184 Constant *C = ConstantInt::get(SelType, TC);
185 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
186 }
187 if (Pred == ICmpInst::ICMP_NE) {
188 // If the masked bit in V is set, set or clear the bit in the result:
189 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191 Constant *C = ConstantInt::get(SelType, FC);
192 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
193 }
194 llvm_unreachable("Only expecting equality predicates")::llvm::llvm_unreachable_internal("Only expecting equality predicates"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 194)
;
195 }
196
197 // Make sure one of the select arms is a power-of-2.
198 if (!TC.isPowerOf2() && !FC.isPowerOf2())
199 return nullptr;
200
201 // Determine which shift is needed to transform result of the 'and' into the
202 // desired result.
203 const APInt &ValC = !TC.isNullValue() ? TC : FC;
204 unsigned ValZeros = ValC.logBase2();
205 unsigned AndZeros = AndMask.logBase2();
206
207 // Insert the 'and' instruction on the input to the truncate.
208 if (CreateAnd)
209 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
210
211 // If types don't match, we can still convert the select by introducing a zext
212 // or a trunc of the 'and'.
213 if (ValZeros > AndZeros) {
214 V = Builder.CreateZExtOrTrunc(V, SelType);
215 V = Builder.CreateShl(V, ValZeros - AndZeros);
216 } else if (ValZeros < AndZeros) {
217 V = Builder.CreateLShr(V, AndZeros - ValZeros);
218 V = Builder.CreateZExtOrTrunc(V, SelType);
219 } else {
220 V = Builder.CreateZExtOrTrunc(V, SelType);
221 }
222
223 // Okay, now we know that everything is set up, we just don't know whether we
224 // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225 bool ShouldNotVal = !TC.isNullValue();
226 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
227 if (ShouldNotVal)
228 V = Builder.CreateXor(V, ValC);
229
230 return V;
231}
232
233/// We want to turn code that looks like this:
234/// %C = or %A, %B
235/// %D = select %cond, %C, %A
236/// into:
237/// %C = select %cond, %B, 0
238/// %D = or %A, %C
239///
240/// Assuming that the specified instruction is an operand to the select, return
241/// a bitmask indicating which operands of this instruction are foldable if they
242/// equal the other incoming value of the select.
243static unsigned getSelectFoldableOperands(BinaryOperator *I) {
244 switch (I->getOpcode()) {
245 case Instruction::Add:
246 case Instruction::Mul:
247 case Instruction::And:
248 case Instruction::Or:
249 case Instruction::Xor:
250 return 3; // Can fold through either operand.
251 case Instruction::Sub: // Can only fold on the amount subtracted.
252 case Instruction::Shl: // Can only fold on the shift amount.
253 case Instruction::LShr:
254 case Instruction::AShr:
255 return 1;
256 default:
257 return 0; // Cannot fold
258 }
259}
260
261/// For the same transformation as the previous function, return the identity
262/// constant that goes into the select.
263static APInt getSelectFoldableConstant(BinaryOperator *I) {
264 switch (I->getOpcode()) {
265 default: llvm_unreachable("This cannot happen!")::llvm::llvm_unreachable_internal("This cannot happen!", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 265)
;
266 case Instruction::Add:
267 case Instruction::Sub:
268 case Instruction::Or:
269 case Instruction::Xor:
270 case Instruction::Shl:
271 case Instruction::LShr:
272 case Instruction::AShr:
273 return APInt::getNullValue(I->getType()->getScalarSizeInBits());
274 case Instruction::And:
275 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
276 case Instruction::Mul:
277 return APInt(I->getType()->getScalarSizeInBits(), 1);
278 }
279}
280
281/// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
282Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
283 Instruction *FI) {
284 // Don't break up min/max patterns. The hasOneUse checks below prevent that
285 // for most cases, but vector min/max with bitcasts can be transformed. If the
286 // one-use restrictions are eased for other patterns, we still don't want to
287 // obfuscate min/max.
288 if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289 match(&SI, m_SMax(m_Value(), m_Value())) ||
290 match(&SI, m_UMin(m_Value(), m_Value())) ||
291 match(&SI, m_UMax(m_Value(), m_Value()))))
292 return nullptr;
293
294 // If this is a cast from the same type, merge.
295 Value *Cond = SI.getCondition();
296 Type *CondTy = Cond->getType();
297 if (TI->getNumOperands() == 1 && TI->isCast()) {
298 Type *FIOpndTy = FI->getOperand(0)->getType();
299 if (TI->getOperand(0)->getType() != FIOpndTy)
300 return nullptr;
301
302 // The select condition may be a vector. We may only change the operand
303 // type if the vector width remains the same (and matches the condition).
304 if (CondTy->isVectorTy()) {
305 if (!FIOpndTy->isVectorTy())
306 return nullptr;
307 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
308 return nullptr;
309
310 // TODO: If the backend knew how to deal with casts better, we could
311 // remove this limitation. For now, there's too much potential to create
312 // worse codegen by promoting the select ahead of size-altering casts
313 // (PR28160).
314 //
315 // Note that ValueTracking's matchSelectPattern() looks through casts
316 // without checking 'hasOneUse' when it matches min/max patterns, so this
317 // transform may end up happening anyway.
318 if (TI->getOpcode() != Instruction::BitCast &&
319 (!TI->hasOneUse() || !FI->hasOneUse()))
320 return nullptr;
321 } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
322 // TODO: The one-use restrictions for a scalar select could be eased if
323 // the fold of a select in visitLoadInst() was enhanced to match a pattern
324 // that includes a cast.
325 return nullptr;
326 }
327
328 // Fold this by inserting a select from the input values.
329 Value *NewSI =
330 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0),
331 SI.getName() + ".v", &SI);
332 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
333 TI->getType());
334 }
335
336 // Cond ? -X : -Y --> -(Cond ? X : Y)
337 Value *X, *Y;
338 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) &&
339 (TI->hasOneUse() || FI->hasOneUse())) {
340 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI);
341 // TODO: Remove the hack for the binop form when the unary op is optimized
342 // properly with all IR passes.
343 if (TI->getOpcode() != Instruction::FNeg)
344 return BinaryOperator::CreateFNegFMF(NewSel, cast<BinaryOperator>(TI));
345 return UnaryOperator::CreateFNeg(NewSel);
346 }
347
348 // Only handle binary operators (including two-operand getelementptr) with
349 // one-use here. As with the cast case above, it may be possible to relax the
350 // one-use constraint, but that needs be examined carefully since it may not
351 // reduce the total number of instructions.
352 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
353 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
354 !TI->hasOneUse() || !FI->hasOneUse())
355 return nullptr;
356
357 // Figure out if the operations have any operands in common.
358 Value *MatchOp, *OtherOpT, *OtherOpF;
359 bool MatchIsOpZero;
360 if (TI->getOperand(0) == FI->getOperand(0)) {
361 MatchOp = TI->getOperand(0);
362 OtherOpT = TI->getOperand(1);
363 OtherOpF = FI->getOperand(1);
364 MatchIsOpZero = true;
365 } else if (TI->getOperand(1) == FI->getOperand(1)) {
366 MatchOp = TI->getOperand(1);
367 OtherOpT = TI->getOperand(0);
368 OtherOpF = FI->getOperand(0);
369 MatchIsOpZero = false;
370 } else if (!TI->isCommutative()) {
371 return nullptr;
372 } else if (TI->getOperand(0) == FI->getOperand(1)) {
373 MatchOp = TI->getOperand(0);
374 OtherOpT = TI->getOperand(1);
375 OtherOpF = FI->getOperand(0);
376 MatchIsOpZero = true;
377 } else if (TI->getOperand(1) == FI->getOperand(0)) {
378 MatchOp = TI->getOperand(1);
379 OtherOpT = TI->getOperand(0);
380 OtherOpF = FI->getOperand(1);
381 MatchIsOpZero = true;
382 } else {
383 return nullptr;
384 }
385
386 // If the select condition is a vector, the operands of the original select's
387 // operands also must be vectors. This may not be the case for getelementptr
388 // for example.
389 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() ||
390 !OtherOpF->getType()->isVectorTy()))
391 return nullptr;
392
393 // If we reach here, they do have operations in common.
394 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF,
395 SI.getName() + ".v", &SI);
396 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
397 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
398 if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
399 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
400 NewBO->copyIRFlags(TI);
401 NewBO->andIRFlags(FI);
402 return NewBO;
403 }
404 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
405 auto *FGEP = cast<GetElementPtrInst>(FI);
406 Type *ElementType = TGEP->getResultElementType();
407 return TGEP->isInBounds() && FGEP->isInBounds()
408 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
409 : GetElementPtrInst::Create(ElementType, Op0, {Op1});
410 }
411 llvm_unreachable("Expected BinaryOperator or GEP")::llvm::llvm_unreachable_internal("Expected BinaryOperator or GEP"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 411)
;
412 return nullptr;
413}
414
415static bool isSelect01(const APInt &C1I, const APInt &C2I) {
416 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
417 return false;
418 return C1I.isOneValue() || C1I.isAllOnesValue() ||
419 C2I.isOneValue() || C2I.isAllOnesValue();
420}
421
422/// Try to fold the select into one of the operands to allow further
423/// optimization.
424Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
425 Value *FalseVal) {
426 // See the comment above GetSelectFoldableOperands for a description of the
427 // transformation we are doing here.
428 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
429 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
430 if (unsigned SFO = getSelectFoldableOperands(TVI)) {
431 unsigned OpToFold = 0;
432 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
433 OpToFold = 1;
434 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
435 OpToFold = 2;
436 }
437
438 if (OpToFold) {
439 APInt CI = getSelectFoldableConstant(TVI);
440 Value *OOp = TVI->getOperand(2-OpToFold);
441 // Avoid creating select between 2 constants unless it's selecting
442 // between 0, 1 and -1.
443 const APInt *OOpC;
444 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
445 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
446 Value *C = ConstantInt::get(OOp->getType(), CI);
447 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
448 NewSel->takeName(TVI);
449 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
450 FalseVal, NewSel);
451 BO->copyIRFlags(TVI);
452 return BO;
453 }
454 }
455 }
456 }
457 }
458
459 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
460 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
461 if (unsigned SFO = getSelectFoldableOperands(FVI)) {
462 unsigned OpToFold = 0;
463 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
464 OpToFold = 1;
465 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
466 OpToFold = 2;
467 }
468
469 if (OpToFold) {
470 APInt CI = getSelectFoldableConstant(FVI);
471 Value *OOp = FVI->getOperand(2-OpToFold);
472 // Avoid creating select between 2 constants unless it's selecting
473 // between 0, 1 and -1.
474 const APInt *OOpC;
475 bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
476 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
477 Value *C = ConstantInt::get(OOp->getType(), CI);
478 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
479 NewSel->takeName(FVI);
480 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
481 TrueVal, NewSel);
482 BO->copyIRFlags(FVI);
483 return BO;
484 }
485 }
486 }
487 }
488 }
489
490 return nullptr;
491}
492
493/// We want to turn:
494/// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
495/// into:
496/// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
497/// Note:
498/// Z may be 0 if lshr is missing.
499/// Worst-case scenario is that we will replace 5 instructions with 5 different
500/// instructions, but we got rid of select.
501static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
502 Value *TVal, Value *FVal,
503 InstCombiner::BuilderTy &Builder) {
504 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
505 Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
506 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
507 return nullptr;
508
509 // The TrueVal has general form of: and %B, 1
510 Value *B;
511 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
512 return nullptr;
513
514 // Where %B may be optionally shifted: lshr %X, %Z.
515 Value *X, *Z;
516 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
517 if (!HasShift)
518 X = B;
519
520 Value *Y;
521 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
522 return nullptr;
523
524 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
525 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
526 Constant *One = ConstantInt::get(SelType, 1);
527 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
528 Value *FullMask = Builder.CreateOr(Y, MaskB);
529 Value *MaskedX = Builder.CreateAnd(X, FullMask);
530 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
531 return new ZExtInst(ICmpNeZero, SelType);
532}
533
534/// We want to turn:
535/// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1
536/// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0
537/// into:
538/// ashr (X, Y)
539static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
540 Value *FalseVal,
541 InstCombiner::BuilderTy &Builder) {
542 ICmpInst::Predicate Pred = IC->getPredicate();
543 Value *CmpLHS = IC->getOperand(0);
544 Value *CmpRHS = IC->getOperand(1);
545 if (!CmpRHS->getType()->isIntOrIntVectorTy())
546 return nullptr;
547
548 Value *X, *Y;
549 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
550 if ((Pred != ICmpInst::ICMP_SGT ||
551 !match(CmpRHS,
552 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
553 (Pred != ICmpInst::ICMP_SLT ||
554 !match(CmpRHS,
555 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
556 return nullptr;
557
558 // Canonicalize so that ashr is in FalseVal.
559 if (Pred == ICmpInst::ICMP_SLT)
560 std::swap(TrueVal, FalseVal);
561
562 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) &&
563 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) &&
564 match(CmpLHS, m_Specific(X))) {
565 const auto *Ashr = cast<Instruction>(FalseVal);
566 // if lshr is not exact and ashr is, this new ashr must not be exact.
567 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact();
568 return Builder.CreateAShr(X, Y, IC->getName(), IsExact);
569 }
570
571 return nullptr;
572}
573
574/// We want to turn:
575/// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
576/// into:
577/// (or (shl (and X, C1), C3), Y)
578/// iff:
579/// C1 and C2 are both powers of 2
580/// where:
581/// C3 = Log(C2) - Log(C1)
582///
583/// This transform handles cases where:
584/// 1. The icmp predicate is inverted
585/// 2. The select operands are reversed
586/// 3. The magnitude of C2 and C1 are flipped
587static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
588 Value *FalseVal,
589 InstCombiner::BuilderTy &Builder) {
590 // Only handle integer compares. Also, if this is a vector select, we need a
591 // vector compare.
592 if (!TrueVal->getType()->isIntOrIntVectorTy() ||
593 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
594 return nullptr;
595
596 Value *CmpLHS = IC->getOperand(0);
597 Value *CmpRHS = IC->getOperand(1);
598
599 Value *V;
600 unsigned C1Log;
601 bool IsEqualZero;
602 bool NeedAnd = false;
603 if (IC->isEquality()) {
604 if (!match(CmpRHS, m_Zero()))
605 return nullptr;
606
607 const APInt *C1;
608 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
609 return nullptr;
610
611 V = CmpLHS;
612 C1Log = C1->logBase2();
613 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
614 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
615 IC->getPredicate() == ICmpInst::ICMP_SGT) {
616 // We also need to recognize (icmp slt (trunc (X)), 0) and
617 // (icmp sgt (trunc (X)), -1).
618 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
619 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
620 (!IsEqualZero && !match(CmpRHS, m_Zero())))
621 return nullptr;
622
623 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
624 return nullptr;
625
626 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
627 NeedAnd = true;
628 } else {
629 return nullptr;
630 }
631
632 const APInt *C2;
633 bool OrOnTrueVal = false;
634 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
635 if (!OrOnFalseVal)
636 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
637
638 if (!OrOnFalseVal && !OrOnTrueVal)
639 return nullptr;
640
641 Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
642
643 unsigned C2Log = C2->logBase2();
644
645 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
646 bool NeedShift = C1Log != C2Log;
647 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
648 V->getType()->getScalarSizeInBits();
649
650 // Make sure we don't create more instructions than we save.
651 Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
652 if ((NeedShift + NeedXor + NeedZExtTrunc) >
653 (IC->hasOneUse() + Or->hasOneUse()))
654 return nullptr;
655
656 if (NeedAnd) {
657 // Insert the AND instruction on the input to the truncate.
658 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
659 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
660 }
661
662 if (C2Log > C1Log) {
663 V = Builder.CreateZExtOrTrunc(V, Y->getType());
664 V = Builder.CreateShl(V, C2Log - C1Log);
665 } else if (C1Log > C2Log) {
666 V = Builder.CreateLShr(V, C1Log - C2Log);
667 V = Builder.CreateZExtOrTrunc(V, Y->getType());
668 } else
669 V = Builder.CreateZExtOrTrunc(V, Y->getType());
670
671 if (NeedXor)
672 V = Builder.CreateXor(V, *C2);
673
674 return Builder.CreateOr(V, Y);
675}
676
677/// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b).
678/// There are 8 commuted/swapped variants of this pattern.
679/// TODO: Also support a - UMIN(a,b) patterns.
680static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI,
681 const Value *TrueVal,
682 const Value *FalseVal,
683 InstCombiner::BuilderTy &Builder) {
684 ICmpInst::Predicate Pred = ICI->getPredicate();
685 if (!ICmpInst::isUnsigned(Pred))
686 return nullptr;
687
688 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
689 if (match(TrueVal, m_Zero())) {
690 Pred = ICmpInst::getInversePredicate(Pred);
691 std::swap(TrueVal, FalseVal);
692 }
693 if (!match(FalseVal, m_Zero()))
694 return nullptr;
695
696 Value *A = ICI->getOperand(0);
697 Value *B = ICI->getOperand(1);
698 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
699 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
700 std::swap(A, B);
701 Pred = ICmpInst::getSwappedPredicate(Pred);
702 }
703
704 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&(((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
"Unexpected isUnsigned predicate!") ? static_cast<void>
(0) : __assert_fail ("(Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && \"Unexpected isUnsigned predicate!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 705, __PRETTY_FUNCTION__))
705 "Unexpected isUnsigned predicate!")(((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
"Unexpected isUnsigned predicate!") ? static_cast<void>
(0) : __assert_fail ("(Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && \"Unexpected isUnsigned predicate!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 705, __PRETTY_FUNCTION__))
;
706
707 // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
708 bool IsNegative = false;
709 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
710 IsNegative = true;
711 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
712 return nullptr;
713
714 // If sub is used anywhere else, we wouldn't be able to eliminate it
715 // afterwards.
716 if (!TrueVal->hasOneUse())
717 return nullptr;
718
719 // (a > b) ? a - b : 0 -> usub.sat(a, b)
720 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
721 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
722 if (IsNegative)
723 Result = Builder.CreateNeg(Result);
724 return Result;
725}
726
727static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
728 InstCombiner::BuilderTy &Builder) {
729 if (!Cmp->hasOneUse())
730 return nullptr;
731
732 // Match unsigned saturated add with constant.
733 Value *Cmp0 = Cmp->getOperand(0);
734 Value *Cmp1 = Cmp->getOperand(1);
735 ICmpInst::Predicate Pred = Cmp->getPredicate();
736 Value *X;
737 const APInt *C, *CmpC;
738 if (Pred == ICmpInst::ICMP_ULT &&
739 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
740 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
741 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
742 return Builder.CreateBinaryIntrinsic(
743 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
744 }
745
746 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
747 // There are 8 commuted variants.
748 // Canonicalize -1 (saturated result) to true value of the select. Just
749 // swapping the compare operands is legal, because the selected value is the
750 // same in case of equality, so we can interchange u< and u<=.
751 if (match(FVal, m_AllOnes())) {
752 std::swap(TVal, FVal);
753 std::swap(Cmp0, Cmp1);
754 }
755 if (!match(TVal, m_AllOnes()))
756 return nullptr;
757
758 // Canonicalize predicate to 'ULT'.
759 if (Pred == ICmpInst::ICMP_UGT) {
760 Pred = ICmpInst::ICMP_ULT;
761 std::swap(Cmp0, Cmp1);
762 }
763 if (Pred != ICmpInst::ICMP_ULT)
764 return nullptr;
765
766 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
767 Value *Y;
768 if (match(Cmp0, m_Not(m_Value(X))) &&
769 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
770 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
771 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
772 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
773 }
774 // The 'not' op may be included in the sum but not the compare.
775 X = Cmp0;
776 Y = Cmp1;
777 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
778 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
779 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
780 BinaryOperator *BO = cast<BinaryOperator>(FVal);
781 return Builder.CreateBinaryIntrinsic(
782 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
783 }
784 // The overflow may be detected via the add wrapping round.
785 if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
786 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
787 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
788 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
789 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
790 }
791
792 return nullptr;
793}
794
795/// Fold the following code sequence:
796/// \code
797/// int a = ctlz(x & -x);
798// x ? 31 - a : a;
799/// \code
800///
801/// into:
802/// cttz(x)
803static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
804 Value *FalseVal,
805 InstCombiner::BuilderTy &Builder) {
806 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
807 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
808 return nullptr;
809
810 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
811 std::swap(TrueVal, FalseVal);
812
813 if (!match(FalseVal,
814 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
815 return nullptr;
816
817 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
818 return nullptr;
819
820 Value *X = ICI->getOperand(0);
821 auto *II = cast<IntrinsicInst>(TrueVal);
822 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
823 return nullptr;
824
825 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
826 II->getType());
827 return CallInst::Create(F, {X, II->getArgOperand(1)});
828}
829
830/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
831/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
832///
833/// For example, we can fold the following code sequence:
834/// \code
835/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
836/// %1 = icmp ne i32 %x, 0
837/// %2 = select i1 %1, i32 %0, i32 32
838/// \code
839///
840/// into:
841/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
842static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
843 InstCombiner::BuilderTy &Builder) {
844 ICmpInst::Predicate Pred = ICI->getPredicate();
845 Value *CmpLHS = ICI->getOperand(0);
846 Value *CmpRHS = ICI->getOperand(1);
847
848 // Check if the condition value compares a value for equality against zero.
849 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
850 return nullptr;
851
852 Value *Count = FalseVal;
853 Value *ValueOnZero = TrueVal;
854 if (Pred == ICmpInst::ICMP_NE)
855 std::swap(Count, ValueOnZero);
856
857 // Skip zero extend/truncate.
858 Value *V = nullptr;
859 if (match(Count, m_ZExt(m_Value(V))) ||
860 match(Count, m_Trunc(m_Value(V))))
861 Count = V;
862
863 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
864 // input to the cttz/ctlz is used as LHS for the compare instruction.
865 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
866 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
867 return nullptr;
868
869 IntrinsicInst *II = cast<IntrinsicInst>(Count);
870
871 // Check if the value propagated on zero is a constant number equal to the
872 // sizeof in bits of 'Count'.
873 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
874 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
875 // Explicitly clear the 'undef_on_zero' flag.
876 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
877 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
878 Builder.Insert(NewI);
879 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
880 }
881
882 // If the ValueOnZero is not the bitwidth, we can at least make use of the
883 // fact that the cttz/ctlz result will not be used if the input is zero, so
884 // it's okay to relax it to undef for that case.
885 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
886 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
887
888 return nullptr;
889}
890
891/// Return true if we find and adjust an icmp+select pattern where the compare
892/// is with a constant that can be incremented or decremented to match the
893/// minimum or maximum idiom.
894static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
895 ICmpInst::Predicate Pred = Cmp.getPredicate();
896 Value *CmpLHS = Cmp.getOperand(0);
897 Value *CmpRHS = Cmp.getOperand(1);
898 Value *TrueVal = Sel.getTrueValue();
899 Value *FalseVal = Sel.getFalseValue();
900
901 // We may move or edit the compare, so make sure the select is the only user.
902 const APInt *CmpC;
903 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
904 return false;
905
906 // These transforms only work for selects of integers or vector selects of
907 // integer vectors.
908 Type *SelTy = Sel.getType();
909 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
910 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
911 return false;
912
913 Constant *AdjustedRHS;
914 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
915 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
916 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
917 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
918 else
919 return false;
920
921 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
922 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
923 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
924 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
925 ; // Nothing to do here. Values match without any sign/zero extension.
926 }
927 // Types do not match. Instead of calculating this with mixed types, promote
928 // all to the larger type. This enables scalar evolution to analyze this
929 // expression.
930 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
931 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
932
933 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
934 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
935 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
936 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
937 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
938 CmpLHS = TrueVal;
939 AdjustedRHS = SextRHS;
940 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
941 SextRHS == TrueVal) {
942 CmpLHS = FalseVal;
943 AdjustedRHS = SextRHS;
944 } else if (Cmp.isUnsigned()) {
945 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
946 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
947 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
948 // zext + signed compare cannot be changed:
949 // 0xff <s 0x00, but 0x00ff >s 0x0000
950 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
951 CmpLHS = TrueVal;
952 AdjustedRHS = ZextRHS;
953 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
954 ZextRHS == TrueVal) {
955 CmpLHS = FalseVal;
956 AdjustedRHS = ZextRHS;
957 } else {
958 return false;
959 }
960 } else {
961 return false;
962 }
963 } else {
964 return false;
965 }
966
967 Pred = ICmpInst::getSwappedPredicate(Pred);
968 CmpRHS = AdjustedRHS;
969 std::swap(FalseVal, TrueVal);
970 Cmp.setPredicate(Pred);
971 Cmp.setOperand(0, CmpLHS);
972 Cmp.setOperand(1, CmpRHS);
973 Sel.setOperand(1, TrueVal);
974 Sel.setOperand(2, FalseVal);
975 Sel.swapProfMetadata();
976
977 // Move the compare instruction right before the select instruction. Otherwise
978 // the sext/zext value may be defined after the compare instruction uses it.
979 Cmp.moveBefore(&Sel);
980
981 return true;
982}
983
984/// If this is an integer min/max (icmp + select) with a constant operand,
985/// create the canonical icmp for the min/max operation and canonicalize the
986/// constant to the 'false' operand of the select:
987/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
988/// Note: if C1 != C2, this will change the icmp constant to the existing
989/// constant operand of the select.
990static Instruction *
991canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
992 InstCombiner::BuilderTy &Builder) {
993 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
994 return nullptr;
995
996 // Canonicalize the compare predicate based on whether we have min or max.
997 Value *LHS, *RHS;
998 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
999 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1000 return nullptr;
1001
1002 // Is this already canonical?
1003 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1004 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1005 Cmp.getPredicate() == CanonicalPred)
1006 return nullptr;
1007
1008 // Create the canonical compare and plug it into the select.
1009 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
1010
1011 // If the select operands did not change, we're done.
1012 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1013 return &Sel;
1014
1015 // If we are swapping the select operands, swap the metadata too.
1016 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&((Sel.getTrueValue() == RHS && Sel.getFalseValue() ==
LHS && "Unexpected results from matchSelectPattern")
? static_cast<void> (0) : __assert_fail ("Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && \"Unexpected results from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1017, __PRETTY_FUNCTION__))
1017 "Unexpected results from matchSelectPattern")((Sel.getTrueValue() == RHS && Sel.getFalseValue() ==
LHS && "Unexpected results from matchSelectPattern")
? static_cast<void> (0) : __assert_fail ("Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && \"Unexpected results from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1017, __PRETTY_FUNCTION__))
;
1018 Sel.swapValues();
1019 Sel.swapProfMetadata();
1020 return &Sel;
1021}
1022
1023/// There are many select variants for each of ABS/NABS.
1024/// In matchSelectPattern(), there are different compare constants, compare
1025/// predicates/operands and select operands.
1026/// In isKnownNegation(), there are different formats of negated operands.
1027/// Canonicalize all these variants to 1 pattern.
1028/// This makes CSE more likely.
1029static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1030 InstCombiner::BuilderTy &Builder) {
1031 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1032 return nullptr;
1033
1034 // Choose a sign-bit check for the compare (likely simpler for codegen).
1035 // ABS: (X <s 0) ? -X : X
1036 // NABS: (X <s 0) ? X : -X
1037 Value *LHS, *RHS;
1038 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1039 if (SPF != SelectPatternFlavor::SPF_ABS &&
1040 SPF != SelectPatternFlavor::SPF_NABS)
1041 return nullptr;
1042
1043 Value *TVal = Sel.getTrueValue();
1044 Value *FVal = Sel.getFalseValue();
1045 assert(isKnownNegation(TVal, FVal) &&((isKnownNegation(TVal, FVal) && "Unexpected result from matchSelectPattern"
) ? static_cast<void> (0) : __assert_fail ("isKnownNegation(TVal, FVal) && \"Unexpected result from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1046, __PRETTY_FUNCTION__))
1046 "Unexpected result from matchSelectPattern")((isKnownNegation(TVal, FVal) && "Unexpected result from matchSelectPattern"
) ? static_cast<void> (0) : __assert_fail ("isKnownNegation(TVal, FVal) && \"Unexpected result from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1046, __PRETTY_FUNCTION__))
;
1047
1048 // The compare may use the negated abs()/nabs() operand, or it may use
1049 // negation in non-canonical form such as: sub A, B.
1050 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1051 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1052
1053 bool CmpCanonicalized = !CmpUsesNegatedOp &&
1054 match(Cmp.getOperand(1), m_ZeroInt()) &&
1055 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1056 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1057
1058 // Is this already canonical?
1059 if (CmpCanonicalized && RHSCanonicalized)
1060 return nullptr;
1061
1062 // If RHS is used by other instructions except compare and select, don't
1063 // canonicalize it to not increase the instruction count.
1064 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1065 return nullptr;
1066
1067 // Create the canonical compare: icmp slt LHS 0.
1068 if (!CmpCanonicalized) {
1069 Cmp.setPredicate(ICmpInst::ICMP_SLT);
1070 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1071 if (CmpUsesNegatedOp)
1072 Cmp.setOperand(0, LHS);
1073 }
1074
1075 // Create the canonical RHS: RHS = sub (0, LHS).
1076 if (!RHSCanonicalized) {
1077 assert(RHS->hasOneUse() && "RHS use number is not right")((RHS->hasOneUse() && "RHS use number is not right"
) ? static_cast<void> (0) : __assert_fail ("RHS->hasOneUse() && \"RHS use number is not right\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1077, __PRETTY_FUNCTION__))
;
1078 RHS = Builder.CreateNeg(LHS);
1079 if (TVal == LHS) {
1080 Sel.setFalseValue(RHS);
1081 FVal = RHS;
1082 } else {
1083 Sel.setTrueValue(RHS);
1084 TVal = RHS;
1085 }
1086 }
1087
1088 // If the select operands do not change, we're done.
1089 if (SPF == SelectPatternFlavor::SPF_NABS) {
1090 if (TVal == LHS)
1091 return &Sel;
1092 assert(FVal == LHS && "Unexpected results from matchSelectPattern")((FVal == LHS && "Unexpected results from matchSelectPattern"
) ? static_cast<void> (0) : __assert_fail ("FVal == LHS && \"Unexpected results from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1092, __PRETTY_FUNCTION__))
;
1093 } else {
1094 if (FVal == LHS)
1095 return &Sel;
1096 assert(TVal == LHS && "Unexpected results from matchSelectPattern")((TVal == LHS && "Unexpected results from matchSelectPattern"
) ? static_cast<void> (0) : __assert_fail ("TVal == LHS && \"Unexpected results from matchSelectPattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1096, __PRETTY_FUNCTION__))
;
1097 }
1098
1099 // We are swapping the select operands, so swap the metadata too.
1100 Sel.swapValues();
1101 Sel.swapProfMetadata();
1102 return &Sel;
1103}
1104
1105static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp,
1106 const SimplifyQuery &Q) {
1107 // If this is a binary operator, try to simplify it with the replaced op
1108 // because we know Op and ReplaceOp are equivalant.
1109 // For example: V = X + 1, Op = X, ReplaceOp = 42
1110 // Simplifies as: add(42, 1) --> 43
1111 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1112 if (BO->getOperand(0) == Op)
1113 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q);
1114 if (BO->getOperand(1) == Op)
1115 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q);
1116 }
1117
1118 return nullptr;
1119}
1120
1121/// If we have a select with an equality comparison, then we know the value in
1122/// one of the arms of the select. See if substituting this value into an arm
1123/// and simplifying the result yields the same value as the other arm.
1124///
1125/// To make this transform safe, we must drop poison-generating flags
1126/// (nsw, etc) if we simplified to a binop because the select may be guarding
1127/// that poison from propagating. If the existing binop already had no
1128/// poison-generating flags, then this transform can be done by instsimplify.
1129///
1130/// Consider:
1131/// %cmp = icmp eq i32 %x, 2147483647
1132/// %add = add nsw i32 %x, 1
1133/// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1134///
1135/// We can't replace %sel with %add unless we strip away the flags.
1136/// TODO: Wrapping flags could be preserved in some cases with better analysis.
1137static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
1138 const SimplifyQuery &Q) {
1139 if (!Cmp.isEquality())
1140 return nullptr;
1141
1142 // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1143 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1144 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1145 std::swap(TrueVal, FalseVal);
1146
1147 // Try each equivalence substitution possibility.
1148 // We have an 'EQ' comparison, so the select's false value will propagate.
1149 // Example:
1150 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1151 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43
1152 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1153 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal ||
1154 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal ||
1155 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal ||
1156 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) {
1157 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal))
1158 FalseInst->dropPoisonGeneratingFlags();
1159 return FalseVal;
1160 }
1161 return nullptr;
1162}
1163
1164// See if this is a pattern like:
1165// %old_cmp1 = icmp slt i32 %x, C2
1166// %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1167// %old_x_offseted = add i32 %x, C1
1168// %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1169// %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1170// This can be rewritten as more canonical pattern:
1171// %new_cmp1 = icmp slt i32 %x, -C1
1172// %new_cmp2 = icmp sge i32 %x, C0-C1
1173// %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1174// %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1175// Iff -C1 s<= C2 s<= C0-C1
1176// Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1177// SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1178static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1179 InstCombiner::BuilderTy &Builder) {
1180 Value *X = Sel0.getTrueValue();
1181 Value *Sel1 = Sel0.getFalseValue();
1182
1183 // First match the condition of the outermost select.
1184 // Said condition must be one-use.
1185 if (!Cmp0.hasOneUse())
1186 return nullptr;
1187 Value *Cmp00 = Cmp0.getOperand(0);
1188 Constant *C0;
1189 if (!match(Cmp0.getOperand(1),
1190 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1191 return nullptr;
1192 // Canonicalize Cmp0 into the form we expect.
1193 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1194 switch (Cmp0.getPredicate()) {
1195 case ICmpInst::Predicate::ICMP_ULT:
1196 break; // Great!
1197 case ICmpInst::Predicate::ICMP_ULE:
1198 // We'd have to increment C0 by one, and for that it must not have all-ones
1199 // element, but then it would have been canonicalized to 'ult' before
1200 // we get here. So we can't do anything useful with 'ule'.
1201 return nullptr;
1202 case ICmpInst::Predicate::ICMP_UGT:
1203 // We want to canonicalize it to 'ult', so we'll need to increment C0,
1204 // which again means it must not have any all-ones elements.
1205 if (!match(C0,
1206 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1207 APInt::getAllOnesValue(
1208 C0->getType()->getScalarSizeInBits()))))
1209 return nullptr; // Can't do, have all-ones element[s].
1210 C0 = AddOne(C0);
1211 std::swap(X, Sel1);
1212 break;
1213 case ICmpInst::Predicate::ICMP_UGE:
1214 // The only way we'd get this predicate if this `icmp` has extra uses,
1215 // but then we won't be able to do this fold.
1216 return nullptr;
1217 default:
1218 return nullptr; // Unknown predicate.
1219 }
1220
1221 // Now that we've canonicalized the ICmp, we know the X we expect;
1222 // the select in other hand should be one-use.
1223 if (!Sel1->hasOneUse())
1224 return nullptr;
1225
1226 // We now can finish matching the condition of the outermost select:
1227 // it should either be the X itself, or an addition of some constant to X.
1228 Constant *C1;
1229 if (Cmp00 == X)
1230 C1 = ConstantInt::getNullValue(Sel0.getType());
1231 else if (!match(Cmp00,
1232 m_Add(m_Specific(X),
1233 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1234 return nullptr;
1235
1236 Value *Cmp1;
1237 ICmpInst::Predicate Pred1;
1238 Constant *C2;
1239 Value *ReplacementLow, *ReplacementHigh;
1240 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1241 m_Value(ReplacementHigh))) ||
1242 !match(Cmp1,
1243 m_ICmp(Pred1, m_Specific(X),
1244 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1245 return nullptr;
1246
1247 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1248 return nullptr; // Not enough one-use instructions for the fold.
1249 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1250 // two comparisons we'll need to build.
1251
1252 // Canonicalize Cmp1 into the form we expect.
1253 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1254 switch (Pred1) {
1255 case ICmpInst::Predicate::ICMP_SLT:
1256 break;
1257 case ICmpInst::Predicate::ICMP_SLE:
1258 // We'd have to increment C2 by one, and for that it must not have signed
1259 // max element, but then it would have been canonicalized to 'slt' before
1260 // we get here. So we can't do anything useful with 'sle'.
1261 return nullptr;
1262 case ICmpInst::Predicate::ICMP_SGT:
1263 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1264 // which again means it must not have any signed max elements.
1265 if (!match(C2,
1266 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1267 APInt::getSignedMaxValue(
1268 C2->getType()->getScalarSizeInBits()))))
1269 return nullptr; // Can't do, have signed max element[s].
1270 C2 = AddOne(C2);
1271 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1272 case ICmpInst::Predicate::ICMP_SGE:
1273 // Also non-canonical, but here we don't need to change C2,
1274 // so we don't have any restrictions on C2, so we can just handle it.
1275 std::swap(ReplacementLow, ReplacementHigh);
1276 break;
1277 default:
1278 return nullptr; // Unknown predicate.
1279 }
1280
1281 // The thresholds of this clamp-like pattern.
1282 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1283 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1284
1285 // The fold has a precondition 1: C2 s>= ThresholdLow
1286 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1287 ThresholdLowIncl);
1288 if (!match(Precond1, m_One()))
1289 return nullptr;
1290 // The fold has a precondition 2: C2 s<= ThresholdHigh
1291 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1292 ThresholdHighExcl);
1293 if (!match(Precond2, m_One()))
1294 return nullptr;
1295
1296 // All good, finally emit the new pattern.
1297 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1298 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1299 Value *MaybeReplacedLow =
1300 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1301 Instruction *MaybeReplacedHigh =
1302 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1303
1304 return MaybeReplacedHigh;
1305}
1306
1307// If we have
1308// %cmp = icmp [canonical predicate] i32 %x, C0
1309// %r = select i1 %cmp, i32 %y, i32 C1
1310// Where C0 != C1 and %x may be different from %y, see if the constant that we
1311// will have if we flip the strictness of the predicate (i.e. without changing
1312// the result) is identical to the C1 in select. If it matches we can change
1313// original comparison to one with swapped predicate, reuse the constant,
1314// and swap the hands of select.
1315static Instruction *
1316tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1317 InstCombiner::BuilderTy &Builder) {
1318 ICmpInst::Predicate Pred;
1319 Value *X;
1320 Constant *C0;
1321 if (!match(&Cmp, m_OneUse(m_ICmp(
1322 Pred, m_Value(X),
1323 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1324 return nullptr;
1325
1326 // If comparison predicate is non-relational, we won't be able to do anything.
1327 if (ICmpInst::isEquality(Pred))
1328 return nullptr;
1329
1330 // If comparison predicate is non-canonical, then we certainly won't be able
1331 // to make it canonical; canonicalizeCmpWithConstant() already tried.
1332 if (!isCanonicalPredicate(Pred))
1333 return nullptr;
1334
1335 // If the [input] type of comparison and select type are different, lets abort
1336 // for now. We could try to compare constants with trunc/[zs]ext though.
1337 if (C0->getType() != Sel.getType())
1338 return nullptr;
1339
1340 // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1341
1342 Value *SelVal0, *SelVal1; // We do not care which one is from where.
1343 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1344 // At least one of these values we are selecting between must be a constant
1345 // else we'll never succeed.
1346 if (!match(SelVal0, m_AnyIntegralConstant()) &&
1347 !match(SelVal1, m_AnyIntegralConstant()))
1348 return nullptr;
1349
1350 // Does this constant C match any of the `select` values?
1351 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1352 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1353 };
1354
1355 // If C0 *already* matches true/false value of select, we are done.
1356 if (MatchesSelectValue(C0))
1357 return nullptr;
1358
1359 // Check the constant we'd have with flipped-strictness predicate.
1360 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
1361 if (!FlippedStrictness)
1362 return nullptr;
1363
1364 // If said constant doesn't match either, then there is no hope,
1365 if (!MatchesSelectValue(FlippedStrictness->second))
1366 return nullptr;
1367
1368 // It matched! Lets insert the new comparison just before select.
1369 InstCombiner::BuilderTy::InsertPointGuard Guard(Builder);
1370 Builder.SetInsertPoint(&Sel);
1371
1372 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1373 Value *NewCmp = Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1374 Cmp.getName() + ".inv");
1375 Sel.setCondition(NewCmp);
1376 Sel.swapValues();
1377 Sel.swapProfMetadata();
1378
1379 return &Sel;
1380}
1381
1382/// Visit a SelectInst that has an ICmpInst as its first operand.
1383Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1384 ICmpInst *ICI) {
1385 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
1386 return replaceInstUsesWith(SI, V);
1387
1388 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
1389 return NewSel;
1390
1391 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
1392 return NewAbs;
1393
1394 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1395 return NewAbs;
1396
1397 if (Instruction *NewSel =
1398 tryToReuseConstantFromSelectInComparison(SI, *ICI, Builder))
1399 return NewSel;
1400
1401 bool Changed = adjustMinMax(SI, *ICI);
1402
1403 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1404 return replaceInstUsesWith(SI, V);
1405
1406 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1407 Value *TrueVal = SI.getTrueValue();
1408 Value *FalseVal = SI.getFalseValue();
1409 ICmpInst::Predicate Pred = ICI->getPredicate();
1410 Value *CmpLHS = ICI->getOperand(0);
1411 Value *CmpRHS = ICI->getOperand(1);
1412 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1413 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1414 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1415 SI.setOperand(1, CmpRHS);
1416 Changed = true;
1417 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1418 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1419 SI.setOperand(2, CmpRHS);
1420 Changed = true;
1421 }
1422 }
1423
1424 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1425 // decomposeBitTestICmp() might help.
1426 {
1427 unsigned BitWidth =
1428 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1429 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1430 Value *X;
1431 const APInt *Y, *C;
1432 bool TrueWhenUnset;
1433 bool IsBitTest = false;
1434 if (ICmpInst::isEquality(Pred) &&
1435 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1436 match(CmpRHS, m_Zero())) {
1437 IsBitTest = true;
1438 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1439 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1440 X = CmpLHS;
1441 Y = &MinSignedValue;
1442 IsBitTest = true;
1443 TrueWhenUnset = false;
1444 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1445 X = CmpLHS;
1446 Y = &MinSignedValue;
1447 IsBitTest = true;
1448 TrueWhenUnset = true;
1449 }
1450 if (IsBitTest) {
1451 Value *V = nullptr;
1452 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1453 if (TrueWhenUnset && TrueVal == X &&
1454 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1455 V = Builder.CreateAnd(X, ~(*Y));
1456 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1457 else if (!TrueWhenUnset && FalseVal == X &&
1458 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1459 V = Builder.CreateAnd(X, ~(*Y));
1460 // (X & Y) == 0 ? X ^ Y : X --> X | Y
1461 else if (TrueWhenUnset && FalseVal == X &&
1462 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1463 V = Builder.CreateOr(X, *Y);
1464 // (X & Y) != 0 ? X : X ^ Y --> X | Y
1465 else if (!TrueWhenUnset && TrueVal == X &&
1466 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1467 V = Builder.CreateOr(X, *Y);
1468
1469 if (V)
1470 return replaceInstUsesWith(SI, V);
1471 }
1472 }
1473
1474 if (Instruction *V =
1475 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1476 return V;
1477
1478 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1479 return V;
1480
1481 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1482 return replaceInstUsesWith(SI, V);
1483
1484 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1485 return replaceInstUsesWith(SI, V);
1486
1487 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1488 return replaceInstUsesWith(SI, V);
1489
1490 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1491 return replaceInstUsesWith(SI, V);
1492
1493 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1494 return replaceInstUsesWith(SI, V);
1495
1496 return Changed ? &SI : nullptr;
1497}
1498
1499/// SI is a select whose condition is a PHI node (but the two may be in
1500/// different blocks). See if the true/false values (V) are live in all of the
1501/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1502///
1503/// X = phi [ C1, BB1], [C2, BB2]
1504/// Y = add
1505/// Z = select X, Y, 0
1506///
1507/// because Y is not live in BB1/BB2.
1508static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1509 const SelectInst &SI) {
1510 // If the value is a non-instruction value like a constant or argument, it
1511 // can always be mapped.
1512 const Instruction *I = dyn_cast<Instruction>(V);
1513 if (!I) return true;
1514
1515 // If V is a PHI node defined in the same block as the condition PHI, we can
1516 // map the arguments.
1517 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1518
1519 if (const PHINode *VP = dyn_cast<PHINode>(I))
1520 if (VP->getParent() == CondPHI->getParent())
1521 return true;
1522
1523 // Otherwise, if the PHI and select are defined in the same block and if V is
1524 // defined in a different block, then we can transform it.
1525 if (SI.getParent() == CondPHI->getParent() &&
1526 I->getParent() != CondPHI->getParent())
1527 return true;
1528
1529 // Otherwise we have a 'hard' case and we can't tell without doing more
1530 // detailed dominator based analysis, punt.
1531 return false;
1532}
1533
1534/// We have an SPF (e.g. a min or max) of an SPF of the form:
1535/// SPF2(SPF1(A, B), C)
1536Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1537 SelectPatternFlavor SPF1,
1538 Value *A, Value *B,
1539 Instruction &Outer,
1540 SelectPatternFlavor SPF2, Value *C) {
1541 if (Outer.getType() != Inner->getType())
1542 return nullptr;
1543
1544 if (C == A || C == B) {
1545 // MAX(MAX(A, B), B) -> MAX(A, B)
1546 // MIN(MIN(a, b), a) -> MIN(a, b)
1547 // TODO: This could be done in instsimplify.
1548 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1549 return replaceInstUsesWith(Outer, Inner);
1550
1551 // MAX(MIN(a, b), a) -> a
1552 // MIN(MAX(a, b), a) -> a
1553 // TODO: This could be done in instsimplify.
1554 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1555 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1556 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1557 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1558 return replaceInstUsesWith(Outer, C);
1559 }
1560
1561 if (SPF1 == SPF2) {
1562 const APInt *CB, *CC;
1563 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1564 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1565 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1566 // TODO: This could be done in instsimplify.
1567 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1568 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1569 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1570 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1571 return replaceInstUsesWith(Outer, Inner);
1572
1573 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1574 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1575 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1576 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1577 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1578 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1579 Outer.replaceUsesOfWith(Inner, A);
1580 return &Outer;
1581 }
1582 }
1583 }
1584
1585 // max(max(A, B), min(A, B)) --> max(A, B)
1586 // min(min(A, B), max(A, B)) --> min(A, B)
1587 // TODO: This could be done in instsimplify.
1588 if (SPF1 == SPF2 &&
1589 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1590 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1591 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1592 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1593 return replaceInstUsesWith(Outer, Inner);
1594
1595 // ABS(ABS(X)) -> ABS(X)
1596 // NABS(NABS(X)) -> NABS(X)
1597 // TODO: This could be done in instsimplify.
1598 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1599 return replaceInstUsesWith(Outer, Inner);
1600 }
1601
1602 // ABS(NABS(X)) -> ABS(X)
1603 // NABS(ABS(X)) -> NABS(X)
1604 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1605 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1606 SelectInst *SI = cast<SelectInst>(Inner);
1607 Value *NewSI =
1608 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1609 SI->getTrueValue(), SI->getName(), SI);
1610 return replaceInstUsesWith(Outer, NewSI);
1611 }
1612
1613 auto IsFreeOrProfitableToInvert =
1614 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1615 if (match(V, m_Not(m_Value(NotV)))) {
1616 // If V has at most 2 uses then we can get rid of the xor operation
1617 // entirely.
1618 ElidesXor |= !V->hasNUsesOrMore(3);
1619 return true;
1620 }
1621
1622 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1623 NotV = nullptr;
1624 return true;
1625 }
1626
1627 return false;
1628 };
1629
1630 Value *NotA, *NotB, *NotC;
1631 bool ElidesXor = false;
1632
1633 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1634 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1635 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1636 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1637 //
1638 // This transform is performance neutral if we can elide at least one xor from
1639 // the set of three operands, since we'll be tacking on an xor at the very
1640 // end.
1641 if (SelectPatternResult::isMinOrMax(SPF1) &&
1642 SelectPatternResult::isMinOrMax(SPF2) &&
1643 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1644 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1645 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1646 if (!NotA)
1647 NotA = Builder.CreateNot(A);
1648 if (!NotB)
1649 NotB = Builder.CreateNot(B);
1650 if (!NotC)
1651 NotC = Builder.CreateNot(C);
1652
1653 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1654 NotB);
1655 Value *NewOuter = Builder.CreateNot(
1656 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1657 return replaceInstUsesWith(Outer, NewOuter);
1658 }
1659
1660 return nullptr;
1661}
1662
1663/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1664/// This is even legal for FP.
1665static Instruction *foldAddSubSelect(SelectInst &SI,
1666 InstCombiner::BuilderTy &Builder) {
1667 Value *CondVal = SI.getCondition();
1668 Value *TrueVal = SI.getTrueValue();
1669 Value *FalseVal = SI.getFalseValue();
1670 auto *TI = dyn_cast<Instruction>(TrueVal);
1671 auto *FI = dyn_cast<Instruction>(FalseVal);
1672 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1673 return nullptr;
1674
1675 Instruction *AddOp = nullptr, *SubOp = nullptr;
1676 if ((TI->getOpcode() == Instruction::Sub &&
1677 FI->getOpcode() == Instruction::Add) ||
1678 (TI->getOpcode() == Instruction::FSub &&
1679 FI->getOpcode() == Instruction::FAdd)) {
1680 AddOp = FI;
1681 SubOp = TI;
1682 } else if ((FI->getOpcode() == Instruction::Sub &&
1683 TI->getOpcode() == Instruction::Add) ||
1684 (FI->getOpcode() == Instruction::FSub &&
1685 TI->getOpcode() == Instruction::FAdd)) {
1686 AddOp = TI;
1687 SubOp = FI;
1688 }
1689
1690 if (AddOp) {
1691 Value *OtherAddOp = nullptr;
1692 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1693 OtherAddOp = AddOp->getOperand(1);
1694 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1695 OtherAddOp = AddOp->getOperand(0);
1696 }
1697
1698 if (OtherAddOp) {
1699 // So at this point we know we have (Y -> OtherAddOp):
1700 // select C, (add X, Y), (sub X, Z)
1701 Value *NegVal; // Compute -Z
1702 if (SI.getType()->isFPOrFPVectorTy()) {
1703 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1704 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1705 FastMathFlags Flags = AddOp->getFastMathFlags();
1706 Flags &= SubOp->getFastMathFlags();
1707 NegInst->setFastMathFlags(Flags);
1708 }
1709 } else {
1710 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1711 }
1712
1713 Value *NewTrueOp = OtherAddOp;
1714 Value *NewFalseOp = NegVal;
1715 if (AddOp != TI)
1716 std::swap(NewTrueOp, NewFalseOp);
1717 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1718 SI.getName() + ".p", &SI);
1719
1720 if (SI.getType()->isFPOrFPVectorTy()) {
1721 Instruction *RI =
1722 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1723
1724 FastMathFlags Flags = AddOp->getFastMathFlags();
1725 Flags &= SubOp->getFastMathFlags();
1726 RI->setFastMathFlags(Flags);
1727 return RI;
1728 } else
1729 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1730 }
1731 }
1732 return nullptr;
1733}
1734
1735/// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1736/// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1737static Instruction *
1738foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1739 Value *CondVal = SI.getCondition();
1740 Value *TrueVal = SI.getTrueValue();
1741 Value *FalseVal = SI.getFalseValue();
1742
1743 WithOverflowInst *II;
1744 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1745 !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1746 return nullptr;
1747
1748 Intrinsic::ID NewIntrinsicID;
1749 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1750 match(TrueVal, m_AllOnes()))
1751 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1752 NewIntrinsicID = Intrinsic::uadd_sat;
1753 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1754 match(TrueVal, m_Zero()))
1755 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1756 NewIntrinsicID = Intrinsic::usub_sat;
1757 else
1758 return nullptr;
1759
1760 Function *F =
1761 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1762 return CallInst::Create(F, {II->getArgOperand(0), II->getArgOperand(1)});
1763}
1764
1765Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1766 Constant *C;
1767 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1768 !match(Sel.getFalseValue(), m_Constant(C)))
1769 return nullptr;
1770
1771 Instruction *ExtInst;
1772 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1773 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1774 return nullptr;
1775
1776 auto ExtOpcode = ExtInst->getOpcode();
1777 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1778 return nullptr;
1779
1780 // If we are extending from a boolean type or if we can create a select that
1781 // has the same size operands as its condition, try to narrow the select.
1782 Value *X = ExtInst->getOperand(0);
1783 Type *SmallType = X->getType();
1784 Value *Cond = Sel.getCondition();
1785 auto *Cmp = dyn_cast<CmpInst>(Cond);
1786 if (!SmallType->isIntOrIntVectorTy(1) &&
1787 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1788 return nullptr;
1789
1790 // If the constant is the same after truncation to the smaller type and
1791 // extension to the original type, we can narrow the select.
1792 Type *SelType = Sel.getType();
1793 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1794 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1795 if (ExtC == C) {
1796 Value *TruncCVal = cast<Value>(TruncC);
1797 if (ExtInst == Sel.getFalseValue())
1798 std::swap(X, TruncCVal);
1799
1800 // select Cond, (ext X), C --> ext(select Cond, X, C')
1801 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1802 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1803 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1804 }
1805
1806 // If one arm of the select is the extend of the condition, replace that arm
1807 // with the extension of the appropriate known bool value.
1808 if (Cond == X) {
1809 if (ExtInst == Sel.getTrueValue()) {
1810 // select X, (sext X), C --> select X, -1, C
1811 // select X, (zext X), C --> select X, 1, C
1812 Constant *One = ConstantInt::getTrue(SmallType);
1813 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1814 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1815 } else {
1816 // select X, C, (sext X) --> select X, C, 0
1817 // select X, C, (zext X) --> select X, C, 0
1818 Constant *Zero = ConstantInt::getNullValue(SelType);
1819 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1820 }
1821 }
1822
1823 return nullptr;
1824}
1825
1826/// Try to transform a vector select with a constant condition vector into a
1827/// shuffle for easier combining with other shuffles and insert/extract.
1828static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1829 Value *CondVal = SI.getCondition();
1830 Constant *CondC;
1831 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
8
Taking true branch
1832 return nullptr;
9
Returning null pointer, which participates in a condition later
1833
1834 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1835 SmallVector<Constant *, 16> Mask;
1836 Mask.reserve(NumElts);
1837 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1838 for (unsigned i = 0; i != NumElts; ++i) {
1839 Constant *Elt = CondC->getAggregateElement(i);
1840 if (!Elt)
1841 return nullptr;
1842
1843 if (Elt->isOneValue()) {
1844 // If the select condition element is true, choose from the 1st vector.
1845 Mask.push_back(ConstantInt::get(Int32Ty, i));
1846 } else if (Elt->isNullValue()) {
1847 // If the select condition element is false, choose from the 2nd vector.
1848 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1849 } else if (isa<UndefValue>(Elt)) {
1850 // Undef in a select condition (choose one of the operands) does not mean
1851 // the same thing as undef in a shuffle mask (any value is acceptable), so
1852 // give up.
1853 return nullptr;
1854 } else {
1855 // Bail out on a constant expression.
1856 return nullptr;
1857 }
1858 }
1859
1860 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1861 ConstantVector::get(Mask));
1862}
1863
1864/// If we have a select of vectors with a scalar condition, try to convert that
1865/// to a vector select by splatting the condition. A splat may get folded with
1866/// other operations in IR and having all operands of a select be vector types
1867/// is likely better for vector codegen.
1868static Instruction *canonicalizeScalarSelectOfVecs(
1869 SelectInst &Sel, InstCombiner::BuilderTy &Builder) {
1870 Type *Ty = Sel.getType();
1871 if (!Ty->isVectorTy())
13
Calling 'Type::isVectorTy'
16
Returning from 'Type::isVectorTy'
17
Taking true branch
1872 return nullptr;
18
Returning null pointer, which participates in a condition later
1873
1874 // We can replace a single-use extract with constant index.
1875 Value *Cond = Sel.getCondition();
1876 if (!match(Cond, m_OneUse(m_ExtractElement(m_Value(), m_ConstantInt()))))
1877 return nullptr;
1878
1879 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
1880 // Splatting the extracted condition reduces code (we could directly create a
1881 // splat shuffle of the source vector to eliminate the intermediate step).
1882 unsigned NumElts = Ty->getVectorNumElements();
1883 Value *SplatCond = Builder.CreateVectorSplat(NumElts, Cond);
1884 Sel.setCondition(SplatCond);
1885 return &Sel;
1886}
1887
1888/// Reuse bitcasted operands between a compare and select:
1889/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1890/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1891static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1892 InstCombiner::BuilderTy &Builder) {
1893 Value *Cond = Sel.getCondition();
1894 Value *TVal = Sel.getTrueValue();
1895 Value *FVal = Sel.getFalseValue();
1896
1897 CmpInst::Predicate Pred;
1898 Value *A, *B;
1899 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1900 return nullptr;
1901
1902 // The select condition is a compare instruction. If the select's true/false
1903 // values are already the same as the compare operands, there's nothing to do.
1904 if (TVal == A || TVal == B || FVal == A || FVal == B)
1905 return nullptr;
1906
1907 Value *C, *D;
1908 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1909 return nullptr;
1910
1911 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1912 Value *TSrc, *FSrc;
1913 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1914 !match(FVal, m_BitCast(m_Value(FSrc))))
1915 return nullptr;
1916
1917 // If the select true/false values are *different bitcasts* of the same source
1918 // operands, make the select operands the same as the compare operands and
1919 // cast the result. This is the canonical select form for min/max.
1920 Value *NewSel;
1921 if (TSrc == C && FSrc == D) {
1922 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1923 // bitcast (select (cmp A, B), A, B)
1924 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1925 } else if (TSrc == D && FSrc == C) {
1926 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1927 // bitcast (select (cmp A, B), B, A)
1928 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1929 } else {
1930 return nullptr;
1931 }
1932 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1933}
1934
1935/// Try to eliminate select instructions that test the returned flag of cmpxchg
1936/// instructions.
1937///
1938/// If a select instruction tests the returned flag of a cmpxchg instruction and
1939/// selects between the returned value of the cmpxchg instruction its compare
1940/// operand, the result of the select will always be equal to its false value.
1941/// For example:
1942///
1943/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1944/// %1 = extractvalue { i64, i1 } %0, 1
1945/// %2 = extractvalue { i64, i1 } %0, 0
1946/// %3 = select i1 %1, i64 %compare, i64 %2
1947/// ret i64 %3
1948///
1949/// The returned value of the cmpxchg instruction (%2) is the original value
1950/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1951/// must have been equal to %compare. Thus, the result of the select is always
1952/// equal to %2, and the code can be simplified to:
1953///
1954/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1955/// %1 = extractvalue { i64, i1 } %0, 0
1956/// ret i64 %1
1957///
1958static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1959 // A helper that determines if V is an extractvalue instruction whose
1960 // aggregate operand is a cmpxchg instruction and whose single index is equal
1961 // to I. If such conditions are true, the helper returns the cmpxchg
1962 // instruction; otherwise, a nullptr is returned.
1963 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1964 auto *Extract = dyn_cast<ExtractValueInst>(V);
1965 if (!Extract)
1966 return nullptr;
1967 if (Extract->getIndices()[0] != I)
1968 return nullptr;
1969 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1970 };
1971
1972 // If the select has a single user, and this user is a select instruction that
1973 // we can simplify, skip the cmpxchg simplification for now.
1974 if (SI.hasOneUse())
1975 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1976 if (Select->getCondition() == SI.getCondition())
1977 if (Select->getFalseValue() == SI.getTrueValue() ||
1978 Select->getTrueValue() == SI.getFalseValue())
1979 return nullptr;
1980
1981 // Ensure the select condition is the returned flag of a cmpxchg instruction.
1982 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1983 if (!CmpXchg)
1984 return nullptr;
1985
1986 // Check the true value case: The true value of the select is the returned
1987 // value of the same cmpxchg used by the condition, and the false value is the
1988 // cmpxchg instruction's compare operand.
1989 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1990 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1991 SI.setTrueValue(SI.getFalseValue());
1992 return &SI;
1993 }
1994
1995 // Check the false value case: The false value of the select is the returned
1996 // value of the same cmpxchg used by the condition, and the true value is the
1997 // cmpxchg instruction's compare operand.
1998 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1999 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
2000 SI.setTrueValue(SI.getFalseValue());
2001 return &SI;
2002 }
2003
2004 return nullptr;
2005}
2006
2007static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2008 Value *Y,
2009 InstCombiner::BuilderTy &Builder) {
2010 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern")((SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern"
) ? static_cast<void> (0) : __assert_fail ("SelectPatternResult::isMinOrMax(SPF) && \"Expected min/max pattern\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 2010, __PRETTY_FUNCTION__))
;
2011 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2012 SPF == SelectPatternFlavor::SPF_UMAX;
2013 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2014 // the constant value check to an assert.
2015 Value *A;
2016 const APInt *C1, *C2;
2017 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2018 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2019 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2020 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2021 Value *NewMinMax = createMinMax(Builder, SPF, A,
2022 ConstantInt::get(X->getType(), *C2 - *C1));
2023 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2024 ConstantInt::get(X->getType(), *C1));
2025 }
2026
2027 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2028 match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2029 bool Overflow;
2030 APInt Diff = C2->ssub_ov(*C1, Overflow);
2031 if (!Overflow) {
2032 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2033 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2034 Value *NewMinMax = createMinMax(Builder, SPF, A,
2035 ConstantInt::get(X->getType(), Diff));
2036 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2037 ConstantInt::get(X->getType(), *C1));
2038 }
2039 }
2040
2041 return nullptr;
2042}
2043
2044/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2045Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) {
2046 Type *Ty = MinMax1.getType();
2047
2048 // We are looking for a tree of:
2049 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2050 // Where the min and max could be reversed
2051 Instruction *MinMax2;
2052 BinaryOperator *AddSub;
2053 const APInt *MinValue, *MaxValue;
2054 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2055 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2056 return nullptr;
2057 } else if (match(&MinMax1,
2058 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2059 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2060 return nullptr;
2061 } else
2062 return nullptr;
2063
2064 // Check that the constants clamp a saturate, and that the new type would be
2065 // sensible to convert to.
2066 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2067 return nullptr;
2068 // In what bitwidth can this be treated as saturating arithmetics?
2069 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2070 // FIXME: This isn't quite right for vectors, but using the scalar type is a
2071 // good first approximation for what should be done there.
2072 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2073 return nullptr;
2074
2075 // Also make sure that the number of uses is as expected. The "3"s are for the
2076 // the two items of min/max (the compare and the select).
2077 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2078 return nullptr;
2079
2080 // Create the new type (which can be a vector type)
2081 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2082 // Match the two extends from the add/sub
2083 Value *A, *B;
2084 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2085 return nullptr;
2086 // And check the incoming values are of a type smaller than or equal to the
2087 // size of the saturation. Otherwise the higher bits can cause different
2088 // results.
2089 if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2090 B->getType()->getScalarSizeInBits() > NewBitWidth)
2091 return nullptr;
2092
2093 Intrinsic::ID IntrinsicID;
2094 if (AddSub->getOpcode() == Instruction::Add)
2095 IntrinsicID = Intrinsic::sadd_sat;
2096 else if (AddSub->getOpcode() == Instruction::Sub)
2097 IntrinsicID = Intrinsic::ssub_sat;
2098 else
2099 return nullptr;
2100
2101 // Finally create and return the sat intrinsic, truncated to the new type
2102 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2103 Value *AT = Builder.CreateSExt(A, NewTy);
2104 Value *BT = Builder.CreateSExt(B, NewTy);
2105 Value *Sat = Builder.CreateCall(F, {AT, BT});
2106 return CastInst::Create(Instruction::SExt, Sat, Ty);
2107}
2108
2109/// Reduce a sequence of min/max with a common operand.
2110static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2111 Value *RHS,
2112 InstCombiner::BuilderTy &Builder) {
2113 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max")((SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max"
) ? static_cast<void> (0) : __assert_fail ("SelectPatternResult::isMinOrMax(SPF) && \"Expected a min/max\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 2113, __PRETTY_FUNCTION__))
;
2114 // TODO: Allow FP min/max with nnan/nsz.
2115 if (!LHS->getType()->isIntOrIntVectorTy())
2116 return nullptr;
2117
2118 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2119 Value *A, *B, *C, *D;
2120 SelectPatternResult L = matchSelectPattern(LHS, A, B);
2121 SelectPatternResult R = matchSelectPattern(RHS, C, D);
2122 if (SPF != L.Flavor || L.Flavor != R.Flavor)
2123 return nullptr;
2124
2125 // Look for a common operand. The use checks are different than usual because
2126 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2127 // the select.
2128 Value *MinMaxOp = nullptr;
2129 Value *ThirdOp = nullptr;
2130 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2131 // If the LHS is only used in this chain and the RHS is used outside of it,
2132 // reuse the RHS min/max because that will eliminate the LHS.
2133 if (D == A || C == A) {
2134 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2135 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2136 MinMaxOp = RHS;
2137 ThirdOp = B;
2138 } else if (D == B || C == B) {
2139 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2140 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2141 MinMaxOp = RHS;
2142 ThirdOp = A;
2143 }
2144 } else if (!RHS->hasNUsesOrMore(3)) {
2145 // Reuse the LHS. This will eliminate the RHS.
2146 if (D == A || D == B) {
2147 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2148 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2149 MinMaxOp = LHS;
2150 ThirdOp = C;
2151 } else if (C == A || C == B) {
2152 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2153 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2154 MinMaxOp = LHS;
2155 ThirdOp = D;
2156 }
2157 }
2158 if (!MinMaxOp || !ThirdOp)
2159 return nullptr;
2160
2161 CmpInst::Predicate P = getMinMaxPred(SPF);
2162 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2163 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2164}
2165
2166/// Try to reduce a rotate pattern that includes a compare and select into a
2167/// funnel shift intrinsic. Example:
2168/// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2169/// --> call llvm.fshl.i32(a, a, b)
2170static Instruction *foldSelectRotate(SelectInst &Sel) {
2171 // The false value of the select must be a rotate of the true value.
2172 Value *Or0, *Or1;
2173 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
2174 return nullptr;
2175
2176 Value *TVal = Sel.getTrueValue();
2177 Value *SA0, *SA1;
2178 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
2179 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
2180 return nullptr;
2181
2182 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
2183 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
2184 if (ShiftOpcode0 == ShiftOpcode1)
2185 return nullptr;
2186
2187 // We have one of these patterns so far:
2188 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
2189 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2190 // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2191 unsigned Width = Sel.getType()->getScalarSizeInBits();
2192 if (!isPowerOf2_32(Width))
2193 return nullptr;
2194
2195 // Check the shift amounts to see if they are an opposite pair.
2196 Value *ShAmt;
2197 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2198 ShAmt = SA0;
2199 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2200 ShAmt = SA1;
2201 else
2202 return nullptr;
2203
2204 // Finally, see if the select is filtering out a shift-by-zero.
2205 Value *Cond = Sel.getCondition();
2206 ICmpInst::Predicate Pred;
2207 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2208 Pred != ICmpInst::ICMP_EQ)
2209 return nullptr;
2210
2211 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2212 // Convert to funnel shift intrinsic.
2213 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
2214 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
2215 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2216 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2217 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
2218}
2219
2220Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2221 Value *CondVal = SI.getCondition();
2222 Value *TrueVal = SI.getTrueValue();
2223 Value *FalseVal = SI.getFalseValue();
1
'FalseVal' initialized here
2224 Type *SelType = SI.getType();
2225
2226 // FIXME: Remove this workaround when freeze related patches are done.
2227 // For select with undef operand which feeds into an equality comparison,
2228 // don't simplify it so loop unswitch can know the equality comparison
2229 // may have an undef operand. This is a workaround for PR31652 caused by
2230 // descrepancy about branch on undef between LoopUnswitch and GVN.
2231 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
2
Assuming 'TrueVal' is not a 'UndefValue'
3
Assuming 'FalseVal' is not a 'UndefValue'
4
Taking false branch
2232 if (llvm::any_of(SI.users(), [&](User *U) {
2233 ICmpInst *CI = dyn_cast<ICmpInst>(U);
2234 if (CI && CI->isEquality())
2235 return true;
2236 return false;
2237 })) {
2238 return nullptr;
2239 }
2240 }
2241
2242 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
5
Assuming 'V' is null
6
Taking false branch
2243 SQ.getWithInstruction(&SI)))
2244 return replaceInstUsesWith(SI, V);
2245
2246 if (Instruction *I
10.1
'I' is null
10.1
'I' is null
10.1
'I' is null
10.1
'I' is null
= canonicalizeSelectToShuffle(SI))
7
Calling 'canonicalizeSelectToShuffle'
10
Returning from 'canonicalizeSelectToShuffle'
11
Taking false branch
2247 return I;
2248
2249 if (Instruction *I
19.1
'I' is null
19.1
'I' is null
19.1
'I' is null
19.1
'I' is null
= canonicalizeScalarSelectOfVecs(SI, Builder))
12
Calling 'canonicalizeScalarSelectOfVecs'
19
Returning from 'canonicalizeScalarSelectOfVecs'
20
Taking false branch
2250 return I;
2251
2252 // Canonicalize a one-use integer compare with a non-canonical predicate by
2253 // inverting the predicate and swapping the select operands. This matches a
2254 // compare canonicalization for conditional branches.
2255 // TODO: Should we do the same for FP compares?
2256 CmpInst::Predicate Pred;
2257 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
21
Taking false branch
2258 !isCanonicalPredicate(Pred)) {
2259 // Swap true/false values and condition.
2260 CmpInst *Cond = cast<CmpInst>(CondVal);
2261 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2262 SI.setOperand(1, FalseVal);
2263 SI.setOperand(2, TrueVal);
2264 SI.swapProfMetadata();
2265 Worklist.Add(Cond);
2266 return &SI;
2267 }
2268
2269 if (SelType->isIntOrIntVectorTy(1) &&
22
Assuming the condition is false
2270 TrueVal->getType() == CondVal->getType()) {
2271 if (match(TrueVal, m_One())) {
2272 // Change: A = select B, true, C --> A = or B, C
2273 return BinaryOperator::CreateOr(CondVal, FalseVal);
2274 }
2275 if (match(TrueVal, m_Zero())) {
2276 // Change: A = select B, false, C --> A = and !B, C
2277 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2278 return BinaryOperator::CreateAnd(NotCond, FalseVal);
2279 }
2280 if (match(FalseVal, m_Zero())) {
2281 // Change: A = select B, C, false --> A = and B, C
2282 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2283 }
2284 if (match(FalseVal, m_One())) {
2285 // Change: A = select B, C, true --> A = or !B, C
2286 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2287 return BinaryOperator::CreateOr(NotCond, TrueVal);
2288 }
2289
2290 // select a, a, b -> a | b
2291 // select a, b, a -> a & b
2292 if (CondVal == TrueVal)
2293 return BinaryOperator::CreateOr(CondVal, FalseVal);
2294 if (CondVal == FalseVal)
2295 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2296
2297 // select a, ~a, b -> (~a) & b
2298 // select a, b, ~a -> (~a) | b
2299 if (match(TrueVal, m_Not(m_Specific(CondVal))))
2300 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2301 if (match(FalseVal, m_Not(m_Specific(CondVal))))
2302 return BinaryOperator::CreateOr(TrueVal, FalseVal);
2303 }
2304
2305 // Selecting between two integer or vector splat integer constants?
2306 //
2307 // Note that we don't handle a scalar select of vectors:
2308 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2309 // because that may need 3 instructions to splat the condition value:
2310 // extend, insertelement, shufflevector.
2311 if (SelType->isIntOrIntVectorTy() &&
23
Calling 'Type::isIntOrIntVectorTy'
29
Returning from 'Type::isIntOrIntVectorTy'
2312 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2313 // select C, 1, 0 -> zext C to int
2314 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2315 return new ZExtInst(CondVal, SelType);
2316
2317 // select C, -1, 0 -> sext C to int
2318 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2319 return new SExtInst(CondVal, SelType);
2320
2321 // select C, 0, 1 -> zext !C to int
2322 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2323 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2324 return new ZExtInst(NotCond, SelType);
2325 }
2326
2327 // select C, 0, -1 -> sext !C to int
2328 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2329 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2330 return new SExtInst(NotCond, SelType);
2331 }
2332 }
2333
2334 // See if we are selecting two values based on a comparison of the two values.
2335 if (FCmpInst *FCI
30.1
'FCI' is non-null
30.1
'FCI' is non-null
30.1
'FCI' is non-null
30.1
'FCI' is non-null
= dyn_cast<FCmpInst>(CondVal)) {
30
Assuming 'CondVal' is a 'FCmpInst'
31
Taking true branch
2336 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2337 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
32
Assuming 'Cmp0' is equal to 'TrueVal'
33
Assuming 'Cmp1' is equal to 'FalseVal'
2338 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2339 // Canonicalize to use ordered comparisons by swapping the select
2340 // operands.
2341 //
2342 // e.g.
2343 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2344 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
34
Calling 'Value::hasOneUse'
38
Returning from 'Value::hasOneUse'
39
Assuming the condition is true
40
Assuming the condition is true
41
Taking true branch
2345 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2346 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2347 Builder.setFastMathFlags(FCI->getFastMathFlags());
2348 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2349 FCI->getName() + ".inv");
2350
2351 return SelectInst::Create(NewCond, FalseVal, TrueVal,
42
Passing null pointer value via 2nd parameter 'S1'
43
Calling 'SelectInst::Create'
2352 SI.getName() + ".p");
2353 }
2354
2355 // NOTE: if we wanted to, this is where to detect MIN/MAX
2356 }
2357 }
2358
2359 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2360 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2361 // also require nnan because we do not want to unintentionally change the
2362 // sign of a NaN value.
2363 // FIXME: These folds should test/propagate FMF from the select, not the
2364 // fsub or fneg.
2365 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2366 Instruction *FSub;
2367 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2368 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2369 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2370 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2371 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2372 return replaceInstUsesWith(SI, Fabs);
2373 }
2374 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
2375 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2376 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2377 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2378 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2379 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2380 return replaceInstUsesWith(SI, Fabs);
2381 }
2382 // With nnan and nsz:
2383 // (X < +/-0.0) ? -X : X --> fabs(X)
2384 // (X <= +/-0.0) ? -X : X --> fabs(X)
2385 Instruction *FNeg;
2386 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2387 match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2388 match(TrueVal, m_Instruction(FNeg)) &&
2389 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2390 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2391 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2392 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2393 return replaceInstUsesWith(SI, Fabs);
2394 }
2395 // With nnan and nsz:
2396 // (X > +/-0.0) ? X : -X --> fabs(X)
2397 // (X >= +/-0.0) ? X : -X --> fabs(X)
2398 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2399 match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2400 match(FalseVal, m_Instruction(FNeg)) &&
2401 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2402 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2403 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2404 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2405 return replaceInstUsesWith(SI, Fabs);
2406 }
2407
2408 // See if we are selecting two values based on a comparison of the two values.
2409 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2410 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2411 return Result;
2412
2413 if (Instruction *Add = foldAddSubSelect(SI, Builder))
2414 return Add;
2415 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2416 return Add;
2417
2418 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2419 auto *TI = dyn_cast<Instruction>(TrueVal);
2420 auto *FI = dyn_cast<Instruction>(FalseVal);
2421 if (TI && FI && TI->getOpcode() == FI->getOpcode())
2422 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2423 return IV;
2424
2425 if (Instruction *I = foldSelectExtConst(SI))
2426 return I;
2427
2428 // See if we can fold the select into one of our operands.
2429 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2430 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2431 return FoldI;
2432
2433 Value *LHS, *RHS;
2434 Instruction::CastOps CastOp;
2435 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2436 auto SPF = SPR.Flavor;
2437 if (SPF) {
2438 Value *LHS2, *RHS2;
2439 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2440 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2441 RHS2, SI, SPF, RHS))
2442 return R;
2443 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2444 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2445 RHS2, SI, SPF, LHS))
2446 return R;
2447 // TODO.
2448 // ABS(-X) -> ABS(X)
2449 }
2450
2451 if (SelectPatternResult::isMinOrMax(SPF)) {
2452 // Canonicalize so that
2453 // - type casts are outside select patterns.
2454 // - float clamp is transformed to min/max pattern
2455
2456 bool IsCastNeeded = LHS->getType() != SelType;
2457 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2458 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2459 if (IsCastNeeded ||
2460 (LHS->getType()->isFPOrFPVectorTy() &&
2461 ((CmpLHS != LHS && CmpLHS != RHS) ||
2462 (CmpRHS != LHS && CmpRHS != RHS)))) {
2463 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2464
2465 Value *Cmp;
2466 if (CmpInst::isIntPredicate(MinMaxPred)) {
2467 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2468 } else {
2469 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2470 auto FMF =
2471 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2472 Builder.setFastMathFlags(FMF);
2473 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2474 }
2475
2476 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2477 if (!IsCastNeeded)
2478 return replaceInstUsesWith(SI, NewSI);
2479
2480 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2481 return replaceInstUsesWith(SI, NewCast);
2482 }
2483
2484 // MAX(~a, ~b) -> ~MIN(a, b)
2485 // MAX(~a, C) -> ~MIN(a, ~C)
2486 // MIN(~a, ~b) -> ~MAX(a, b)
2487 // MIN(~a, C) -> ~MAX(a, ~C)
2488 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2489 Value *A;
2490 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2491 !isFreeToInvert(A, A->hasOneUse()) &&
2492 // Passing false to only consider m_Not and constants.
2493 isFreeToInvert(Y, false)) {
2494 Value *B = Builder.CreateNot(Y);
2495 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2496 A, B);
2497 // Copy the profile metadata.
2498 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2499 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2500 // Swap the metadata if the operands are swapped.
2501 if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2502 cast<SelectInst>(NewMinMax)->swapProfMetadata();
2503 }
2504
2505 return BinaryOperator::CreateNot(NewMinMax);
2506 }
2507
2508 return nullptr;
2509 };
2510
2511 if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2512 return I;
2513 if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2514 return I;
2515
2516 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2517 return I;
2518
2519 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2520 return I;
2521 if (Instruction *I = matchSAddSubSat(SI))
2522 return I;
2523 }
2524 }
2525
2526 // Canonicalize select of FP values where NaN and -0.0 are not valid as
2527 // minnum/maxnum intrinsics.
2528 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2529 Value *X, *Y;
2530 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2531 return replaceInstUsesWith(
2532 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2533
2534 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2535 return replaceInstUsesWith(
2536 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2537 }
2538
2539 // See if we can fold the select into a phi node if the condition is a select.
2540 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2541 // The true/false values have to be live in the PHI predecessor's blocks.
2542 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2543 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2544 if (Instruction *NV = foldOpIntoPhi(SI, PN))
2545 return NV;
2546
2547 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2548 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2549 // select(C, select(C, a, b), c) -> select(C, a, c)
2550 if (TrueSI->getCondition() == CondVal) {
2551 if (SI.getTrueValue() == TrueSI->getTrueValue())
2552 return nullptr;
2553 SI.setOperand(1, TrueSI->getTrueValue());
2554 return &SI;
2555 }
2556 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2557 // We choose this as normal form to enable folding on the And and shortening
2558 // paths for the values (this helps GetUnderlyingObjects() for example).
2559 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2560 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2561 SI.setOperand(0, And);
2562 SI.setOperand(1, TrueSI->getTrueValue());
2563 return &SI;
2564 }
2565 }
2566 }
2567 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2568 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2569 // select(C, a, select(C, b, c)) -> select(C, a, c)
2570 if (FalseSI->getCondition() == CondVal) {
2571 if (SI.getFalseValue() == FalseSI->getFalseValue())
2572 return nullptr;
2573 SI.setOperand(2, FalseSI->getFalseValue());
2574 return &SI;
2575 }
2576 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2577 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2578 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2579 SI.setOperand(0, Or);
2580 SI.setOperand(2, FalseSI->getFalseValue());
2581 return &SI;
2582 }
2583 }
2584 }
2585
2586 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2587 // The select might be preventing a division by 0.
2588 switch (BO->getOpcode()) {
2589 default:
2590 return true;
2591 case Instruction::SRem:
2592 case Instruction::URem:
2593 case Instruction::SDiv:
2594 case Instruction::UDiv:
2595 return false;
2596 }
2597 };
2598
2599 // Try to simplify a binop sandwiched between 2 selects with the same
2600 // condition.
2601 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2602 BinaryOperator *TrueBO;
2603 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2604 canMergeSelectThroughBinop(TrueBO)) {
2605 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2606 if (TrueBOSI->getCondition() == CondVal) {
2607 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
2608 Worklist.Add(TrueBO);
2609 return &SI;
2610 }
2611 }
2612 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2613 if (TrueBOSI->getCondition() == CondVal) {
2614 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
2615 Worklist.Add(TrueBO);
2616 return &SI;
2617 }
2618 }
2619 }
2620
2621 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2622 BinaryOperator *FalseBO;
2623 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2624 canMergeSelectThroughBinop(FalseBO)) {
2625 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2626 if (FalseBOSI->getCondition() == CondVal) {
2627 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
2628 Worklist.Add(FalseBO);
2629 return &SI;
2630 }
2631 }
2632 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2633 if (FalseBOSI->getCondition() == CondVal) {
2634 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
2635 Worklist.Add(FalseBO);
2636 return &SI;
2637 }
2638 }
2639 }
2640
2641 Value *NotCond;
2642 if (match(CondVal, m_Not(m_Value(NotCond)))) {
2643 SI.setOperand(0, NotCond);
2644 SI.setOperand(1, FalseVal);
2645 SI.setOperand(2, TrueVal);
2646 SI.swapProfMetadata();
2647 return &SI;
2648 }
2649
2650 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2651 unsigned VWidth = VecTy->getNumElements();
2652 APInt UndefElts(VWidth, 0);
2653 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2654 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2655 if (V != &SI)
2656 return replaceInstUsesWith(SI, V);
2657 return &SI;
2658 }
2659 }
2660
2661 // If we can compute the condition, there's no need for a select.
2662 // Like the above fold, we are attempting to reduce compile-time cost by
2663 // putting this fold here with limitations rather than in InstSimplify.
2664 // The motivation for this call into value tracking is to take advantage of
2665 // the assumption cache, so make sure that is populated.
2666 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2667 KnownBits Known(1);
2668 computeKnownBits(CondVal, Known, 0, &SI);
2669 if (Known.One.isOneValue())
2670 return replaceInstUsesWith(SI, TrueVal);
2671 if (Known.Zero.isOneValue())
2672 return replaceInstUsesWith(SI, FalseVal);
2673 }
2674
2675 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2676 return BitCastSel;
2677
2678 // Simplify selects that test the returned flag of cmpxchg instructions.
2679 if (Instruction *Select = foldSelectCmpXchg(SI))
2680 return Select;
2681
2682 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
2683 return Select;
2684
2685 if (Instruction *Rot = foldSelectRotate(SI))
2686 return Rot;
2687
2688 return nullptr;
2689}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h

1//===- llvm/Type.h - Classes for handling data types ------------*- 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 contains the declaration of the Type class. For more "Type"
10// stuff, look in DerivedTypes.h.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_TYPE_H
15#define LLVM_IR_TYPE_H
16
17#include "llvm/ADT/APFloat.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/Support/CBindingWrapping.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/Compiler.h"
23#include "llvm/Support/ErrorHandling.h"
24#include "llvm/Support/TypeSize.h"
25#include <cassert>
26#include <cstdint>
27#include <iterator>
28
29namespace llvm {
30
31template<class GraphType> struct GraphTraits;
32class IntegerType;
33class LLVMContext;
34class PointerType;
35class raw_ostream;
36class StringRef;
37
38/// The instances of the Type class are immutable: once they are created,
39/// they are never changed. Also note that only one instance of a particular
40/// type is ever created. Thus seeing if two types are equal is a matter of
41/// doing a trivial pointer comparison. To enforce that no two equal instances
42/// are created, Type instances can only be created via static factory methods
43/// in class Type and in derived classes. Once allocated, Types are never
44/// free'd.
45///
46class Type {
47public:
48 //===--------------------------------------------------------------------===//
49 /// Definitions of all of the base types for the Type system. Based on this
50 /// value, you can cast to a class defined in DerivedTypes.h.
51 /// Note: If you add an element to this, you need to add an element to the
52 /// Type::getPrimitiveType function, or else things will break!
53 /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding.
54 ///
55 enum TypeID {
56 // PrimitiveTypes - make sure LastPrimitiveTyID stays up to date.
57 VoidTyID = 0, ///< 0: type with no size
58 HalfTyID, ///< 1: 16-bit floating point type
59 FloatTyID, ///< 2: 32-bit floating point type
60 DoubleTyID, ///< 3: 64-bit floating point type
61 X86_FP80TyID, ///< 4: 80-bit floating point type (X87)
62 FP128TyID, ///< 5: 128-bit floating point type (112-bit mantissa)
63 PPC_FP128TyID, ///< 6: 128-bit floating point type (two 64-bits, PowerPC)
64 LabelTyID, ///< 7: Labels
65 MetadataTyID, ///< 8: Metadata
66 X86_MMXTyID, ///< 9: MMX vectors (64 bits, X86 specific)
67 TokenTyID, ///< 10: Tokens
68
69 // Derived types... see DerivedTypes.h file.
70 // Make sure FirstDerivedTyID stays up to date!
71 IntegerTyID, ///< 11: Arbitrary bit width integers
72 FunctionTyID, ///< 12: Functions
73 StructTyID, ///< 13: Structures
74 ArrayTyID, ///< 14: Arrays
75 PointerTyID, ///< 15: Pointers
76 VectorTyID ///< 16: SIMD 'packed' format, or other vector type
77 };
78
79private:
80 /// This refers to the LLVMContext in which this type was uniqued.
81 LLVMContext &Context;
82
83 TypeID ID : 8; // The current base type of this type.
84 unsigned SubclassData : 24; // Space for subclasses to store data.
85 // Note that this should be synchronized with
86 // MAX_INT_BITS value in IntegerType class.
87
88protected:
89 friend class LLVMContextImpl;
90
91 explicit Type(LLVMContext &C, TypeID tid)
92 : Context(C), ID(tid), SubclassData(0) {}
93 ~Type() = default;
94
95 unsigned getSubclassData() const { return SubclassData; }
96
97 void setSubclassData(unsigned val) {
98 SubclassData = val;
99 // Ensure we don't have any accidental truncation.
100 assert(getSubclassData() == val && "Subclass data too large for field")((getSubclassData() == val && "Subclass data too large for field"
) ? static_cast<void> (0) : __assert_fail ("getSubclassData() == val && \"Subclass data too large for field\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 100, __PRETTY_FUNCTION__))
;
101 }
102
103 /// Keeps track of how many Type*'s there are in the ContainedTys list.
104 unsigned NumContainedTys = 0;
105
106 /// A pointer to the array of Types contained by this Type. For example, this
107 /// includes the arguments of a function type, the elements of a structure,
108 /// the pointee of a pointer, the element type of an array, etc. This pointer
109 /// may be 0 for types that don't contain other types (Integer, Double,
110 /// Float).
111 Type * const *ContainedTys = nullptr;
112
113 static bool isSequentialType(TypeID TyID) {
114 return TyID == ArrayTyID || TyID == VectorTyID;
115 }
116
117public:
118 /// Print the current type.
119 /// Omit the type details if \p NoDetails == true.
120 /// E.g., let %st = type { i32, i16 }
121 /// When \p NoDetails is true, we only print %st.
122 /// Put differently, \p NoDetails prints the type as if
123 /// inlined with the operands when printing an instruction.
124 void print(raw_ostream &O, bool IsForDebug = false,
125 bool NoDetails = false) const;
126
127 void dump() const;
128
129 /// Return the LLVMContext in which this type was uniqued.
130 LLVMContext &getContext() const { return Context; }
131
132 //===--------------------------------------------------------------------===//
133 // Accessors for working with types.
134 //
135
136 /// Return the type id for the type. This will return one of the TypeID enum
137 /// elements defined above.
138 TypeID getTypeID() const { return ID; }
139
140 /// Return true if this is 'void'.
141 bool isVoidTy() const { return getTypeID() == VoidTyID; }
142
143 /// Return true if this is 'half', a 16-bit IEEE fp type.
144 bool isHalfTy() const { return getTypeID() == HalfTyID; }
145
146 /// Return true if this is 'float', a 32-bit IEEE fp type.
147 bool isFloatTy() const { return getTypeID() == FloatTyID; }
148
149 /// Return true if this is 'double', a 64-bit IEEE fp type.
150 bool isDoubleTy() const { return getTypeID() == DoubleTyID; }
151
152 /// Return true if this is x86 long double.
153 bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; }
154
155 /// Return true if this is 'fp128'.
156 bool isFP128Ty() const { return getTypeID() == FP128TyID; }
157
158 /// Return true if this is powerpc long double.
159 bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; }
160
161 /// Return true if this is one of the six floating-point types
162 bool isFloatingPointTy() const {
163 return getTypeID() == HalfTyID || getTypeID() == FloatTyID ||
164 getTypeID() == DoubleTyID ||
165 getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID ||
166 getTypeID() == PPC_FP128TyID;
167 }
168
169 const fltSemantics &getFltSemantics() const {
170 switch (getTypeID()) {
171 case HalfTyID: return APFloat::IEEEhalf();
172 case FloatTyID: return APFloat::IEEEsingle();
173 case DoubleTyID: return APFloat::IEEEdouble();
174 case X86_FP80TyID: return APFloat::x87DoubleExtended();
175 case FP128TyID: return APFloat::IEEEquad();
176 case PPC_FP128TyID: return APFloat::PPCDoubleDouble();
177 default: llvm_unreachable("Invalid floating type")::llvm::llvm_unreachable_internal("Invalid floating type", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 177)
;
178 }
179 }
180
181 /// Return true if this is X86 MMX.
182 bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; }
183
184 /// Return true if this is a FP type or a vector of FP.
185 bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); }
186
187 /// Return true if this is 'label'.
188 bool isLabelTy() const { return getTypeID() == LabelTyID; }
189
190 /// Return true if this is 'metadata'.
191 bool isMetadataTy() const { return getTypeID() == MetadataTyID; }
192
193 /// Return true if this is 'token'.
194 bool isTokenTy() const { return getTypeID() == TokenTyID; }
195
196 /// True if this is an instance of IntegerType.
197 bool isIntegerTy() const { return getTypeID() == IntegerTyID; }
25
Assuming the condition is false
26
Returning zero, which participates in a condition later
198
199 /// Return true if this is an IntegerType of the given width.
200 bool isIntegerTy(unsigned Bitwidth) const;
201
202 /// Return true if this is an integer type or a vector of integer types.
203 bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); }
24
Calling 'Type::isIntegerTy'
27
Returning from 'Type::isIntegerTy'
28
Returning zero, which participates in a condition later
204
205 /// Return true if this is an integer type or a vector of integer types of
206 /// the given width.
207 bool isIntOrIntVectorTy(unsigned BitWidth) const {
208 return getScalarType()->isIntegerTy(BitWidth);
209 }
210
211 /// Return true if this is an integer type or a pointer type.
212 bool isIntOrPtrTy() const { return isIntegerTy() || isPointerTy(); }
213
214 /// True if this is an instance of FunctionType.
215 bool isFunctionTy() const { return getTypeID() == FunctionTyID; }
216
217 /// True if this is an instance of StructType.
218 bool isStructTy() const { return getTypeID() == StructTyID; }
219
220 /// True if this is an instance of ArrayType.
221 bool isArrayTy() const { return getTypeID() == ArrayTyID; }
222
223 /// True if this is an instance of PointerType.
224 bool isPointerTy() const { return getTypeID() == PointerTyID; }
225
226 /// Return true if this is a pointer type or a vector of pointer types.
227 bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); }
228
229 /// True if this is an instance of VectorType.
230 bool isVectorTy() const { return getTypeID() == VectorTyID; }
14
Assuming the condition is false
15
Returning zero, which participates in a condition later
231
232 /// Return true if this type could be converted with a lossless BitCast to
233 /// type 'Ty'. For example, i8* to i32*. BitCasts are valid for types of the
234 /// same size only where no re-interpretation of the bits is done.
235 /// Determine if this type could be losslessly bitcast to Ty
236 bool canLosslesslyBitCastTo(Type *Ty) const;
237
238 /// Return true if this type is empty, that is, it has no elements or all of
239 /// its elements are empty.
240 bool isEmptyTy() const;
241
242 /// Return true if the type is "first class", meaning it is a valid type for a
243 /// Value.
244 bool isFirstClassType() const {
245 return getTypeID() != FunctionTyID && getTypeID() != VoidTyID;
246 }
247
248 /// Return true if the type is a valid type for a register in codegen. This
249 /// includes all first-class types except struct and array types.
250 bool isSingleValueType() const {
251 return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() ||
252 isPointerTy() || isVectorTy();
253 }
254
255 /// Return true if the type is an aggregate type. This means it is valid as
256 /// the first operand of an insertvalue or extractvalue instruction. This
257 /// includes struct and array types, but does not include vector types.
258 bool isAggregateType() const {
259 return getTypeID() == StructTyID || getTypeID() == ArrayTyID;
260 }
261
262 /// Return true if it makes sense to take the size of this type. To get the
263 /// actual size for a particular target, it is reasonable to use the
264 /// DataLayout subsystem to do this.
265 bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const {
266 // If it's a primitive, it is always sized.
267 if (getTypeID() == IntegerTyID || isFloatingPointTy() ||
268 getTypeID() == PointerTyID ||
269 getTypeID() == X86_MMXTyID)
270 return true;
271 // If it is not something that can have a size (e.g. a function or label),
272 // it doesn't have a size.
273 if (getTypeID() != StructTyID && getTypeID() != ArrayTyID &&
274 getTypeID() != VectorTyID)
275 return false;
276 // Otherwise we have to try harder to decide.
277 return isSizedDerivedType(Visited);
278 }
279
280 /// Return the basic size of this type if it is a primitive type. These are
281 /// fixed by LLVM and are not target-dependent.
282 /// This will return zero if the type does not have a size or is not a
283 /// primitive type.
284 ///
285 /// If this is a scalable vector type, the scalable property will be set and
286 /// the runtime size will be a positive integer multiple of the base size.
287 ///
288 /// Note that this may not reflect the size of memory allocated for an
289 /// instance of the type or the number of bytes that are written when an
290 /// instance of the type is stored to memory. The DataLayout class provides
291 /// additional query functions to provide this information.
292 ///
293 TypeSize getPrimitiveSizeInBits() const LLVM_READONLY__attribute__((__pure__));
294
295 /// If this is a vector type, return the getPrimitiveSizeInBits value for the
296 /// element type. Otherwise return the getPrimitiveSizeInBits value for this
297 /// type.
298 unsigned getScalarSizeInBits() const LLVM_READONLY__attribute__((__pure__));
299
300 /// Return the width of the mantissa of this type. This is only valid on
301 /// floating-point types. If the FP type does not have a stable mantissa (e.g.
302 /// ppc long double), this method returns -1.
303 int getFPMantissaWidth() const;
304
305 /// If this is a vector type, return the element type, otherwise return
306 /// 'this'.
307 Type *getScalarType() const {
308 if (isVectorTy())
309 return getVectorElementType();
310 return const_cast<Type*>(this);
311 }
312
313 //===--------------------------------------------------------------------===//
314 // Type Iteration support.
315 //
316 using subtype_iterator = Type * const *;
317
318 subtype_iterator subtype_begin() const { return ContainedTys; }
319 subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];}
320 ArrayRef<Type*> subtypes() const {
321 return makeArrayRef(subtype_begin(), subtype_end());
322 }
323
324 using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>;
325
326 subtype_reverse_iterator subtype_rbegin() const {
327 return subtype_reverse_iterator(subtype_end());
328 }
329 subtype_reverse_iterator subtype_rend() const {
330 return subtype_reverse_iterator(subtype_begin());
331 }
332
333 /// This method is used to implement the type iterator (defined at the end of
334 /// the file). For derived types, this returns the types 'contained' in the
335 /// derived type.
336 Type *getContainedType(unsigned i) const {
337 assert(i < NumContainedTys && "Index out of range!")((i < NumContainedTys && "Index out of range!") ? static_cast
<void> (0) : __assert_fail ("i < NumContainedTys && \"Index out of range!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 337, __PRETTY_FUNCTION__))
;
338 return ContainedTys[i];
339 }
340
341 /// Return the number of types in the derived type.
342 unsigned getNumContainedTypes() const { return NumContainedTys; }
343
344 //===--------------------------------------------------------------------===//
345 // Helper methods corresponding to subclass methods. This forces a cast to
346 // the specified subclass and calls its accessor. "getVectorNumElements" (for
347 // example) is shorthand for cast<VectorType>(Ty)->getNumElements(). This is
348 // only intended to cover the core methods that are frequently used, helper
349 // methods should not be added here.
350
351 inline unsigned getIntegerBitWidth() const;
352
353 inline Type *getFunctionParamType(unsigned i) const;
354 inline unsigned getFunctionNumParams() const;
355 inline bool isFunctionVarArg() const;
356
357 inline StringRef getStructName() const;
358 inline unsigned getStructNumElements() const;
359 inline Type *getStructElementType(unsigned N) const;
360
361 inline Type *getSequentialElementType() const {
362 assert(isSequentialType(getTypeID()) && "Not a sequential type!")((isSequentialType(getTypeID()) && "Not a sequential type!"
) ? static_cast<void> (0) : __assert_fail ("isSequentialType(getTypeID()) && \"Not a sequential type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 362, __PRETTY_FUNCTION__))
;
363 return ContainedTys[0];
364 }
365
366 inline uint64_t getArrayNumElements() const;
367
368 Type *getArrayElementType() const {
369 assert(getTypeID() == ArrayTyID)((getTypeID() == ArrayTyID) ? static_cast<void> (0) : __assert_fail
("getTypeID() == ArrayTyID", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 369, __PRETTY_FUNCTION__))
;
370 return ContainedTys[0];
371 }
372
373 inline bool getVectorIsScalable() const;
374 inline unsigned getVectorNumElements() const;
375 inline ElementCount getVectorElementCount() const;
376 Type *getVectorElementType() const {
377 assert(getTypeID() == VectorTyID)((getTypeID() == VectorTyID) ? static_cast<void> (0) : __assert_fail
("getTypeID() == VectorTyID", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 377, __PRETTY_FUNCTION__))
;
378 return ContainedTys[0];
379 }
380
381 Type *getPointerElementType() const {
382 assert(getTypeID() == PointerTyID)((getTypeID() == PointerTyID) ? static_cast<void> (0) :
__assert_fail ("getTypeID() == PointerTyID", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 382, __PRETTY_FUNCTION__))
;
383 return ContainedTys[0];
384 }
385
386 /// Given an integer or vector type, change the lane bitwidth to NewBitwidth,
387 /// whilst keeping the old number of lanes.
388 inline Type *getWithNewBitWidth(unsigned NewBitWidth) const;
389
390 /// Given scalar/vector integer type, returns a type with elements twice as
391 /// wide as in the original type. For vectors, preserves element count.
392 inline Type *getExtendedType() const;
393
394 /// Get the address space of this pointer or pointer vector type.
395 inline unsigned getPointerAddressSpace() const;
396
397 //===--------------------------------------------------------------------===//
398 // Static members exported by the Type class itself. Useful for getting
399 // instances of Type.
400 //
401
402 /// Return a type based on an identifier.
403 static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber);
404
405 //===--------------------------------------------------------------------===//
406 // These are the builtin types that are always available.
407 //
408 static Type *getVoidTy(LLVMContext &C);
409 static Type *getLabelTy(LLVMContext &C);
410 static Type *getHalfTy(LLVMContext &C);
411 static Type *getFloatTy(LLVMContext &C);
412 static Type *getDoubleTy(LLVMContext &C);
413 static Type *getMetadataTy(LLVMContext &C);
414 static Type *getX86_FP80Ty(LLVMContext &C);
415 static Type *getFP128Ty(LLVMContext &C);
416 static Type *getPPC_FP128Ty(LLVMContext &C);
417 static Type *getX86_MMXTy(LLVMContext &C);
418 static Type *getTokenTy(LLVMContext &C);
419 static IntegerType *getIntNTy(LLVMContext &C, unsigned N);
420 static IntegerType *getInt1Ty(LLVMContext &C);
421 static IntegerType *getInt8Ty(LLVMContext &C);
422 static IntegerType *getInt16Ty(LLVMContext &C);
423 static IntegerType *getInt32Ty(LLVMContext &C);
424 static IntegerType *getInt64Ty(LLVMContext &C);
425 static IntegerType *getInt128Ty(LLVMContext &C);
426 template <typename ScalarTy> static Type *getScalarTy(LLVMContext &C) {
427 int noOfBits = sizeof(ScalarTy) * CHAR_BIT8;
428 if (std::is_integral<ScalarTy>::value) {
429 return (Type*) Type::getIntNTy(C, noOfBits);
430 } else if (std::is_floating_point<ScalarTy>::value) {
431 switch (noOfBits) {
432 case 32:
433 return Type::getFloatTy(C);
434 case 64:
435 return Type::getDoubleTy(C);
436 }
437 }
438 llvm_unreachable("Unsupported type in Type::getScalarTy")::llvm::llvm_unreachable_internal("Unsupported type in Type::getScalarTy"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Type.h"
, 438)
;
439 }
440
441 //===--------------------------------------------------------------------===//
442 // Convenience methods for getting pointer types with one of the above builtin
443 // types as pointee.
444 //
445 static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0);
446 static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0);
447 static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0);
448 static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0);
449 static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0);
450 static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0);
451 static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0);
452 static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0);
453 static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0);
454 static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0);
455 static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0);
456 static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0);
457 static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0);
458
459 /// Return a pointer to the current type. This is equivalent to
460 /// PointerType::get(Foo, AddrSpace).
461 PointerType *getPointerTo(unsigned AddrSpace = 0) const;
462
463private:
464 /// Derived types like structures and arrays are sized iff all of the members
465 /// of the type are sized as well. Since asking for their size is relatively
466 /// uncommon, move this operation out-of-line.
467 bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const;
468};
469
470// Printing of types.
471inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) {
472 T.print(OS);
473 return OS;
474}
475
476// allow isa<PointerType>(x) to work without DerivedTypes.h included.
477template <> struct isa_impl<PointerType, Type> {
478 static inline bool doit(const Type &Ty) {
479 return Ty.getTypeID() == Type::PointerTyID;
480 }
481};
482
483// Create wrappers for C Binding types (see CBindingWrapping.h).
484DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)inline Type *unwrap(LLVMTypeRef P) { return reinterpret_cast<
Type*>(P); } inline LLVMTypeRef wrap(const Type *P) { return
reinterpret_cast<LLVMTypeRef>(const_cast<Type*>(
P)); } template<typename T> inline T *unwrap(LLVMTypeRef
P) { return cast<T>(unwrap(P)); }
485
486/* Specialized opaque type conversions.
487 */
488inline Type **unwrap(LLVMTypeRef* Tys) {
489 return reinterpret_cast<Type**>(Tys);
490}
491
492inline LLVMTypeRef *wrap(Type **Tys) {
493 return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys));
494}
495
496} // end namespace llvm
497
498#endif // LLVM_IR_TYPE_H

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h

1//===- llvm/Value.h - Definition of the Value 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//
9// This file declares the Value class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_IR_VALUE_H
14#define LLVM_IR_VALUE_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/iterator_range.h"
19#include "llvm/IR/Use.h"
20#include "llvm/Support/Alignment.h"
21#include "llvm/Support/CBindingWrapping.h"
22#include "llvm/Support/Casting.h"
23#include <cassert>
24#include <iterator>
25#include <memory>
26
27namespace llvm {
28
29class APInt;
30class Argument;
31class BasicBlock;
32class Constant;
33class ConstantData;
34class ConstantAggregate;
35class DataLayout;
36class Function;
37class GlobalAlias;
38class GlobalIFunc;
39class GlobalIndirectSymbol;
40class GlobalObject;
41class GlobalValue;
42class GlobalVariable;
43class InlineAsm;
44class Instruction;
45class LLVMContext;
46class Module;
47class ModuleSlotTracker;
48class raw_ostream;
49template<typename ValueTy> class StringMapEntry;
50class StringRef;
51class Twine;
52class Type;
53class User;
54
55using ValueName = StringMapEntry<Value *>;
56
57//===----------------------------------------------------------------------===//
58// Value Class
59//===----------------------------------------------------------------------===//
60
61/// LLVM Value Representation
62///
63/// This is a very important LLVM class. It is the base class of all values
64/// computed by a program that may be used as operands to other values. Value is
65/// the super class of other important classes such as Instruction and Function.
66/// All Values have a Type. Type is not a subclass of Value. Some values can
67/// have a name and they belong to some Module. Setting the name on the Value
68/// automatically updates the module's symbol table.
69///
70/// Every value has a "use list" that keeps track of which other Values are
71/// using this Value. A Value can also have an arbitrary number of ValueHandle
72/// objects that watch it and listen to RAUW and Destroy events. See
73/// llvm/IR/ValueHandle.h for details.
74class Value {
75 // The least-significant bit of the first word of Value *must* be zero:
76 // http://www.llvm.org/docs/ProgrammersManual.html#the-waymarking-algorithm
77 Type *VTy;
78 Use *UseList;
79
80 friend class ValueAsMetadata; // Allow access to IsUsedByMD.
81 friend class ValueHandleBase;
82
83 const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
84 unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
85
86protected:
87 /// Hold subclass data that can be dropped.
88 ///
89 /// This member is similar to SubclassData, however it is for holding
90 /// information which may be used to aid optimization, but which may be
91 /// cleared to zero without affecting conservative interpretation.
92 unsigned char SubclassOptionalData : 7;
93
94private:
95 /// Hold arbitrary subclass data.
96 ///
97 /// This member is defined by this class, but is not used for anything.
98 /// Subclasses can use it to hold whatever state they find useful. This
99 /// field is initialized to zero by the ctor.
100 unsigned short SubclassData;
101
102protected:
103 /// The number of operands in the subclass.
104 ///
105 /// This member is defined by this class, but not used for anything.
106 /// Subclasses can use it to store their number of operands, if they have
107 /// any.
108 ///
109 /// This is stored here to save space in User on 64-bit hosts. Since most
110 /// instances of Value have operands, 32-bit hosts aren't significantly
111 /// affected.
112 ///
113 /// Note, this should *NOT* be used directly by any class other than User.
114 /// User uses this value to find the Use list.
115 enum : unsigned { NumUserOperandsBits = 28 };
116 unsigned NumUserOperands : NumUserOperandsBits;
117
118 // Use the same type as the bitfield above so that MSVC will pack them.
119 unsigned IsUsedByMD : 1;
120 unsigned HasName : 1;
121 unsigned HasHungOffUses : 1;
122 unsigned HasDescriptor : 1;
123
124private:
125 template <typename UseT> // UseT == 'Use' or 'const Use'
126 class use_iterator_impl
127 : public std::iterator<std::forward_iterator_tag, UseT *> {
128 friend class Value;
129
130 UseT *U;
131
132 explicit use_iterator_impl(UseT *u) : U(u) {}
133
134 public:
135 use_iterator_impl() : U() {}
136
137 bool operator==(const use_iterator_impl &x) const { return U == x.U; }
138 bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
139
140 use_iterator_impl &operator++() { // Preincrement
141 assert(U && "Cannot increment end iterator!")((U && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 141, __PRETTY_FUNCTION__))
;
142 U = U->getNext();
143 return *this;
144 }
145
146 use_iterator_impl operator++(int) { // Postincrement
147 auto tmp = *this;
148 ++*this;
149 return tmp;
150 }
151
152 UseT &operator*() const {
153 assert(U && "Cannot dereference end iterator!")((U && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("U && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 153, __PRETTY_FUNCTION__))
;
154 return *U;
155 }
156
157 UseT *operator->() const { return &operator*(); }
158
159 operator use_iterator_impl<const UseT>() const {
160 return use_iterator_impl<const UseT>(U);
161 }
162 };
163
164 template <typename UserTy> // UserTy == 'User' or 'const User'
165 class user_iterator_impl
166 : public std::iterator<std::forward_iterator_tag, UserTy *> {
167 use_iterator_impl<Use> UI;
168 explicit user_iterator_impl(Use *U) : UI(U) {}
169 friend class Value;
170
171 public:
172 user_iterator_impl() = default;
173
174 bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
175 bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
176
177 /// Returns true if this iterator is equal to user_end() on the value.
178 bool atEnd() const { return *this == user_iterator_impl(); }
179
180 user_iterator_impl &operator++() { // Preincrement
181 ++UI;
182 return *this;
183 }
184
185 user_iterator_impl operator++(int) { // Postincrement
186 auto tmp = *this;
187 ++*this;
188 return tmp;
189 }
190
191 // Retrieve a pointer to the current User.
192 UserTy *operator*() const {
193 return UI->getUser();
194 }
195
196 UserTy *operator->() const { return operator*(); }
197
198 operator user_iterator_impl<const UserTy>() const {
199 return user_iterator_impl<const UserTy>(*UI);
200 }
201
202 Use &getUse() const { return *UI; }
203 };
204
205protected:
206 Value(Type *Ty, unsigned scid);
207
208 /// Value's destructor should be virtual by design, but that would require
209 /// that Value and all of its subclasses have a vtable that effectively
210 /// duplicates the information in the value ID. As a size optimization, the
211 /// destructor has been protected, and the caller should manually call
212 /// deleteValue.
213 ~Value(); // Use deleteValue() to delete a generic Value.
214
215public:
216 Value(const Value &) = delete;
217 Value &operator=(const Value &) = delete;
218
219 /// Delete a pointer to a generic Value.
220 void deleteValue();
221
222 /// Support for debugging, callable in GDB: V->dump()
223 void dump() const;
224
225 /// Implement operator<< on Value.
226 /// @{
227 void print(raw_ostream &O, bool IsForDebug = false) const;
228 void print(raw_ostream &O, ModuleSlotTracker &MST,
229 bool IsForDebug = false) const;
230 /// @}
231
232 /// Print the name of this Value out to the specified raw_ostream.
233 ///
234 /// This is useful when you just want to print 'int %reg126', not the
235 /// instruction that generated it. If you specify a Module for context, then
236 /// even constanst get pretty-printed; for example, the type of a null
237 /// pointer is printed symbolically.
238 /// @{
239 void printAsOperand(raw_ostream &O, bool PrintType = true,
240 const Module *M = nullptr) const;
241 void printAsOperand(raw_ostream &O, bool PrintType,
242 ModuleSlotTracker &MST) const;
243 /// @}
244
245 /// All values are typed, get the type of this value.
246 Type *getType() const { return VTy; }
247
248 /// All values hold a context through their type.
249 LLVMContext &getContext() const;
250
251 // All values can potentially be named.
252 bool hasName() const { return HasName; }
253 ValueName *getValueName() const;
254 void setValueName(ValueName *VN);
255
256private:
257 void destroyValueName();
258 enum class ReplaceMetadataUses { No, Yes };
259 void doRAUW(Value *New, ReplaceMetadataUses);
260 void setNameImpl(const Twine &Name);
261
262public:
263 /// Return a constant reference to the value's name.
264 ///
265 /// This guaranteed to return the same reference as long as the value is not
266 /// modified. If the value has a name, this does a hashtable lookup, so it's
267 /// not free.
268 StringRef getName() const;
269
270 /// Change the name of the value.
271 ///
272 /// Choose a new unique name if the provided name is taken.
273 ///
274 /// \param Name The new name; or "" if the value's name should be removed.
275 void setName(const Twine &Name);
276
277 /// Transfer the name from V to this value.
278 ///
279 /// After taking V's name, sets V's name to empty.
280 ///
281 /// \note It is an error to call V->takeName(V).
282 void takeName(Value *V);
283
284 /// Change all uses of this to point to a new Value.
285 ///
286 /// Go through the uses list for this definition and make each use point to
287 /// "V" instead of "this". After this completes, 'this's use list is
288 /// guaranteed to be empty.
289 void replaceAllUsesWith(Value *V);
290
291 /// Change non-metadata uses of this to point to a new Value.
292 ///
293 /// Go through the uses list for this definition and make each use point to
294 /// "V" instead of "this". This function skips metadata entries in the list.
295 void replaceNonMetadataUsesWith(Value *V);
296
297 /// Go through the uses list for this definition and make each use point
298 /// to "V" if the callback ShouldReplace returns true for the given Use.
299 /// Unlike replaceAllUsesWith() this function does not support basic block
300 /// values or constant users.
301 void replaceUsesWithIf(Value *New,
302 llvm::function_ref<bool(Use &U)> ShouldReplace) {
303 assert(New && "Value::replaceUsesWithIf(<null>) is invalid!")((New && "Value::replaceUsesWithIf(<null>) is invalid!"
) ? static_cast<void> (0) : __assert_fail ("New && \"Value::replaceUsesWithIf(<null>) is invalid!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 303, __PRETTY_FUNCTION__))
;
304 assert(New->getType() == getType() &&((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 305, __PRETTY_FUNCTION__))
305 "replaceUses of value with new value of different type!")((New->getType() == getType() && "replaceUses of value with new value of different type!"
) ? static_cast<void> (0) : __assert_fail ("New->getType() == getType() && \"replaceUses of value with new value of different type!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 305, __PRETTY_FUNCTION__))
;
306
307 for (use_iterator UI = use_begin(), E = use_end(); UI != E;) {
308 Use &U = *UI;
309 ++UI;
310 if (!ShouldReplace(U))
311 continue;
312 U.set(New);
313 }
314 }
315
316 /// replaceUsesOutsideBlock - Go through the uses list for this definition and
317 /// make each use point to "V" instead of "this" when the use is outside the
318 /// block. 'This's use list is expected to have at least one element.
319 /// Unlike replaceAllUsesWith() this function does not support basic block
320 /// values or constant users.
321 void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
322
323 //----------------------------------------------------------------------
324 // Methods for handling the chain of uses of this Value.
325 //
326 // Materializing a function can introduce new uses, so these methods come in
327 // two variants:
328 // The methods that start with materialized_ check the uses that are
329 // currently known given which functions are materialized. Be very careful
330 // when using them since you might not get all uses.
331 // The methods that don't start with materialized_ assert that modules is
332 // fully materialized.
333 void assertModuleIsMaterializedImpl() const;
334 // This indirection exists so we can keep assertModuleIsMaterializedImpl()
335 // around in release builds of Value.cpp to be linked with other code built
336 // in debug mode. But this avoids calling it in any of the release built code.
337 void assertModuleIsMaterialized() const {
338#ifndef NDEBUG
339 assertModuleIsMaterializedImpl();
340#endif
341 }
342
343 bool use_empty() const {
344 assertModuleIsMaterialized();
345 return UseList == nullptr;
346 }
347
348 bool materialized_use_empty() const {
349 return UseList == nullptr;
350 }
351
352 using use_iterator = use_iterator_impl<Use>;
353 using const_use_iterator = use_iterator_impl<const Use>;
354
355 use_iterator materialized_use_begin() { return use_iterator(UseList); }
356 const_use_iterator materialized_use_begin() const {
357 return const_use_iterator(UseList);
358 }
359 use_iterator use_begin() {
360 assertModuleIsMaterialized();
361 return materialized_use_begin();
362 }
363 const_use_iterator use_begin() const {
364 assertModuleIsMaterialized();
365 return materialized_use_begin();
366 }
367 use_iterator use_end() { return use_iterator(); }
368 const_use_iterator use_end() const { return const_use_iterator(); }
369 iterator_range<use_iterator> materialized_uses() {
370 return make_range(materialized_use_begin(), use_end());
371 }
372 iterator_range<const_use_iterator> materialized_uses() const {
373 return make_range(materialized_use_begin(), use_end());
374 }
375 iterator_range<use_iterator> uses() {
376 assertModuleIsMaterialized();
377 return materialized_uses();
378 }
379 iterator_range<const_use_iterator> uses() const {
380 assertModuleIsMaterialized();
381 return materialized_uses();
382 }
383
384 bool user_empty() const {
385 assertModuleIsMaterialized();
386 return UseList == nullptr;
387 }
388
389 using user_iterator = user_iterator_impl<User>;
390 using const_user_iterator = user_iterator_impl<const User>;
391
392 user_iterator materialized_user_begin() { return user_iterator(UseList); }
393 const_user_iterator materialized_user_begin() const {
394 return const_user_iterator(UseList);
395 }
396 user_iterator user_begin() {
397 assertModuleIsMaterialized();
398 return materialized_user_begin();
399 }
400 const_user_iterator user_begin() const {
401 assertModuleIsMaterialized();
402 return materialized_user_begin();
403 }
404 user_iterator user_end() { return user_iterator(); }
405 const_user_iterator user_end() const { return const_user_iterator(); }
406 User *user_back() {
407 assertModuleIsMaterialized();
408 return *materialized_user_begin();
409 }
410 const User *user_back() const {
411 assertModuleIsMaterialized();
412 return *materialized_user_begin();
413 }
414 iterator_range<user_iterator> materialized_users() {
415 return make_range(materialized_user_begin(), user_end());
416 }
417 iterator_range<const_user_iterator> materialized_users() const {
418 return make_range(materialized_user_begin(), user_end());
419 }
420 iterator_range<user_iterator> users() {
421 assertModuleIsMaterialized();
422 return materialized_users();
423 }
424 iterator_range<const_user_iterator> users() const {
425 assertModuleIsMaterialized();
426 return materialized_users();
427 }
428
429 /// Return true if there is exactly one user of this value.
430 ///
431 /// This is specialized because it is a common request and does not require
432 /// traversing the whole use list.
433 bool hasOneUse() const {
434 const_use_iterator I = use_begin(), E = use_end();
435 if (I == E) return false;
35
Assuming the condition is false
36
Taking false branch
436 return ++I == E;
37
Returning value, which participates in a condition later
437 }
438
439 /// Return true if this Value has exactly N users.
440 bool hasNUses(unsigned N) const;
441
442 /// Return true if this value has N users or more.
443 ///
444 /// This is logically equivalent to getNumUses() >= N.
445 bool hasNUsesOrMore(unsigned N) const;
446
447 /// Check if this value is used in the specified basic block.
448 bool isUsedInBasicBlock(const BasicBlock *BB) const;
449
450 /// This method computes the number of uses of this Value.
451 ///
452 /// This is a linear time operation. Use hasOneUse, hasNUses, or
453 /// hasNUsesOrMore to check for specific values.
454 unsigned getNumUses() const;
455
456 /// This method should only be used by the Use class.
457 void addUse(Use &U) { U.addToList(&UseList); }
458
459 /// Concrete subclass of this.
460 ///
461 /// An enumeration for keeping track of the concrete subclass of Value that
462 /// is actually instantiated. Values of this enumeration are kept in the
463 /// Value classes SubclassID field. They are used for concrete type
464 /// identification.
465 enum ValueTy {
466#define HANDLE_VALUE(Name) Name##Val,
467#include "llvm/IR/Value.def"
468
469 // Markers:
470#define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
471#include "llvm/IR/Value.def"
472 };
473
474 /// Return an ID for the concrete type of this object.
475 ///
476 /// This is used to implement the classof checks. This should not be used
477 /// for any other purpose, as the values may change as LLVM evolves. Also,
478 /// note that for instructions, the Instruction's opcode is added to
479 /// InstructionVal. So this means three things:
480 /// # there is no value with code InstructionVal (no opcode==0).
481 /// # there are more possible values for the value type than in ValueTy enum.
482 /// # the InstructionVal enumerator must be the highest valued enumerator in
483 /// the ValueTy enum.
484 unsigned getValueID() const {
485 return SubclassID;
486 }
487
488 /// Return the raw optional flags value contained in this value.
489 ///
490 /// This should only be used when testing two Values for equivalence.
491 unsigned getRawSubclassOptionalData() const {
492 return SubclassOptionalData;
493 }
494
495 /// Clear the optional flags contained in this value.
496 void clearSubclassOptionalData() {
497 SubclassOptionalData = 0;
498 }
499
500 /// Check the optional flags for equality.
501 bool hasSameSubclassOptionalData(const Value *V) const {
502 return SubclassOptionalData == V->SubclassOptionalData;
503 }
504
505 /// Return true if there is a value handle associated with this value.
506 bool hasValueHandle() const { return HasValueHandle; }
507
508 /// Return true if there is metadata referencing this value.
509 bool isUsedByMetadata() const { return IsUsedByMD; }
510
511 /// Return true if this value is a swifterror value.
512 ///
513 /// swifterror values can be either a function argument or an alloca with a
514 /// swifterror attribute.
515 bool isSwiftError() const;
516
517 /// Strip off pointer casts, all-zero GEPs and address space casts.
518 ///
519 /// Returns the original uncasted value. If this is called on a non-pointer
520 /// value, it returns 'this'.
521 const Value *stripPointerCasts() const;
522 Value *stripPointerCasts() {
523 return const_cast<Value *>(
524 static_cast<const Value *>(this)->stripPointerCasts());
525 }
526
527 /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
528 ///
529 /// Returns the original uncasted value. If this is called on a non-pointer
530 /// value, it returns 'this'.
531 const Value *stripPointerCastsAndAliases() const;
532 Value *stripPointerCastsAndAliases() {
533 return const_cast<Value *>(
534 static_cast<const Value *>(this)->stripPointerCastsAndAliases());
535 }
536
537 /// Strip off pointer casts, all-zero GEPs and address space casts
538 /// but ensures the representation of the result stays the same.
539 ///
540 /// Returns the original uncasted value with the same representation. If this
541 /// is called on a non-pointer value, it returns 'this'.
542 const Value *stripPointerCastsSameRepresentation() const;
543 Value *stripPointerCastsSameRepresentation() {
544 return const_cast<Value *>(static_cast<const Value *>(this)
545 ->stripPointerCastsSameRepresentation());
546 }
547
548 /// Strip off pointer casts, all-zero GEPs and invariant group info.
549 ///
550 /// Returns the original uncasted value. If this is called on a non-pointer
551 /// value, it returns 'this'. This function should be used only in
552 /// Alias analysis.
553 const Value *stripPointerCastsAndInvariantGroups() const;
554 Value *stripPointerCastsAndInvariantGroups() {
555 return const_cast<Value *>(static_cast<const Value *>(this)
556 ->stripPointerCastsAndInvariantGroups());
557 }
558
559 /// Strip off pointer casts and all-constant inbounds GEPs.
560 ///
561 /// Returns the original pointer value. If this is called on a non-pointer
562 /// value, it returns 'this'.
563 const Value *stripInBoundsConstantOffsets() const;
564 Value *stripInBoundsConstantOffsets() {
565 return const_cast<Value *>(
566 static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
567 }
568
569 /// Accumulate the constant offset this value has compared to a base pointer.
570 /// Only 'getelementptr' instructions (GEPs) with constant indices are
571 /// accumulated but other instructions, e.g., casts, are stripped away as
572 /// well. The accumulated constant offset is added to \p Offset and the base
573 /// pointer is returned.
574 ///
575 /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
576 /// the address space of 'this' pointer value, e.g., use
577 /// DataLayout::getIndexTypeSizeInBits(Ty).
578 ///
579 /// If \p AllowNonInbounds is true, constant offsets in GEPs are stripped and
580 /// accumulated even if the GEP is not "inbounds".
581 ///
582 /// If this is called on a non-pointer value, it returns 'this' and the
583 /// \p Offset is not modified.
584 ///
585 /// Note that this function will never return a nullptr. It will also never
586 /// manipulate the \p Offset in a way that would not match the difference
587 /// between the underlying value and the returned one. Thus, if no constant
588 /// offset was found, the returned value is the underlying one and \p Offset
589 /// is unchanged.
590 const Value *stripAndAccumulateConstantOffsets(const DataLayout &DL,
591 APInt &Offset,
592 bool AllowNonInbounds) const;
593 Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
594 bool AllowNonInbounds) {
595 return const_cast<Value *>(
596 static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
597 DL, Offset, AllowNonInbounds));
598 }
599
600 /// This is a wrapper around stripAndAccumulateConstantOffsets with the
601 /// in-bounds requirement set to false.
602 const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
603 APInt &Offset) const {
604 return stripAndAccumulateConstantOffsets(DL, Offset,
605 /* AllowNonInbounds */ false);
606 }
607 Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
608 APInt &Offset) {
609 return stripAndAccumulateConstantOffsets(DL, Offset,
610 /* AllowNonInbounds */ false);
611 }
612
613 /// Strip off pointer casts and inbounds GEPs.
614 ///
615 /// Returns the original pointer value. If this is called on a non-pointer
616 /// value, it returns 'this'.
617 const Value *stripInBoundsOffsets() const;
618 Value *stripInBoundsOffsets() {
619 return const_cast<Value *>(
620 static_cast<const Value *>(this)->stripInBoundsOffsets());
621 }
622
623 /// Returns the number of bytes known to be dereferenceable for the
624 /// pointer value.
625 ///
626 /// If CanBeNull is set by this function the pointer can either be null or be
627 /// dereferenceable up to the returned number of bytes.
628 uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
629 bool &CanBeNull) const;
630
631 /// Returns an alignment of the pointer value.
632 ///
633 /// Returns an alignment which is either specified explicitly, e.g. via
634 /// align attribute of a function argument, or guaranteed by DataLayout.
635 MaybeAlign getPointerAlignment(const DataLayout &DL) const;
636
637 /// Translate PHI node to its predecessor from the given basic block.
638 ///
639 /// If this value is a PHI node with CurBB as its parent, return the value in
640 /// the PHI node corresponding to PredBB. If not, return ourself. This is
641 /// useful if you want to know the value something has in a predecessor
642 /// block.
643 const Value *DoPHITranslation(const BasicBlock *CurBB,
644 const BasicBlock *PredBB) const;
645 Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
646 return const_cast<Value *>(
647 static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
648 }
649
650 /// The maximum alignment for instructions.
651 ///
652 /// This is the greatest alignment value supported by load, store, and alloca
653 /// instructions, and global values.
654 static const unsigned MaxAlignmentExponent = 29;
655 static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent;
656
657 /// Mutate the type of this Value to be of the specified type.
658 ///
659 /// Note that this is an extremely dangerous operation which can create
660 /// completely invalid IR very easily. It is strongly recommended that you
661 /// recreate IR objects with the right types instead of mutating them in
662 /// place.
663 void mutateType(Type *Ty) {
664 VTy = Ty;
665 }
666
667 /// Sort the use-list.
668 ///
669 /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
670 /// expected to compare two \a Use references.
671 template <class Compare> void sortUseList(Compare Cmp);
672
673 /// Reverse the use-list.
674 void reverseUseList();
675
676private:
677 /// Merge two lists together.
678 ///
679 /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
680 /// "equal" items from L before items from R.
681 ///
682 /// \return the first element in the list.
683 ///
684 /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
685 template <class Compare>
686 static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
687 Use *Merged;
688 Use **Next = &Merged;
689
690 while (true) {
691 if (!L) {
692 *Next = R;
693 break;
694 }
695 if (!R) {
696 *Next = L;
697 break;
698 }
699 if (Cmp(*R, *L)) {
700 *Next = R;
701 Next = &R->Next;
702 R = R->Next;
703 } else {
704 *Next = L;
705 Next = &L->Next;
706 L = L->Next;
707 }
708 }
709
710 return Merged;
711 }
712
713protected:
714 unsigned short getSubclassDataFromValue() const { return SubclassData; }
715 void setValueSubclassData(unsigned short D) { SubclassData = D; }
716};
717
718struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
719
720/// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
721/// Those don't work because Value and Instruction's destructors are protected,
722/// aren't virtual, and won't destroy the complete object.
723using unique_value = std::unique_ptr<Value, ValueDeleter>;
724
725inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
726 V.print(OS);
727 return OS;
728}
729
730void Use::set(Value *V) {
731 if (Val) removeFromList();
732 Val = V;
733 if (V) V->addUse(*this);
734}
735
736Value *Use::operator=(Value *RHS) {
737 set(RHS);
738 return RHS;
739}
740
741const Use &Use::operator=(const Use &RHS) {
742 set(RHS.Val);
743 return *this;
744}
745
746template <class Compare> void Value::sortUseList(Compare Cmp) {
747 if (!UseList || !UseList->Next)
748 // No need to sort 0 or 1 uses.
749 return;
750
751 // Note: this function completely ignores Prev pointers until the end when
752 // they're fixed en masse.
753
754 // Create a binomial vector of sorted lists, visiting uses one at a time and
755 // merging lists as necessary.
756 const unsigned MaxSlots = 32;
757 Use *Slots[MaxSlots];
758
759 // Collect the first use, turning it into a single-item list.
760 Use *Next = UseList->Next;
761 UseList->Next = nullptr;
762 unsigned NumSlots = 1;
763 Slots[0] = UseList;
764
765 // Collect all but the last use.
766 while (Next->Next) {
767 Use *Current = Next;
768 Next = Current->Next;
769
770 // Turn Current into a single-item list.
771 Current->Next = nullptr;
772
773 // Save Current in the first available slot, merging on collisions.
774 unsigned I;
775 for (I = 0; I < NumSlots; ++I) {
776 if (!Slots[I])
777 break;
778
779 // Merge two lists, doubling the size of Current and emptying slot I.
780 //
781 // Since the uses in Slots[I] originally preceded those in Current, send
782 // Slots[I] in as the left parameter to maintain a stable sort.
783 Current = mergeUseLists(Slots[I], Current, Cmp);
784 Slots[I] = nullptr;
785 }
786 // Check if this is a new slot.
787 if (I == NumSlots) {
788 ++NumSlots;
789 assert(NumSlots <= MaxSlots && "Use list bigger than 2^32")((NumSlots <= MaxSlots && "Use list bigger than 2^32"
) ? static_cast<void> (0) : __assert_fail ("NumSlots <= MaxSlots && \"Use list bigger than 2^32\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 789, __PRETTY_FUNCTION__))
;
790 }
791
792 // Found an open slot.
793 Slots[I] = Current;
794 }
795
796 // Merge all the lists together.
797 assert(Next && "Expected one more Use")((Next && "Expected one more Use") ? static_cast<void
> (0) : __assert_fail ("Next && \"Expected one more Use\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 797, __PRETTY_FUNCTION__))
;
798 assert(!Next->Next && "Expected only one Use")((!Next->Next && "Expected only one Use") ? static_cast
<void> (0) : __assert_fail ("!Next->Next && \"Expected only one Use\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Value.h"
, 798, __PRETTY_FUNCTION__))
;
799 UseList = Next;
800 for (unsigned I = 0; I < NumSlots; ++I)
801 if (Slots[I])
802 // Since the uses in Slots[I] originally preceded those in UseList, send
803 // Slots[I] in as the left parameter to maintain a stable sort.
804 UseList = mergeUseLists(Slots[I], UseList, Cmp);
805
806 // Fix the Prev pointers.
807 for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
808 I->setPrev(Prev);
809 Prev = &I->Next;
810 }
811}
812
813// isa - Provide some specializations of isa so that we don't have to include
814// the subtype header files to test to see if the value is a subclass...
815//
816template <> struct isa_impl<Constant, Value> {
817 static inline bool doit(const Value &Val) {
818 static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
819 return Val.getValueID() <= Value::ConstantLastVal;
820 }
821};
822
823template <> struct isa_impl<ConstantData, Value> {
824 static inline bool doit(const Value &Val) {
825 return Val.getValueID() >= Value::ConstantDataFirstVal &&
826 Val.getValueID() <= Value::ConstantDataLastVal;
827 }
828};
829
830template <> struct isa_impl<ConstantAggregate, Value> {
831 static inline bool doit(const Value &Val) {
832 return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
833 Val.getValueID() <= Value::ConstantAggregateLastVal;
834 }
835};
836
837template <> struct isa_impl<Argument, Value> {
838 static inline bool doit (const Value &Val) {
839 return Val.getValueID() == Value::ArgumentVal;
840 }
841};
842
843template <> struct isa_impl<InlineAsm, Value> {
844 static inline bool doit(const Value &Val) {
845 return Val.getValueID() == Value::InlineAsmVal;
846 }
847};
848
849template <> struct isa_impl<Instruction, Value> {
850 static inline bool doit(const Value &Val) {
851 return Val.getValueID() >= Value::InstructionVal;
852 }
853};
854
855template <> struct isa_impl<BasicBlock, Value> {
856 static inline bool doit(const Value &Val) {
857 return Val.getValueID() == Value::BasicBlockVal;
858 }
859};
860
861template <> struct isa_impl<Function, Value> {
862 static inline bool doit(const Value &Val) {
863 return Val.getValueID() == Value::FunctionVal;
864 }
865};
866
867template <> struct isa_impl<GlobalVariable, Value> {
868 static inline bool doit(const Value &Val) {
869 return Val.getValueID() == Value::GlobalVariableVal;
870 }
871};
872
873template <> struct isa_impl<GlobalAlias, Value> {
874 static inline bool doit(const Value &Val) {
875 return Val.getValueID() == Value::GlobalAliasVal;
876 }
877};
878
879template <> struct isa_impl<GlobalIFunc, Value> {
880 static inline bool doit(const Value &Val) {
881 return Val.getValueID() == Value::GlobalIFuncVal;
882 }
883};
884
885template <> struct isa_impl<GlobalIndirectSymbol, Value> {
886 static inline bool doit(const Value &Val) {
887 return isa<GlobalAlias>(Val) || isa<GlobalIFunc>(Val);
888 }
889};
890
891template <> struct isa_impl<GlobalValue, Value> {
892 static inline bool doit(const Value &Val) {
893 return isa<GlobalObject>(Val) || isa<GlobalIndirectSymbol>(Val);
894 }
895};
896
897template <> struct isa_impl<GlobalObject, Value> {
898 static inline bool doit(const Value &Val) {
899 return isa<GlobalVariable>(Val) || isa<Function>(Val);
900 }
901};
902
903// Create wrappers for C Binding types (see CBindingWrapping.h).
904DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)inline Value *unwrap(LLVMValueRef P) { return reinterpret_cast
<Value*>(P); } inline LLVMValueRef wrap(const Value *P)
{ return reinterpret_cast<LLVMValueRef>(const_cast<
Value*>(P)); } template<typename T> inline T *unwrap
(LLVMValueRef P) { return cast<T>(unwrap(P)); }
905
906// Specialized opaque value conversions.
907inline Value **unwrap(LLVMValueRef *Vals) {
908 return reinterpret_cast<Value**>(Vals);
909}
910
911template<typename T>
912inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
913#ifndef NDEBUG
914 for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
915 unwrap<T>(*I); // For side effect of calling assert on invalid usage.
916#endif
917 (void)Length;
918 return reinterpret_cast<T**>(Vals);
919}
920
921inline LLVMValueRef *wrap(const Value **Vals) {
922 return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
923}
924
925} // end namespace llvm
926
927#endif // LLVM_IR_VALUE_H

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.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
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
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, MaybeAlign Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, MaybeAlign 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 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
116 }
117 void setAlignment(MaybeAlign Align);
118
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
123
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
128 }
129
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
134 }
135
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
139 }
140
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
145 }
146
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
150 }
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 }
154
155private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// LoadInst Class
165//===----------------------------------------------------------------------===//
166
167/// An instruction for reading from memory. This uses the SubclassData field in
168/// Value to store whether or not the load is volatile.
169class LoadInst : public UnaryInstruction {
170 void AssertOK();
171
172protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
175
176 LoadInst *cloneImpl() const;
177
178public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 MaybeAlign Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 MaybeAlign Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 MaybeAlign Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 MaybeAlign Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
197
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, MaybeAlign Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
239 }
240
241 /// Return the alignment of the access that is being performed.
242 unsigned getAlignment() const {
243 if (const auto MA =
244 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
245 return MA->value();
246 return 0;
247 }
248
249 void setAlignment(MaybeAlign Align);
250
251 /// Returns the ordering constraint of this load instruction.
252 AtomicOrdering getOrdering() const {
253 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
254 }
255
256 /// Sets the ordering constraint of this load instruction. May not be Release
257 /// or AcquireRelease.
258 void setOrdering(AtomicOrdering Ordering) {
259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
260 ((unsigned)Ordering << 7));
261 }
262
263 /// Returns the synchronization scope ID of this load instruction.
264 SyncScope::ID getSyncScopeID() const {
265 return SSID;
266 }
267
268 /// Sets the synchronization scope ID of this load instruction.
269 void setSyncScopeID(SyncScope::ID SSID) {
270 this->SSID = SSID;
271 }
272
273 /// Sets the ordering constraint and the synchronization scope ID of this load
274 /// instruction.
275 void setAtomic(AtomicOrdering Ordering,
276 SyncScope::ID SSID = SyncScope::System) {
277 setOrdering(Ordering);
278 setSyncScopeID(SSID);
279 }
280
281 bool isSimple() const { return !isAtomic() && !isVolatile(); }
282
283 bool isUnordered() const {
284 return (getOrdering() == AtomicOrdering::NotAtomic ||
285 getOrdering() == AtomicOrdering::Unordered) &&
286 !isVolatile();
287 }
288
289 Value *getPointerOperand() { return getOperand(0); }
290 const Value *getPointerOperand() const { return getOperand(0); }
291 static unsigned getPointerOperandIndex() { return 0U; }
292 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
293
294 /// Returns the address space of the pointer operand.
295 unsigned getPointerAddressSpace() const {
296 return getPointerOperandType()->getPointerAddressSpace();
297 }
298
299 // Methods for support type inquiry through isa, cast, and dyn_cast:
300 static bool classof(const Instruction *I) {
301 return I->getOpcode() == Instruction::Load;
302 }
303 static bool classof(const Value *V) {
304 return isa<Instruction>(V) && classof(cast<Instruction>(V));
305 }
306
307private:
308 // Shadow Instruction::setInstructionSubclassData with a private forwarding
309 // method so that subclasses cannot accidentally use it.
310 void setInstructionSubclassData(unsigned short D) {
311 Instruction::setInstructionSubclassData(D);
312 }
313
314 /// The synchronization scope ID of this load instruction. Not quite enough
315 /// room in SubClassData for everything, so synchronization scope ID gets its
316 /// own field.
317 SyncScope::ID SSID;
318};
319
320//===----------------------------------------------------------------------===//
321// StoreInst Class
322//===----------------------------------------------------------------------===//
323
324/// An instruction for storing to memory.
325class StoreInst : public Instruction {
326 void AssertOK();
327
328protected:
329 // Note: Instruction needs to be a friend here to call cloneImpl.
330 friend class Instruction;
331
332 StoreInst *cloneImpl() const;
333
334public:
335 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
336 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
338 Instruction *InsertBefore = nullptr);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
341 Instruction *InsertBefore = nullptr);
342 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
343 BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
345 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
346 Instruction *InsertBefore = nullptr);
347 StoreInst(Value *Val, Value *Ptr, bool isVolatile, MaybeAlign Align,
348 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd);
349
350 // allocate space for exactly two operands
351 void *operator new(size_t s) {
352 return User::operator new(s, 2);
353 }
354
355 /// Return true if this is a store to a volatile memory location.
356 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
357
358 /// Specify whether this is a volatile store or not.
359 void setVolatile(bool V) {
360 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
361 (V ? 1 : 0));
362 }
363
364 /// Transparently provide more efficient getOperand methods.
365 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
;
366
367 /// Return the alignment of the access that is being performed
368 unsigned getAlignment() const {
369 if (const auto MA =
370 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
371 return MA->value();
372 return 0;
373 }
374
375 void setAlignment(MaybeAlign Align);
376
377 /// Returns the ordering constraint of this store instruction.
378 AtomicOrdering getOrdering() const {
379 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
380 }
381
382 /// Sets the ordering constraint of this store instruction. May not be
383 /// Acquire or AcquireRelease.
384 void setOrdering(AtomicOrdering Ordering) {
385 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
386 ((unsigned)Ordering << 7));
387 }
388
389 /// Returns the synchronization scope ID of this store instruction.
390 SyncScope::ID getSyncScopeID() const {
391 return SSID;
392 }
393
394 /// Sets the synchronization scope ID of this store instruction.
395 void setSyncScopeID(SyncScope::ID SSID) {
396 this->SSID = SSID;
397 }
398
399 /// Sets the ordering constraint and the synchronization scope ID of this
400 /// store instruction.
401 void setAtomic(AtomicOrdering Ordering,
402 SyncScope::ID SSID = SyncScope::System) {
403 setOrdering(Ordering);
404 setSyncScopeID(SSID);
405 }
406
407 bool isSimple() const { return !isAtomic() && !isVolatile(); }
408
409 bool isUnordered() const {
410 return (getOrdering() == AtomicOrdering::NotAtomic ||
411 getOrdering() == AtomicOrdering::Unordered) &&
412 !isVolatile();
413 }
414
415 Value *getValueOperand() { return getOperand(0); }
416 const Value *getValueOperand() const { return getOperand(0); }
417
418 Value *getPointerOperand() { return getOperand(1); }
419 const Value *getPointerOperand() const { return getOperand(1); }
420 static unsigned getPointerOperandIndex() { return 1U; }
421 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
422
423 /// Returns the address space of the pointer operand.
424 unsigned getPointerAddressSpace() const {
425 return getPointerOperandType()->getPointerAddressSpace();
426 }
427
428 // Methods for support type inquiry through isa, cast, and dyn_cast:
429 static bool classof(const Instruction *I) {
430 return I->getOpcode() == Instruction::Store;
431 }
432 static bool classof(const Value *V) {
433 return isa<Instruction>(V) && classof(cast<Instruction>(V));
434 }
435
436private:
437 // Shadow Instruction::setInstructionSubclassData with a private forwarding
438 // method so that subclasses cannot accidentally use it.
439 void setInstructionSubclassData(unsigned short D) {
440 Instruction::setInstructionSubclassData(D);
441 }
442
443 /// The synchronization scope ID of this store instruction. Not quite enough
444 /// room in SubClassData for everything, so synchronization scope ID gets its
445 /// own field.
446 SyncScope::ID SSID;
447};
448
449template <>
450struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
451};
452
453DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 453, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 453, __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
); }
454
455//===----------------------------------------------------------------------===//
456// FenceInst Class
457//===----------------------------------------------------------------------===//
458
459/// An instruction for ordering other memory operations.
460class FenceInst : public Instruction {
461 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
462
463protected:
464 // Note: Instruction needs to be a friend here to call cloneImpl.
465 friend class Instruction;
466
467 FenceInst *cloneImpl() const;
468
469public:
470 // Ordering may only be Acquire, Release, AcquireRelease, or
471 // SequentiallyConsistent.
472 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
473 SyncScope::ID SSID = SyncScope::System,
474 Instruction *InsertBefore = nullptr);
475 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
476 BasicBlock *InsertAtEnd);
477
478 // allocate space for exactly zero operands
479 void *operator new(size_t s) {
480 return User::operator new(s, 0);
481 }
482
483 /// Returns the ordering constraint of this fence instruction.
484 AtomicOrdering getOrdering() const {
485 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
486 }
487
488 /// Sets the ordering constraint of this fence instruction. May only be
489 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
490 void setOrdering(AtomicOrdering Ordering) {
491 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
492 ((unsigned)Ordering << 1));
493 }
494
495 /// Returns the synchronization scope ID of this fence instruction.
496 SyncScope::ID getSyncScopeID() const {
497 return SSID;
498 }
499
500 /// Sets the synchronization scope ID of this fence instruction.
501 void setSyncScopeID(SyncScope::ID SSID) {
502 this->SSID = SSID;
503 }
504
505 // Methods for support type inquiry through isa, cast, and dyn_cast:
506 static bool classof(const Instruction *I) {
507 return I->getOpcode() == Instruction::Fence;
508 }
509 static bool classof(const Value *V) {
510 return isa<Instruction>(V) && classof(cast<Instruction>(V));
511 }
512
513private:
514 // Shadow Instruction::setInstructionSubclassData with a private forwarding
515 // method so that subclasses cannot accidentally use it.
516 void setInstructionSubclassData(unsigned short D) {
517 Instruction::setInstructionSubclassData(D);
518 }
519
520 /// The synchronization scope ID of this fence instruction. Not quite enough
521 /// room in SubClassData for everything, so synchronization scope ID gets its
522 /// own field.
523 SyncScope::ID SSID;
524};
525
526//===----------------------------------------------------------------------===//
527// AtomicCmpXchgInst Class
528//===----------------------------------------------------------------------===//
529
530/// An instruction that atomically checks whether a
531/// specified value is in a memory location, and, if it is, stores a new value
532/// there. The value returned by this instruction is a pair containing the
533/// original value as first element, and an i1 indicating success (true) or
534/// failure (false) as second element.
535///
536class AtomicCmpXchgInst : public Instruction {
537 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
538 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
539 SyncScope::ID SSID);
540
541protected:
542 // Note: Instruction needs to be a friend here to call cloneImpl.
543 friend class Instruction;
544
545 AtomicCmpXchgInst *cloneImpl() const;
546
547public:
548 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
549 AtomicOrdering SuccessOrdering,
550 AtomicOrdering FailureOrdering,
551 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
552 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
553 AtomicOrdering SuccessOrdering,
554 AtomicOrdering FailureOrdering,
555 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
556
557 // allocate space for exactly three operands
558 void *operator new(size_t s) {
559 return User::operator new(s, 3);
560 }
561
562 /// Return true if this is a cmpxchg from a volatile memory
563 /// location.
564 ///
565 bool isVolatile() const {
566 return getSubclassDataFromInstruction() & 1;
567 }
568
569 /// Specify whether this is a volatile cmpxchg.
570 ///
571 void setVolatile(bool V) {
572 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
573 (unsigned)V);
574 }
575
576 /// Return true if this cmpxchg may spuriously fail.
577 bool isWeak() const {
578 return getSubclassDataFromInstruction() & 0x100;
579 }
580
581 void setWeak(bool IsWeak) {
582 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
583 (IsWeak << 8));
584 }
585
586 /// Transparently provide more efficient getOperand methods.
587 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
;
588
589 /// Returns the success ordering constraint of this cmpxchg instruction.
590 AtomicOrdering getSuccessOrdering() const {
591 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
592 }
593
594 /// Sets the success ordering constraint of this cmpxchg instruction.
595 void setSuccessOrdering(AtomicOrdering Ordering) {
596 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 597, __PRETTY_FUNCTION__))
597 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 597, __PRETTY_FUNCTION__))
;
598 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
599 ((unsigned)Ordering << 2));
600 }
601
602 /// Returns the failure ordering constraint of this cmpxchg instruction.
603 AtomicOrdering getFailureOrdering() const {
604 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
605 }
606
607 /// Sets the failure ordering constraint of this cmpxchg instruction.
608 void setFailureOrdering(AtomicOrdering Ordering) {
609 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 610, __PRETTY_FUNCTION__))
610 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 610, __PRETTY_FUNCTION__))
;
611 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
612 ((unsigned)Ordering << 5));
613 }
614
615 /// Returns the synchronization scope ID of this cmpxchg instruction.
616 SyncScope::ID getSyncScopeID() const {
617 return SSID;
618 }
619
620 /// Sets the synchronization scope ID of this cmpxchg instruction.
621 void setSyncScopeID(SyncScope::ID SSID) {
622 this->SSID = SSID;
623 }
624
625 Value *getPointerOperand() { return getOperand(0); }
626 const Value *getPointerOperand() const { return getOperand(0); }
627 static unsigned getPointerOperandIndex() { return 0U; }
628
629 Value *getCompareOperand() { return getOperand(1); }
630 const Value *getCompareOperand() const { return getOperand(1); }
631
632 Value *getNewValOperand() { return getOperand(2); }
633 const Value *getNewValOperand() const { return getOperand(2); }
634
635 /// Returns the address space of the pointer operand.
636 unsigned getPointerAddressSpace() const {
637 return getPointerOperand()->getType()->getPointerAddressSpace();
638 }
639
640 /// Returns the strongest permitted ordering on failure, given the
641 /// desired ordering on success.
642 ///
643 /// If the comparison in a cmpxchg operation fails, there is no atomic store
644 /// so release semantics cannot be provided. So this function drops explicit
645 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
646 /// operation would remain SequentiallyConsistent.
647 static AtomicOrdering
648 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
649 switch (SuccessOrdering) {
650 default:
651 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 651)
;
652 case AtomicOrdering::Release:
653 case AtomicOrdering::Monotonic:
654 return AtomicOrdering::Monotonic;
655 case AtomicOrdering::AcquireRelease:
656 case AtomicOrdering::Acquire:
657 return AtomicOrdering::Acquire;
658 case AtomicOrdering::SequentiallyConsistent:
659 return AtomicOrdering::SequentiallyConsistent;
660 }
661 }
662
663 // Methods for support type inquiry through isa, cast, and dyn_cast:
664 static bool classof(const Instruction *I) {
665 return I->getOpcode() == Instruction::AtomicCmpXchg;
666 }
667 static bool classof(const Value *V) {
668 return isa<Instruction>(V) && classof(cast<Instruction>(V));
669 }
670
671private:
672 // Shadow Instruction::setInstructionSubclassData with a private forwarding
673 // method so that subclasses cannot accidentally use it.
674 void setInstructionSubclassData(unsigned short D) {
675 Instruction::setInstructionSubclassData(D);
676 }
677
678 /// The synchronization scope ID of this cmpxchg instruction. Not quite
679 /// enough room in SubClassData for everything, so synchronization scope ID
680 /// gets its own field.
681 SyncScope::ID SSID;
682};
683
684template <>
685struct OperandTraits<AtomicCmpXchgInst> :
686 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
687};
688
689DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 689, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 689, __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); }
690
691//===----------------------------------------------------------------------===//
692// AtomicRMWInst Class
693//===----------------------------------------------------------------------===//
694
695/// an instruction that atomically reads a memory location,
696/// combines it with another value, and then stores the result back. Returns
697/// the old value.
698///
699class AtomicRMWInst : public Instruction {
700protected:
701 // Note: Instruction needs to be a friend here to call cloneImpl.
702 friend class Instruction;
703
704 AtomicRMWInst *cloneImpl() const;
705
706public:
707 /// This enumeration lists the possible modifications atomicrmw can make. In
708 /// the descriptions, 'p' is the pointer to the instruction's memory location,
709 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
710 /// instruction. These instructions always return 'old'.
711 enum BinOp {
712 /// *p = v
713 Xchg,
714 /// *p = old + v
715 Add,
716 /// *p = old - v
717 Sub,
718 /// *p = old & v
719 And,
720 /// *p = ~(old & v)
721 Nand,
722 /// *p = old | v
723 Or,
724 /// *p = old ^ v
725 Xor,
726 /// *p = old >signed v ? old : v
727 Max,
728 /// *p = old <signed v ? old : v
729 Min,
730 /// *p = old >unsigned v ? old : v
731 UMax,
732 /// *p = old <unsigned v ? old : v
733 UMin,
734
735 /// *p = old + v
736 FAdd,
737
738 /// *p = old - v
739 FSub,
740
741 FIRST_BINOP = Xchg,
742 LAST_BINOP = FSub,
743 BAD_BINOP
744 };
745
746 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
747 AtomicOrdering Ordering, SyncScope::ID SSID,
748 Instruction *InsertBefore = nullptr);
749 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
750 AtomicOrdering Ordering, SyncScope::ID SSID,
751 BasicBlock *InsertAtEnd);
752
753 // allocate space for exactly two operands
754 void *operator new(size_t s) {
755 return User::operator new(s, 2);
756 }
757
758 BinOp getOperation() const {
759 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
760 }
761
762 static StringRef getOperationName(BinOp Op);
763
764 static bool isFPOperation(BinOp Op) {
765 switch (Op) {
766 case AtomicRMWInst::FAdd:
767 case AtomicRMWInst::FSub:
768 return true;
769 default:
770 return false;
771 }
772 }
773
774 void setOperation(BinOp Operation) {
775 unsigned short SubclassData = getSubclassDataFromInstruction();
776 setInstructionSubclassData((SubclassData & 31) |
777 (Operation << 5));
778 }
779
780 /// Return true if this is a RMW on a volatile memory location.
781 ///
782 bool isVolatile() const {
783 return getSubclassDataFromInstruction() & 1;
784 }
785
786 /// Specify whether this is a volatile RMW or not.
787 ///
788 void setVolatile(bool V) {
789 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
790 (unsigned)V);
791 }
792
793 /// Transparently provide more efficient getOperand methods.
794 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
;
795
796 /// Returns the ordering constraint of this rmw instruction.
797 AtomicOrdering getOrdering() const {
798 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
799 }
800
801 /// Sets the ordering constraint of this rmw instruction.
802 void setOrdering(AtomicOrdering Ordering) {
803 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 804, __PRETTY_FUNCTION__))
804 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 804, __PRETTY_FUNCTION__))
;
805 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
806 ((unsigned)Ordering << 2));
807 }
808
809 /// Returns the synchronization scope ID of this rmw instruction.
810 SyncScope::ID getSyncScopeID() const {
811 return SSID;
812 }
813
814 /// Sets the synchronization scope ID of this rmw instruction.
815 void setSyncScopeID(SyncScope::ID SSID) {
816 this->SSID = SSID;
817 }
818
819 Value *getPointerOperand() { return getOperand(0); }
820 const Value *getPointerOperand() const { return getOperand(0); }
821 static unsigned getPointerOperandIndex() { return 0U; }
822
823 Value *getValOperand() { return getOperand(1); }
824 const Value *getValOperand() const { return getOperand(1); }
825
826 /// Returns the address space of the pointer operand.
827 unsigned getPointerAddressSpace() const {
828 return getPointerOperand()->getType()->getPointerAddressSpace();
829 }
830
831 bool isFloatingPointOperation() const {
832 return isFPOperation(getOperation());
833 }
834
835 // Methods for support type inquiry through isa, cast, and dyn_cast:
836 static bool classof(const Instruction *I) {
837 return I->getOpcode() == Instruction::AtomicRMW;
838 }
839 static bool classof(const Value *V) {
840 return isa<Instruction>(V) && classof(cast<Instruction>(V));
841 }
842
843private:
844 void Init(BinOp Operation, Value *Ptr, Value *Val,
845 AtomicOrdering Ordering, SyncScope::ID SSID);
846
847 // Shadow Instruction::setInstructionSubclassData with a private forwarding
848 // method so that subclasses cannot accidentally use it.
849 void setInstructionSubclassData(unsigned short D) {
850 Instruction::setInstructionSubclassData(D);
851 }
852
853 /// The synchronization scope ID of this rmw instruction. Not quite enough
854 /// room in SubClassData for everything, so synchronization scope ID gets its
855 /// own field.
856 SyncScope::ID SSID;
857};
858
859template <>
860struct OperandTraits<AtomicRMWInst>
861 : public FixedNumOperandTraits<AtomicRMWInst,2> {
862};
863
864DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 864, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 864, __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); }
865
866//===----------------------------------------------------------------------===//
867// GetElementPtrInst Class
868//===----------------------------------------------------------------------===//
869
870// checkGEPType - Simple wrapper function to give a better assertion failure
871// message on bad indexes for a gep instruction.
872//
873inline Type *checkGEPType(Type *Ty) {
874 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 874, __PRETTY_FUNCTION__))
;
875 return Ty;
876}
877
878/// an instruction for type-safe pointer arithmetic to
879/// access elements of arrays and structs
880///
881class GetElementPtrInst : public Instruction {
882 Type *SourceElementType;
883 Type *ResultElementType;
884
885 GetElementPtrInst(const GetElementPtrInst &GEPI);
886
887 /// Constructors - Create a getelementptr instruction with a base pointer an
888 /// list of indices. The first ctor can optionally insert before an existing
889 /// instruction, the second appends the new instruction to the specified
890 /// BasicBlock.
891 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
892 ArrayRef<Value *> IdxList, unsigned Values,
893 const Twine &NameStr, Instruction *InsertBefore);
894 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
895 ArrayRef<Value *> IdxList, unsigned Values,
896 const Twine &NameStr, BasicBlock *InsertAtEnd);
897
898 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
899
900protected:
901 // Note: Instruction needs to be a friend here to call cloneImpl.
902 friend class Instruction;
903
904 GetElementPtrInst *cloneImpl() const;
905
906public:
907 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
908 ArrayRef<Value *> IdxList,
909 const Twine &NameStr = "",
910 Instruction *InsertBefore = nullptr) {
911 unsigned Values = 1 + unsigned(IdxList.size());
912 if (!PointeeType)
913 PointeeType =
914 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
915 else
916 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
917 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
918 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 918, __PRETTY_FUNCTION__))
;
919 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
920 NameStr, InsertBefore);
921 }
922
923 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
924 ArrayRef<Value *> IdxList,
925 const Twine &NameStr,
926 BasicBlock *InsertAtEnd) {
927 unsigned Values = 1 + unsigned(IdxList.size());
928 if (!PointeeType)
929 PointeeType =
930 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
931 else
932 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
933 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
934 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 934, __PRETTY_FUNCTION__))
;
935 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
936 NameStr, InsertAtEnd);
937 }
938
939 /// Create an "inbounds" getelementptr. See the documentation for the
940 /// "inbounds" flag in LangRef.html for details.
941 static GetElementPtrInst *CreateInBounds(Value *Ptr,
942 ArrayRef<Value *> IdxList,
943 const Twine &NameStr = "",
944 Instruction *InsertBefore = nullptr){
945 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
946 }
947
948 static GetElementPtrInst *
949 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
950 const Twine &NameStr = "",
951 Instruction *InsertBefore = nullptr) {
952 GetElementPtrInst *GEP =
953 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
954 GEP->setIsInBounds(true);
955 return GEP;
956 }
957
958 static GetElementPtrInst *CreateInBounds(Value *Ptr,
959 ArrayRef<Value *> IdxList,
960 const Twine &NameStr,
961 BasicBlock *InsertAtEnd) {
962 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
963 }
964
965 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
966 ArrayRef<Value *> IdxList,
967 const Twine &NameStr,
968 BasicBlock *InsertAtEnd) {
969 GetElementPtrInst *GEP =
970 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
971 GEP->setIsInBounds(true);
972 return GEP;
973 }
974
975 /// Transparently provide more efficient getOperand methods.
976 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
;
977
978 Type *getSourceElementType() const { return SourceElementType; }
979
980 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
981 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
982
983 Type *getResultElementType() const {
984 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 985, __PRETTY_FUNCTION__))
985 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 985, __PRETTY_FUNCTION__))
;
986 return ResultElementType;
987 }
988
989 /// Returns the address space of this instruction's pointer type.
990 unsigned getAddressSpace() const {
991 // Note that this is always the same as the pointer operand's address space
992 // and that is cheaper to compute, so cheat here.
993 return getPointerAddressSpace();
994 }
995
996 /// Returns the type of the element that would be loaded with
997 /// a load instruction with the specified parameters.
998 ///
999 /// Null is returned if the indices are invalid for the specified
1000 /// pointer type.
1001 ///
1002 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1003 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1004 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1005
1006 inline op_iterator idx_begin() { return op_begin()+1; }
1007 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1008 inline op_iterator idx_end() { return op_end(); }
1009 inline const_op_iterator idx_end() const { return op_end(); }
1010
1011 inline iterator_range<op_iterator> indices() {
1012 return make_range(idx_begin(), idx_end());
1013 }
1014
1015 inline iterator_range<const_op_iterator> indices() const {
1016 return make_range(idx_begin(), idx_end());
1017 }
1018
1019 Value *getPointerOperand() {
1020 return getOperand(0);
1021 }
1022 const Value *getPointerOperand() const {
1023 return getOperand(0);
1024 }
1025 static unsigned getPointerOperandIndex() {
1026 return 0U; // get index for modifying correct operand.
1027 }
1028
1029 /// Method to return the pointer operand as a
1030 /// PointerType.
1031 Type *getPointerOperandType() const {
1032 return getPointerOperand()->getType();
1033 }
1034
1035 /// Returns the address space of the pointer operand.
1036 unsigned getPointerAddressSpace() const {
1037 return getPointerOperandType()->getPointerAddressSpace();
1038 }
1039
1040 /// Returns the pointer type returned by the GEP
1041 /// instruction, which may be a vector of pointers.
1042 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1043 ArrayRef<Value *> IdxList) {
1044 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1045 Ptr->getType()->getPointerAddressSpace());
1046 // Vector GEP
1047 if (Ptr->getType()->isVectorTy()) {
1048 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1049 return VectorType::get(PtrTy, NumElem);
1050 }
1051 for (Value *Index : IdxList)
1052 if (Index->getType()->isVectorTy()) {
1053 unsigned NumElem = Index->getType()->getVectorNumElements();
1054 return VectorType::get(PtrTy, NumElem);
1055 }
1056 // Scalar GEP
1057 return PtrTy;
1058 }
1059
1060 unsigned getNumIndices() const { // Note: always non-negative
1061 return getNumOperands() - 1;
1062 }
1063
1064 bool hasIndices() const {
1065 return getNumOperands() > 1;
1066 }
1067
1068 /// Return true if all of the indices of this GEP are
1069 /// zeros. If so, the result pointer and the first operand have the same
1070 /// value, just potentially different types.
1071 bool hasAllZeroIndices() const;
1072
1073 /// Return true if all of the indices of this GEP are
1074 /// constant integers. If so, the result pointer and the first operand have
1075 /// a constant offset between them.
1076 bool hasAllConstantIndices() const;
1077
1078 /// Set or clear the inbounds flag on this GEP instruction.
1079 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1080 void setIsInBounds(bool b = true);
1081
1082 /// Determine whether the GEP has the inbounds flag.
1083 bool isInBounds() const;
1084
1085 /// Accumulate the constant address offset of this GEP if possible.
1086 ///
1087 /// This routine accepts an APInt into which it will accumulate the constant
1088 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1089 /// all-constant, it returns false and the value of the offset APInt is
1090 /// undefined (it is *not* preserved!). The APInt passed into this routine
1091 /// must be at least as wide as the IntPtr type for the address space of
1092 /// the base GEP pointer.
1093 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1094
1095 // Methods for support type inquiry through isa, cast, and dyn_cast:
1096 static bool classof(const Instruction *I) {
1097 return (I->getOpcode() == Instruction::GetElementPtr);
1098 }
1099 static bool classof(const Value *V) {
1100 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1101 }
1102};
1103
1104template <>
1105struct OperandTraits<GetElementPtrInst> :
1106 public VariadicOperandTraits<GetElementPtrInst, 1> {
1107};
1108
1109GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1110 ArrayRef<Value *> IdxList, unsigned Values,
1111 const Twine &NameStr,
1112 Instruction *InsertBefore)
1113 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1114 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1115 Values, InsertBefore),
1116 SourceElementType(PointeeType),
1117 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1118 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1119, __PRETTY_FUNCTION__))
1119 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1119, __PRETTY_FUNCTION__))
;
1120 init(Ptr, IdxList, NameStr);
1121}
1122
1123GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1124 ArrayRef<Value *> IdxList, unsigned Values,
1125 const Twine &NameStr,
1126 BasicBlock *InsertAtEnd)
1127 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1128 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1129 Values, InsertAtEnd),
1130 SourceElementType(PointeeType),
1131 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1132 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1133, __PRETTY_FUNCTION__))
1133 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1133, __PRETTY_FUNCTION__))
;
1134 init(Ptr, IdxList, NameStr);
1135}
1136
1137DEFINE_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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1137, __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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1137, __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); }
1138
1139//===----------------------------------------------------------------------===//
1140// ICmpInst Class
1141//===----------------------------------------------------------------------===//
1142
1143/// This instruction compares its operands according to the predicate given
1144/// to the constructor. It only operates on integers or pointers. The operands
1145/// must be identical types.
1146/// Represent an integer comparison operator.
1147class ICmpInst: public CmpInst {
1148 void AssertOK() {
1149 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
1150 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1150, __PRETTY_FUNCTION__))
;
1151 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__))
1152 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1152, __PRETTY_FUNCTION__))
;
1153 // Check that the operands are the right type
1154 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
1155 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
1156 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1156, __PRETTY_FUNCTION__))
;
1157 }
1158
1159protected:
1160 // Note: Instruction needs to be a friend here to call cloneImpl.
1161 friend class Instruction;
1162
1163 /// Clone an identical ICmpInst
1164 ICmpInst *cloneImpl() const;
1165
1166public:
1167 /// Constructor with insert-before-instruction semantics.
1168 ICmpInst(
1169 Instruction *InsertBefore, ///< Where to insert
1170 Predicate pred, ///< The predicate to use for the comparison
1171 Value *LHS, ///< The left-hand-side of the expression
1172 Value *RHS, ///< The right-hand-side of the expression
1173 const Twine &NameStr = "" ///< Name of the instruction
1174 ) : CmpInst(makeCmpResultType(LHS->getType()),
1175 Instruction::ICmp, pred, LHS, RHS, NameStr,
1176 InsertBefore) {
1177#ifndef NDEBUG
1178 AssertOK();
1179#endif
1180 }
1181
1182 /// Constructor with insert-at-end semantics.
1183 ICmpInst(
1184 BasicBlock &InsertAtEnd, ///< Block to insert into.
1185 Predicate pred, ///< The predicate to use for the comparison
1186 Value *LHS, ///< The left-hand-side of the expression
1187 Value *RHS, ///< The right-hand-side of the expression
1188 const Twine &NameStr = "" ///< Name of the instruction
1189 ) : CmpInst(makeCmpResultType(LHS->getType()),
1190 Instruction::ICmp, pred, LHS, RHS, NameStr,
1191 &InsertAtEnd) {
1192#ifndef NDEBUG
1193 AssertOK();
1194#endif
1195 }
1196
1197 /// Constructor with no-insertion semantics
1198 ICmpInst(
1199 Predicate pred, ///< The predicate to use for the comparison
1200 Value *LHS, ///< The left-hand-side of the expression
1201 Value *RHS, ///< The right-hand-side of the expression
1202 const Twine &NameStr = "" ///< Name of the instruction
1203 ) : CmpInst(makeCmpResultType(LHS->getType()),
1204 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1205#ifndef NDEBUG
1206 AssertOK();
1207#endif
1208 }
1209
1210 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1211 /// @returns the predicate that would be the result if the operand were
1212 /// regarded as signed.
1213 /// Return the signed version of the predicate
1214 Predicate getSignedPredicate() const {
1215 return getSignedPredicate(getPredicate());
1216 }
1217
1218 /// This is a static version that you can use without an instruction.
1219 /// Return the signed version of the predicate.
1220 static Predicate getSignedPredicate(Predicate pred);
1221
1222 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1223 /// @returns the predicate that would be the result if the operand were
1224 /// regarded as unsigned.
1225 /// Return the unsigned version of the predicate
1226 Predicate getUnsignedPredicate() const {
1227 return getUnsignedPredicate(getPredicate());
1228 }
1229
1230 /// This is a static version that you can use without an instruction.
1231 /// Return the unsigned version of the predicate.
1232 static Predicate getUnsignedPredicate(Predicate pred);
1233
1234 /// Return true if this predicate is either EQ or NE. This also
1235 /// tests for commutativity.
1236 static bool isEquality(Predicate P) {
1237 return P == ICMP_EQ || P == ICMP_NE;
1238 }
1239
1240 /// Return true if this predicate is either EQ or NE. This also
1241 /// tests for commutativity.
1242 bool isEquality() const {
1243 return isEquality(getPredicate());
1244 }
1245
1246 /// @returns true if the predicate of this ICmpInst is commutative
1247 /// Determine if this relation is commutative.
1248 bool isCommutative() const { return isEquality(); }
1249
1250 /// Return true if the predicate is relational (not EQ or NE).
1251 ///
1252 bool isRelational() const {
1253 return !isEquality();
1254 }
1255
1256 /// Return true if the predicate is relational (not EQ or NE).
1257 ///
1258 static bool isRelational(Predicate P) {
1259 return !isEquality(P);
1260 }
1261
1262 /// Exchange the two operands to this instruction in such a way that it does
1263 /// not modify the semantics of the instruction. The predicate value may be
1264 /// changed to retain the same result if the predicate is order dependent
1265 /// (e.g. ult).
1266 /// Swap operands and adjust predicate.
1267 void swapOperands() {
1268 setPredicate(getSwappedPredicate());
1269 Op<0>().swap(Op<1>());
1270 }
1271
1272 // Methods for support type inquiry through isa, cast, and dyn_cast:
1273 static bool classof(const Instruction *I) {
1274 return I->getOpcode() == Instruction::ICmp;
1275 }
1276 static bool classof(const Value *V) {
1277 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1278 }
1279};
1280
1281//===----------------------------------------------------------------------===//
1282// FCmpInst Class
1283//===----------------------------------------------------------------------===//
1284
1285/// This instruction compares its operands according to the predicate given
1286/// to the constructor. It only operates on floating point values or packed
1287/// vectors of floating point values. The operands must be identical types.
1288/// Represents a floating point comparison operator.
1289class FCmpInst: public CmpInst {
1290 void AssertOK() {
1291 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1291, __PRETTY_FUNCTION__))
;
1292 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1293, __PRETTY_FUNCTION__))
1293 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1293, __PRETTY_FUNCTION__))
;
1294 // Check that the operands are the right type
1295 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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1296, __PRETTY_FUNCTION__))
1296 "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-10~+201911111502510600c19528f1809/llvm/include/llvm/IR/Instructions.h"
, 1296, __PRETTY_FUNCTION__))
;
1297 }
1298
1299protected:
1300 // Note: Instruction needs to be a friend here to call cloneImpl.
1301 friend class Instruction;
1302
1303 /// Clone an identical FCmpInst
1304 FCmpInst *cloneImpl() const;
1305
1306public:
1307 /// Constructor with insert-before-instruction semantics.
1308 FCmpInst(
1309 Instruction *InsertBefore, ///< Where to insert
1310 Predicate pred, ///< The predicate to use for the comparison
1311 Value *LHS, ///< The left-hand-side of the expression
1312 Value *RHS, ///< The right-hand-side of the expression
1313 const Twine &NameStr = "" ///< Name of the instruction
1314 ) : CmpInst(makeCmpResultType(LHS->getType()),
1315 Instruction::FCmp, pred, LHS, RHS, NameStr,
1316 InsertBefore) {
1317 AssertOK();
1318 }
1319
1320 /// Constructor with insert-at-end semantics.
1321 FCmpInst(
1322 BasicBlock &InsertAtEnd, ///< Block to insert into.
1323 Predicate pred, ///< The predicate to use for the comparison
1324 Value *LHS, ///< The left-hand-side of the expression
1325 Value *RHS, ///< The right-hand-side of the expression
1326 const Twine &NameStr = "" ///< Name of the instruction
1327 ) : CmpInst(makeCmpResultType(LHS->getType()),
1328 Instruction::FCmp, pred, LHS, RHS, NameStr,
1329 &InsertAtEnd) {
1330 AssertOK();
1331 }
1332
1333 /// Constructor with no-insertion semantics
1334 FCmpInst(
1335 Predicate Pred, ///< The predicate to use for the comparison
1336 Value *LHS, ///< The left-hand-side of the expression
1337 Value *RHS, ///< The right-hand-side of the expression
1338 const Twine &NameStr = "", ///< Name of the instruction
1339 Instruction *FlagsSource = nullptr
1340 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1341 RHS, NameStr, nullptr, FlagsSource) {
1342 AssertOK();
1343 }
1344
1345 /// @returns true if the predicate of this instruction is EQ or NE.
1346 /// Determine if this is an equality predicate.
1347 static bool isEquality(Predicate Pred) {
1348 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1349 Pred == FCMP_UNE;
1350 }
1351
1352 /// @returns true if the predicate of this instruction is EQ or NE.
1353 /// Determine if this is an equality predicate.
1354 bool isEquality() const { return isEquality(getPredicate()); }
1355
1356 /// @returns true if the predicate of this instruction is commutative.
1357 /// Determine if this is a commutative predicate.
1358 bool isCommutative() const {
1359 return isEquality() ||
1360 getPredicate() == FCMP_FALSE ||
1361 getPredicate() == FCMP_TRUE ||
1362 getPredicate() == FCMP_ORD ||
1363 getPredicate() == FCMP_UNO;
1364 }
1365
1366 /// @returns true if the predicate is relational (not EQ or NE).
1367 /// Determine if this a relational predicate.
1368 bool isRelational() const { return !isEquality(); }
1369
1370 /// Exchange the two operands to this instruction in such a way that it does
1371 /// not modify the semantics of the instruction. The predicate value may be
1372 /// changed to retain the same result if the predicate is order dependent
1373 /// (e.g. ult).
1374 /// Swap operands and adjust predicate.
1375 void swapOperands() {
1376 setPredicate(getSwappedPredicate());
1377 Op<0>().swap(Op<1>());
1378 }
1379
1380 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1381 static bool classof(const Instruction *I) {
1382 return I->getOpcode() == Instruction::FCmp;
1383 }
1384 static bool classof(const Value *V) {
1385 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1386 }
1387};
1388
1389//===----------------------------------------------------------------------===//
1390/// This class represents a function call, abstracting a target
1391/// machine's calling convention. This class uses low bit of the SubClassData
1392/// field to indicate whether or not this is a tail call. The rest of the bits
1393/// hold the calling convention of the call.
1394///
1395class CallInst : public CallBase {
1396 CallInst(const CallInst &CI);
1397
1398 /// Construct a CallInst given a range of arguments.
1399 /// Construct a CallInst from a range of arguments
1400 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1401 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1402 Instruction *InsertBefore);
1403
1404 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1405 const Twine &NameStr, Instruction *InsertBefore)
1406 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1407
1408 /// Construct a CallInst given a range of arguments.
1409 /// Construct a CallInst from a range of arguments
1410 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1411 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1412 BasicBlock *InsertAtEnd);
1413
1414 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1415 Instruction *InsertBefore);
1416
1417 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1418 BasicBlock *InsertAtEnd);
1419
1420 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1421 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1422 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1423
1424 /// Compute the number of operands to allocate.
1425 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1426 // We need one operand for the called function, plus the input operand
1427 // counts provided.
1428 return 1 + NumArgs + NumBundleInputs;
1429 }
1430
1431protected:
1432 // Note: Instruction needs to be a friend here to call cloneImpl.
1433 friend class Instruction;
1434
1435 CallInst *cloneImpl() const;
1436
1437public:
1438 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1439 Instruction *InsertBefore = nullptr) {
1440 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1441 }
1442
1443 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1444 const Twine &NameStr,
1445 Instruction *InsertBefore = nullptr) {
1446 return new (ComputeNumOperands(Args.size()))
1447 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1448 }
1449
1450 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1451 ArrayRef<OperandBundleDef> Bundles = None,
1452 const Twine &NameStr = "",
1453 Instruction *InsertBefore = nullptr) {
1454 const int NumOperands =
1455 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1456 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1457
1458 return new (NumOperands, DescriptorBytes)
1459 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1460 }
1461
1462 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1463 BasicBlock *InsertAtEnd) {
1464 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1465 }
1466
1467 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1468 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1469 return new (ComputeNumOperands(Args.size()))
1470 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1471 }
1472
1473 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1474 ArrayRef<OperandBundleDef> Bundles,
1475 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1476 const int NumOperands =
1477 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1478 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1479
1480 return new (NumOperands, DescriptorBytes)
1481 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1482 }
1483
1484 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1485 Instruction *InsertBefore = nullptr) {
1486 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1487 InsertBefore);
1488 }
1489
1490 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1491 ArrayRef<OperandBundleDef> Bundles = None,
1492 const Twine &NameStr = "",
1493 Instruction *InsertBefore = nullptr) {
1494 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1495 NameStr, InsertBefore);
1496 }
1497
1498 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1499 const Twine &NameStr,
1500 Instruction *InsertBefore = nullptr) {
1501 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1502 InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1506 BasicBlock *InsertAtEnd) {
1507 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1508 InsertAtEnd);
1509 }
1510
1511 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1512 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1513 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1514 InsertAtEnd);
1515 }
1516
1517 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1518 ArrayRef<OperandBundleDef> Bundles,
1519 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1520 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1521 NameStr, InsertAtEnd);
1522 }
1523
1524 // Deprecated [opaque pointer types]
1525 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1526 Instruction *InsertBefore = nullptr) {
1527 return Create(cast<FunctionType>(
1528 cast<PointerType>(Func->getType())->getElementType()),
1529 Func, NameStr, InsertBefore);
1530 }
1531
1532 // Deprecated [opaque pointer types]
1533 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1534 const Twine &NameStr,
1535 Instruction *InsertBefore = nullptr) {
1536 return Create(cast<FunctionType>(
1537 cast<PointerType>(Func->getType())->getElementType()),
1538 Func, Args, NameStr, InsertBefore);
1539 }
1540
1541 // Deprecated [opaque pointer types]
1542 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1543 ArrayRef<OperandBundleDef> Bundles = None,
1544 const Twine &NameStr = "",
1545 Instruction *InsertBefore = nullptr) {
1546 return Create(cast<FunctionType>(
1547 cast<PointerType>(Func->getType())->getElementType()),
1548 Func, Args, Bundles, NameStr, InsertBefore);
1549 }
1550
1551 // Deprecated [opaque pointer types]
1552 static CallInst *Create(Value *Func, const Twine &NameStr,
1553 BasicBlock *InsertAtEnd) {
1554 return Create(cast<FunctionType>(
1555 cast<PointerType>(Func->getType())->getElementType()),
1556 Func, NameStr, InsertAtEnd);
1557 }
1558
1559 // Deprecated [opaque pointer types]
1560 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1561 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1562 return Create(cast<FunctionType>(
1563 cast<PointerType>(Func->getType())->getElementType()),
1564 Func, Args, NameStr, InsertAtEnd);
1565 }
1566
1567 // Deprecated [opaque pointer types]
1568 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1569 ArrayRef<OperandBundleDef> Bundles,
1570 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1571 return Create(cast<FunctionType>(
1572 cast<PointerType>(Func->getType())->getElementType()),
1573 Func, Args, Bundles, NameStr, InsertAtEnd);
1574 }
1575
1576 /// Create a clone of \p CI with a different set of operand bundles and
1577 /// insert it before \p InsertPt.
1578 ///
1579 /// The returned call instruction is identical \p CI in every way except that
1580 /// the operand bundles for the new instruction are set to the operand bundles
1581 /// in \p Bundles.
1582 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1583 Instruction *InsertPt = nullptr);
1584
1585 /// Generate the IR for a call to malloc:
1586 /// 1. Compute the malloc call's argument as the specified type's size,
1587 /// possibly multiplied by the array size if the array size is not
1588 /// constant 1.
1589 /// 2. Call malloc with that argument.
1590 /// 3. Bitcast the result of the malloc call to the specified type.
1591 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1592 Type *AllocTy, Value *AllocSize,
1593 Value *ArraySize = nullptr,
1594 Function *MallocF = nullptr,
1595 const Twine &Name = "");
1596 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1597 Type *AllocTy, Value *AllocSize,
1598 Value *ArraySize = nullptr,
1599 Function *MallocF = nullptr,
1600 const Twine &Name = "");
1601 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1602 Type *AllocTy, Value *AllocSize,
1603 Value *ArraySize = nullptr,
1604 ArrayRef<OperandBundleDef> Bundles = None,
1605 Function *MallocF = nullptr,
1606 const Twine &Name = "");
1607 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1608 Type *AllocTy, Value *AllocSize,
1609 Value *ArraySize = nullptr,
1610 ArrayRef<OperandBundleDef> Bundles = None,
1611 Function *MallocF = nullptr,
1612 const Twine &Name = "");
1613 /// Generate the IR for a call to the builtin free function.
1614 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1615 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1616 static Instruction *CreateFree(Value *Source,
1617 ArrayRef<OperandBundleDef> Bundles,
1618 Instruction *InsertBefore);
1619 static Instruction *CreateFree(Value *Source,
1620 ArrayRef<OperandBundleDef> Bundles,
1621 BasicBlock *InsertAtEnd);
1622
1623 // Note that 'musttail' implies 'tail'.
1624 enum TailCallKind {
1625 TCK_None = 0,
1626 TCK_Tail = 1,
1627 TCK_MustTail = 2,
1628 TCK_NoTail = 3
1629 };
1630 TailCallKind getTailCallKind() const {
1631 return TailCallKind(getSubclassDataFromInstruction() & 3);
1632 }
1633
1634 bool isTailCall() const {
1635 unsigned Kind = getSubclassDataFromInstruction() & 3;
1636 return Kind == TCK_Tail || Kind == TCK_MustTail;
1637 }
1638
1639 bool isMustTailCall() const {
1640 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1641 }
1642
1643 bool isNoTailCall() const {
1644 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1645 }
1646
1647 void setTailCall(bool isTC = true) {
1648 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1649 unsigned(isTC ? TCK_Tail : TCK_None));
1650 }
1651
1652 void setTailCallKind(TailCallKind TCK) {
1653 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1654 unsigned(TCK));
1655 }
1656
1657 /// Return true if the call can return twice
1658 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1659 void setCanReturnTwice() {
1660 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1661 }
1662
1663 // Methods for support type inquiry through isa, cast, and dyn_cast:
1664