Bug Summary

File:llvm/include/llvm/IR/Instructions.h
Warning:line 1728, 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 -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -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-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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 InstCombiner &IC) {
61 // The select condition must be an equality compare with a constant operand.
62 Value *X;
63 Constant *C;
64 CmpInst::Predicate Pred;
65 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
66 return nullptr;
67
68 bool IsEq;
69 if (ICmpInst::isEquality(Pred))
70 IsEq = Pred == ICmpInst::ICMP_EQ;
71 else if (Pred == FCmpInst::FCMP_OEQ)
72 IsEq = true;
73 else if (Pred == FCmpInst::FCMP_UNE)
74 IsEq = false;
75 else
76 return nullptr;
77
78 // A select operand must be a binop.
79 BinaryOperator *BO;
80 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
81 return nullptr;
82
83 // The compare constant must be the identity constant for that binop.
84 // If this a floating-point compare with 0.0, any zero constant will do.
85 Type *Ty = BO->getType();
86 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
87 if (IdC != C) {
88 if (!IdC || !CmpInst::isFPPredicate(Pred))
89 return nullptr;
90 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
91 return nullptr;
92 }
93
94 // Last, match the compare variable operand with a binop operand.
95 Value *Y;
96 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
97 return nullptr;
98 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
99 return nullptr;
100
101 // +0.0 compares equal to -0.0, and so it does not behave as required for this
102 // transform. Bail out if we can not exclude that possibility.
103 if (isa<FPMathOperator>(BO))
104 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
105 return nullptr;
106
107 // BO = binop Y, X
108 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
109 // =>
110 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
111 return IC.replaceOperand(Sel, IsEq ? 1 : 2, Y);
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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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 UnaryOperator::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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 705, __PRETTY_FUNCTION__))
;
706
707 // Ensure the sub is of the form:
708 // (a > b) ? a - b : 0 -> usub.sat(a, b)
709 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
710 // Checking for both a-b and a+(-b) as a constant.
711 bool IsNegative = false;
712 const APInt *C;
713 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))) ||
714 (match(A, m_APInt(C)) &&
715 match(TrueVal, m_Add(m_Specific(B), m_SpecificInt(-*C)))))
716 IsNegative = true;
717 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))) &&
718 !(match(B, m_APInt(C)) &&
719 match(TrueVal, m_Add(m_Specific(A), m_SpecificInt(-*C)))))
720 return nullptr;
721
722 // If we are adding a negate and the sub and icmp are used anywhere else, we
723 // would end up with more instructions.
724 if (IsNegative && !TrueVal->hasOneUse() && !ICI->hasOneUse())
725 return nullptr;
726
727 // (a > b) ? a - b : 0 -> usub.sat(a, b)
728 // (a > b) ? b - a : 0 -> -usub.sat(a, b)
729 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B);
730 if (IsNegative)
731 Result = Builder.CreateNeg(Result);
732 return Result;
733}
734
735static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
736 InstCombiner::BuilderTy &Builder) {
737 if (!Cmp->hasOneUse())
738 return nullptr;
739
740 // Match unsigned saturated add with constant.
741 Value *Cmp0 = Cmp->getOperand(0);
742 Value *Cmp1 = Cmp->getOperand(1);
743 ICmpInst::Predicate Pred = Cmp->getPredicate();
744 Value *X;
745 const APInt *C, *CmpC;
746 if (Pred == ICmpInst::ICMP_ULT &&
747 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
748 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
749 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C)
750 return Builder.CreateBinaryIntrinsic(
751 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C));
752 }
753
754 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
755 // There are 8 commuted variants.
756 // Canonicalize -1 (saturated result) to true value of the select. Just
757 // swapping the compare operands is legal, because the selected value is the
758 // same in case of equality, so we can interchange u< and u<=.
759 if (match(FVal, m_AllOnes())) {
760 std::swap(TVal, FVal);
761 std::swap(Cmp0, Cmp1);
762 }
763 if (!match(TVal, m_AllOnes()))
764 return nullptr;
765
766 // Canonicalize predicate to 'ULT'.
767 if (Pred == ICmpInst::ICMP_UGT) {
768 Pred = ICmpInst::ICMP_ULT;
769 std::swap(Cmp0, Cmp1);
770 }
771 if (Pred != ICmpInst::ICMP_ULT)
772 return nullptr;
773
774 // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
775 Value *Y;
776 if (match(Cmp0, m_Not(m_Value(X))) &&
777 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
778 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
779 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y)
780 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y);
781 }
782 // The 'not' op may be included in the sum but not the compare.
783 X = Cmp0;
784 Y = Cmp1;
785 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) {
786 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y)
787 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X)
788 BinaryOperator *BO = cast<BinaryOperator>(FVal);
789 return Builder.CreateBinaryIntrinsic(
790 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1));
791 }
792 // The overflow may be detected via the add wrapping round.
793 if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) &&
794 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) {
795 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y)
796 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y)
797 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y);
798 }
799
800 return nullptr;
801}
802
803/// Fold the following code sequence:
804/// \code
805/// int a = ctlz(x & -x);
806// x ? 31 - a : a;
807/// \code
808///
809/// into:
810/// cttz(x)
811static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal,
812 Value *FalseVal,
813 InstCombiner::BuilderTy &Builder) {
814 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
815 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero()))
816 return nullptr;
817
818 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
819 std::swap(TrueVal, FalseVal);
820
821 if (!match(FalseVal,
822 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1))))
823 return nullptr;
824
825 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>()))
826 return nullptr;
827
828 Value *X = ICI->getOperand(0);
829 auto *II = cast<IntrinsicInst>(TrueVal);
830 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X)))))
831 return nullptr;
832
833 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz,
834 II->getType());
835 return CallInst::Create(F, {X, II->getArgOperand(1)});
836}
837
838/// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
839/// call to cttz/ctlz with flag 'is_zero_undef' cleared.
840///
841/// For example, we can fold the following code sequence:
842/// \code
843/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
844/// %1 = icmp ne i32 %x, 0
845/// %2 = select i1 %1, i32 %0, i32 32
846/// \code
847///
848/// into:
849/// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
850static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
851 InstCombiner::BuilderTy &Builder) {
852 ICmpInst::Predicate Pred = ICI->getPredicate();
853 Value *CmpLHS = ICI->getOperand(0);
854 Value *CmpRHS = ICI->getOperand(1);
855
856 // Check if the condition value compares a value for equality against zero.
857 if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
858 return nullptr;
859
860 Value *SelectArg = FalseVal;
861 Value *ValueOnZero = TrueVal;
862 if (Pred == ICmpInst::ICMP_NE)
863 std::swap(SelectArg, ValueOnZero);
864
865 // Skip zero extend/truncate.
866 Value *Count = nullptr;
867 if (!match(SelectArg, m_ZExt(m_Value(Count))) &&
868 !match(SelectArg, m_Trunc(m_Value(Count))))
869 Count = SelectArg;
870
871 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
872 // input to the cttz/ctlz is used as LHS for the compare instruction.
873 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
874 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
875 return nullptr;
876
877 IntrinsicInst *II = cast<IntrinsicInst>(Count);
878
879 // Check if the value propagated on zero is a constant number equal to the
880 // sizeof in bits of 'Count'.
881 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
882 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
883 // Explicitly clear the 'undef_on_zero' flag. It's always valid to go from
884 // true to false on this flag, so we can replace it for all users.
885 II->setArgOperand(1, ConstantInt::getFalse(II->getContext()));
886 return SelectArg;
887 }
888
889 // If the ValueOnZero is not the bitwidth, we can at least make use of the
890 // fact that the cttz/ctlz result will not be used if the input is zero, so
891 // it's okay to relax it to undef for that case.
892 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
893 II->setArgOperand(1, ConstantInt::getTrue(II->getContext()));
894
895 return nullptr;
896}
897
898/// Return true if we find and adjust an icmp+select pattern where the compare
899/// is with a constant that can be incremented or decremented to match the
900/// minimum or maximum idiom.
901static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
902 ICmpInst::Predicate Pred = Cmp.getPredicate();
903 Value *CmpLHS = Cmp.getOperand(0);
904 Value *CmpRHS = Cmp.getOperand(1);
905 Value *TrueVal = Sel.getTrueValue();
906 Value *FalseVal = Sel.getFalseValue();
907
908 // We may move or edit the compare, so make sure the select is the only user.
909 const APInt *CmpC;
910 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
911 return false;
912
913 // These transforms only work for selects of integers or vector selects of
914 // integer vectors.
915 Type *SelTy = Sel.getType();
916 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
917 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
918 return false;
919
920 Constant *AdjustedRHS;
921 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
922 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
923 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
924 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
925 else
926 return false;
927
928 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
929 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
930 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
931 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
932 ; // Nothing to do here. Values match without any sign/zero extension.
933 }
934 // Types do not match. Instead of calculating this with mixed types, promote
935 // all to the larger type. This enables scalar evolution to analyze this
936 // expression.
937 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
938 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
939
940 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
941 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
942 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
943 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
944 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
945 CmpLHS = TrueVal;
946 AdjustedRHS = SextRHS;
947 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
948 SextRHS == TrueVal) {
949 CmpLHS = FalseVal;
950 AdjustedRHS = SextRHS;
951 } else if (Cmp.isUnsigned()) {
952 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
953 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
954 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
955 // zext + signed compare cannot be changed:
956 // 0xff <s 0x00, but 0x00ff >s 0x0000
957 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
958 CmpLHS = TrueVal;
959 AdjustedRHS = ZextRHS;
960 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
961 ZextRHS == TrueVal) {
962 CmpLHS = FalseVal;
963 AdjustedRHS = ZextRHS;
964 } else {
965 return false;
966 }
967 } else {
968 return false;
969 }
970 } else {
971 return false;
972 }
973
974 Pred = ICmpInst::getSwappedPredicate(Pred);
975 CmpRHS = AdjustedRHS;
976 std::swap(FalseVal, TrueVal);
977 Cmp.setPredicate(Pred);
978 Cmp.setOperand(0, CmpLHS);
979 Cmp.setOperand(1, CmpRHS);
980 Sel.setOperand(1, TrueVal);
981 Sel.setOperand(2, FalseVal);
982 Sel.swapProfMetadata();
983
984 // Move the compare instruction right before the select instruction. Otherwise
985 // the sext/zext value may be defined after the compare instruction uses it.
986 Cmp.moveBefore(&Sel);
987
988 return true;
989}
990
991/// If this is an integer min/max (icmp + select) with a constant operand,
992/// create the canonical icmp for the min/max operation and canonicalize the
993/// constant to the 'false' operand of the select:
994/// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
995/// Note: if C1 != C2, this will change the icmp constant to the existing
996/// constant operand of the select.
997static Instruction *
998canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
999 InstCombiner &IC) {
1000 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1001 return nullptr;
1002
1003 // Canonicalize the compare predicate based on whether we have min or max.
1004 Value *LHS, *RHS;
1005 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
1006 if (!SelectPatternResult::isMinOrMax(SPR.Flavor))
1007 return nullptr;
1008
1009 // Is this already canonical?
1010 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
1011 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
1012 Cmp.getPredicate() == CanonicalPred)
1013 return nullptr;
1014
1015 // Bail out on unsimplified X-0 operand (due to some worklist management bug),
1016 // as this may cause an infinite combine loop. Let the sub be folded first.
1017 if (match(LHS, m_Sub(m_Value(), m_Zero())) ||
1018 match(RHS, m_Sub(m_Value(), m_Zero())))
1019 return nullptr;
1020
1021 // Create the canonical compare and plug it into the select.
1022 IC.replaceOperand(Sel, 0, IC.Builder.CreateICmp(CanonicalPred, LHS, RHS));
1023
1024 // If the select operands did not change, we're done.
1025 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
1026 return &Sel;
1027
1028 // If we are swapping the select operands, swap the metadata too.
1029 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1030, __PRETTY_FUNCTION__))
1030 "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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1030, __PRETTY_FUNCTION__))
;
1031 Sel.swapValues();
1032 Sel.swapProfMetadata();
1033 return &Sel;
1034}
1035
1036/// There are many select variants for each of ABS/NABS.
1037/// In matchSelectPattern(), there are different compare constants, compare
1038/// predicates/operands and select operands.
1039/// In isKnownNegation(), there are different formats of negated operands.
1040/// Canonicalize all these variants to 1 pattern.
1041/// This makes CSE more likely.
1042static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
1043 InstCombiner::BuilderTy &Builder) {
1044 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
1045 return nullptr;
1046
1047 // Choose a sign-bit check for the compare (likely simpler for codegen).
1048 // ABS: (X <s 0) ? -X : X
1049 // NABS: (X <s 0) ? X : -X
1050 Value *LHS, *RHS;
1051 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
1052 if (SPF != SelectPatternFlavor::SPF_ABS &&
1053 SPF != SelectPatternFlavor::SPF_NABS)
1054 return nullptr;
1055
1056 Value *TVal = Sel.getTrueValue();
1057 Value *FVal = Sel.getFalseValue();
1058 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1059, __PRETTY_FUNCTION__))
1059 "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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1059, __PRETTY_FUNCTION__))
;
1060
1061 // The compare may use the negated abs()/nabs() operand, or it may use
1062 // negation in non-canonical form such as: sub A, B.
1063 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
1064 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
1065
1066 bool CmpCanonicalized = !CmpUsesNegatedOp &&
1067 match(Cmp.getOperand(1), m_ZeroInt()) &&
1068 Cmp.getPredicate() == ICmpInst::ICMP_SLT;
1069 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
1070
1071 // Is this already canonical?
1072 if (CmpCanonicalized && RHSCanonicalized)
1073 return nullptr;
1074
1075 // If RHS is not canonical but is used by other instructions, don't
1076 // canonicalize it and potentially increase the instruction count.
1077 if (!RHSCanonicalized)
1078 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
1079 return nullptr;
1080
1081 // Create the canonical compare: icmp slt LHS 0.
1082 if (!CmpCanonicalized) {
1083 Cmp.setPredicate(ICmpInst::ICMP_SLT);
1084 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType()));
1085 if (CmpUsesNegatedOp)
1086 Cmp.setOperand(0, LHS);
1087 }
1088
1089 // Create the canonical RHS: RHS = sub (0, LHS).
1090 if (!RHSCanonicalized) {
1091 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1091, __PRETTY_FUNCTION__))
;
1092 RHS = Builder.CreateNeg(LHS);
1093 if (TVal == LHS) {
1094 Sel.setFalseValue(RHS);
1095 FVal = RHS;
1096 } else {
1097 Sel.setTrueValue(RHS);
1098 TVal = RHS;
1099 }
1100 }
1101
1102 // If the select operands do not change, we're done.
1103 if (SPF == SelectPatternFlavor::SPF_NABS) {
1104 if (TVal == LHS)
1105 return &Sel;
1106 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1106, __PRETTY_FUNCTION__))
;
1107 } else {
1108 if (FVal == LHS)
1109 return &Sel;
1110 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 1110, __PRETTY_FUNCTION__))
;
1111 }
1112
1113 // We are swapping the select operands, so swap the metadata too.
1114 Sel.swapValues();
1115 Sel.swapProfMetadata();
1116 return &Sel;
1117}
1118
1119static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp,
1120 const SimplifyQuery &Q) {
1121 // If this is a binary operator, try to simplify it with the replaced op
1122 // because we know Op and ReplaceOp are equivalant.
1123 // For example: V = X + 1, Op = X, ReplaceOp = 42
1124 // Simplifies as: add(42, 1) --> 43
1125 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1126 if (BO->getOperand(0) == Op)
1127 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q);
1128 if (BO->getOperand(1) == Op)
1129 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q);
1130 }
1131
1132 return nullptr;
1133}
1134
1135/// If we have a select with an equality comparison, then we know the value in
1136/// one of the arms of the select. See if substituting this value into an arm
1137/// and simplifying the result yields the same value as the other arm.
1138///
1139/// To make this transform safe, we must drop poison-generating flags
1140/// (nsw, etc) if we simplified to a binop because the select may be guarding
1141/// that poison from propagating. If the existing binop already had no
1142/// poison-generating flags, then this transform can be done by instsimplify.
1143///
1144/// Consider:
1145/// %cmp = icmp eq i32 %x, 2147483647
1146/// %add = add nsw i32 %x, 1
1147/// %sel = select i1 %cmp, i32 -2147483648, i32 %add
1148///
1149/// We can't replace %sel with %add unless we strip away the flags.
1150/// TODO: Wrapping flags could be preserved in some cases with better analysis.
1151static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp,
1152 const SimplifyQuery &Q) {
1153 if (!Cmp.isEquality())
1154 return nullptr;
1155
1156 // Canonicalize the pattern to ICMP_EQ by swapping the select operands.
1157 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue();
1158 if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
1159 std::swap(TrueVal, FalseVal);
1160
1161 // Try each equivalence substitution possibility.
1162 // We have an 'EQ' comparison, so the select's false value will propagate.
1163 // Example:
1164 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1
1165 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43
1166 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1);
1167 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal ||
1168 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal ||
1169 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal ||
1170 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) {
1171 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal))
1172 FalseInst->dropPoisonGeneratingFlags();
1173 return FalseVal;
1174 }
1175 return nullptr;
1176}
1177
1178// See if this is a pattern like:
1179// %old_cmp1 = icmp slt i32 %x, C2
1180// %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high
1181// %old_x_offseted = add i32 %x, C1
1182// %old_cmp0 = icmp ult i32 %old_x_offseted, C0
1183// %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement
1184// This can be rewritten as more canonical pattern:
1185// %new_cmp1 = icmp slt i32 %x, -C1
1186// %new_cmp2 = icmp sge i32 %x, C0-C1
1187// %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x
1188// %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low
1189// Iff -C1 s<= C2 s<= C0-C1
1190// Also ULT predicate can also be UGT iff C0 != -1 (+invert result)
1191// SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.)
1192static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0,
1193 InstCombiner::BuilderTy &Builder) {
1194 Value *X = Sel0.getTrueValue();
1195 Value *Sel1 = Sel0.getFalseValue();
1196
1197 // First match the condition of the outermost select.
1198 // Said condition must be one-use.
1199 if (!Cmp0.hasOneUse())
1200 return nullptr;
1201 Value *Cmp00 = Cmp0.getOperand(0);
1202 Constant *C0;
1203 if (!match(Cmp0.getOperand(1),
1204 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))
1205 return nullptr;
1206 // Canonicalize Cmp0 into the form we expect.
1207 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1208 switch (Cmp0.getPredicate()) {
1209 case ICmpInst::Predicate::ICMP_ULT:
1210 break; // Great!
1211 case ICmpInst::Predicate::ICMP_ULE:
1212 // We'd have to increment C0 by one, and for that it must not have all-ones
1213 // element, but then it would have been canonicalized to 'ult' before
1214 // we get here. So we can't do anything useful with 'ule'.
1215 return nullptr;
1216 case ICmpInst::Predicate::ICMP_UGT:
1217 // We want to canonicalize it to 'ult', so we'll need to increment C0,
1218 // which again means it must not have any all-ones elements.
1219 if (!match(C0,
1220 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1221 APInt::getAllOnesValue(
1222 C0->getType()->getScalarSizeInBits()))))
1223 return nullptr; // Can't do, have all-ones element[s].
1224 C0 = AddOne(C0);
1225 std::swap(X, Sel1);
1226 break;
1227 case ICmpInst::Predicate::ICMP_UGE:
1228 // The only way we'd get this predicate if this `icmp` has extra uses,
1229 // but then we won't be able to do this fold.
1230 return nullptr;
1231 default:
1232 return nullptr; // Unknown predicate.
1233 }
1234
1235 // Now that we've canonicalized the ICmp, we know the X we expect;
1236 // the select in other hand should be one-use.
1237 if (!Sel1->hasOneUse())
1238 return nullptr;
1239
1240 // We now can finish matching the condition of the outermost select:
1241 // it should either be the X itself, or an addition of some constant to X.
1242 Constant *C1;
1243 if (Cmp00 == X)
1244 C1 = ConstantInt::getNullValue(Sel0.getType());
1245 else if (!match(Cmp00,
1246 m_Add(m_Specific(X),
1247 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1)))))
1248 return nullptr;
1249
1250 Value *Cmp1;
1251 ICmpInst::Predicate Pred1;
1252 Constant *C2;
1253 Value *ReplacementLow, *ReplacementHigh;
1254 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow),
1255 m_Value(ReplacementHigh))) ||
1256 !match(Cmp1,
1257 m_ICmp(Pred1, m_Specific(X),
1258 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2)))))
1259 return nullptr;
1260
1261 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse()))
1262 return nullptr; // Not enough one-use instructions for the fold.
1263 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of
1264 // two comparisons we'll need to build.
1265
1266 // Canonicalize Cmp1 into the form we expect.
1267 // FIXME: we shouldn't care about lanes that are 'undef' in the end?
1268 switch (Pred1) {
1269 case ICmpInst::Predicate::ICMP_SLT:
1270 break;
1271 case ICmpInst::Predicate::ICMP_SLE:
1272 // We'd have to increment C2 by one, and for that it must not have signed
1273 // max element, but then it would have been canonicalized to 'slt' before
1274 // we get here. So we can't do anything useful with 'sle'.
1275 return nullptr;
1276 case ICmpInst::Predicate::ICMP_SGT:
1277 // We want to canonicalize it to 'slt', so we'll need to increment C2,
1278 // which again means it must not have any signed max elements.
1279 if (!match(C2,
1280 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE,
1281 APInt::getSignedMaxValue(
1282 C2->getType()->getScalarSizeInBits()))))
1283 return nullptr; // Can't do, have signed max element[s].
1284 C2 = AddOne(C2);
1285 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1286 case ICmpInst::Predicate::ICMP_SGE:
1287 // Also non-canonical, but here we don't need to change C2,
1288 // so we don't have any restrictions on C2, so we can just handle it.
1289 std::swap(ReplacementLow, ReplacementHigh);
1290 break;
1291 default:
1292 return nullptr; // Unknown predicate.
1293 }
1294
1295 // The thresholds of this clamp-like pattern.
1296 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1);
1297 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1);
1298
1299 // The fold has a precondition 1: C2 s>= ThresholdLow
1300 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2,
1301 ThresholdLowIncl);
1302 if (!match(Precond1, m_One()))
1303 return nullptr;
1304 // The fold has a precondition 2: C2 s<= ThresholdHigh
1305 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2,
1306 ThresholdHighExcl);
1307 if (!match(Precond2, m_One()))
1308 return nullptr;
1309
1310 // All good, finally emit the new pattern.
1311 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl);
1312 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl);
1313 Value *MaybeReplacedLow =
1314 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X);
1315 Instruction *MaybeReplacedHigh =
1316 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow);
1317
1318 return MaybeReplacedHigh;
1319}
1320
1321// If we have
1322// %cmp = icmp [canonical predicate] i32 %x, C0
1323// %r = select i1 %cmp, i32 %y, i32 C1
1324// Where C0 != C1 and %x may be different from %y, see if the constant that we
1325// will have if we flip the strictness of the predicate (i.e. without changing
1326// the result) is identical to the C1 in select. If it matches we can change
1327// original comparison to one with swapped predicate, reuse the constant,
1328// and swap the hands of select.
1329static Instruction *
1330tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp,
1331 InstCombiner &IC) {
1332 ICmpInst::Predicate Pred;
1333 Value *X;
1334 Constant *C0;
1335 if (!match(&Cmp, m_OneUse(m_ICmp(
1336 Pred, m_Value(X),
1337 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0))))))
1338 return nullptr;
1339
1340 // If comparison predicate is non-relational, we won't be able to do anything.
1341 if (ICmpInst::isEquality(Pred))
1342 return nullptr;
1343
1344 // If comparison predicate is non-canonical, then we certainly won't be able
1345 // to make it canonical; canonicalizeCmpWithConstant() already tried.
1346 if (!isCanonicalPredicate(Pred))
1347 return nullptr;
1348
1349 // If the [input] type of comparison and select type are different, lets abort
1350 // for now. We could try to compare constants with trunc/[zs]ext though.
1351 if (C0->getType() != Sel.getType())
1352 return nullptr;
1353
1354 // FIXME: are there any magic icmp predicate+constant pairs we must not touch?
1355
1356 Value *SelVal0, *SelVal1; // We do not care which one is from where.
1357 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1)));
1358 // At least one of these values we are selecting between must be a constant
1359 // else we'll never succeed.
1360 if (!match(SelVal0, m_AnyIntegralConstant()) &&
1361 !match(SelVal1, m_AnyIntegralConstant()))
1362 return nullptr;
1363
1364 // Does this constant C match any of the `select` values?
1365 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) {
1366 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1);
1367 };
1368
1369 // If C0 *already* matches true/false value of select, we are done.
1370 if (MatchesSelectValue(C0))
1371 return nullptr;
1372
1373 // Check the constant we'd have with flipped-strictness predicate.
1374 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0);
1375 if (!FlippedStrictness)
1376 return nullptr;
1377
1378 // If said constant doesn't match either, then there is no hope,
1379 if (!MatchesSelectValue(FlippedStrictness->second))
1380 return nullptr;
1381
1382 // It matched! Lets insert the new comparison just before select.
1383 InstCombiner::BuilderTy::InsertPointGuard Guard(IC.Builder);
1384 IC.Builder.SetInsertPoint(&Sel);
1385
1386 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped.
1387 Value *NewCmp = IC.Builder.CreateICmp(Pred, X, FlippedStrictness->second,
1388 Cmp.getName() + ".inv");
1389 IC.replaceOperand(Sel, 0, NewCmp);
1390 Sel.swapValues();
1391 Sel.swapProfMetadata();
1392
1393 return &Sel;
1394}
1395
1396/// Visit a SelectInst that has an ICmpInst as its first operand.
1397Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1398 ICmpInst *ICI) {
1399 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ))
1400 return replaceInstUsesWith(SI, V);
1401
1402 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, *this))
1403 return NewSel;
1404
1405 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
1406 return NewAbs;
1407
1408 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder))
1409 return NewAbs;
1410
1411 if (Instruction *NewSel =
1412 tryToReuseConstantFromSelectInComparison(SI, *ICI, *this))
1413 return NewSel;
1414
1415 bool Changed = adjustMinMax(SI, *ICI);
1416
1417 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1418 return replaceInstUsesWith(SI, V);
1419
1420 // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1421 Value *TrueVal = SI.getTrueValue();
1422 Value *FalseVal = SI.getFalseValue();
1423 ICmpInst::Predicate Pred = ICI->getPredicate();
1424 Value *CmpLHS = ICI->getOperand(0);
1425 Value *CmpRHS = ICI->getOperand(1);
1426 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1427 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1428 // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1429 SI.setOperand(1, CmpRHS);
1430 Changed = true;
1431 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1432 // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1433 SI.setOperand(2, CmpRHS);
1434 Changed = true;
1435 }
1436 }
1437
1438 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1439 // decomposeBitTestICmp() might help.
1440 {
1441 unsigned BitWidth =
1442 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1443 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1444 Value *X;
1445 const APInt *Y, *C;
1446 bool TrueWhenUnset;
1447 bool IsBitTest = false;
1448 if (ICmpInst::isEquality(Pred) &&
1449 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1450 match(CmpRHS, m_Zero())) {
1451 IsBitTest = true;
1452 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1453 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1454 X = CmpLHS;
1455 Y = &MinSignedValue;
1456 IsBitTest = true;
1457 TrueWhenUnset = false;
1458 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1459 X = CmpLHS;
1460 Y = &MinSignedValue;
1461 IsBitTest = true;
1462 TrueWhenUnset = true;
1463 }
1464 if (IsBitTest) {
1465 Value *V = nullptr;
1466 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1467 if (TrueWhenUnset && TrueVal == X &&
1468 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1469 V = Builder.CreateAnd(X, ~(*Y));
1470 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1471 else if (!TrueWhenUnset && FalseVal == X &&
1472 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1473 V = Builder.CreateAnd(X, ~(*Y));
1474 // (X & Y) == 0 ? X ^ Y : X --> X | Y
1475 else if (TrueWhenUnset && FalseVal == X &&
1476 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1477 V = Builder.CreateOr(X, *Y);
1478 // (X & Y) != 0 ? X : X ^ Y --> X | Y
1479 else if (!TrueWhenUnset && TrueVal == X &&
1480 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1481 V = Builder.CreateOr(X, *Y);
1482
1483 if (V)
1484 return replaceInstUsesWith(SI, V);
1485 }
1486 }
1487
1488 if (Instruction *V =
1489 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1490 return V;
1491
1492 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder))
1493 return V;
1494
1495 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1496 return replaceInstUsesWith(SI, V);
1497
1498 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder))
1499 return replaceInstUsesWith(SI, V);
1500
1501 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1502 return replaceInstUsesWith(SI, V);
1503
1504 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1505 return replaceInstUsesWith(SI, V);
1506
1507 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1508 return replaceInstUsesWith(SI, V);
1509
1510 return Changed ? &SI : nullptr;
1511}
1512
1513/// SI is a select whose condition is a PHI node (but the two may be in
1514/// different blocks). See if the true/false values (V) are live in all of the
1515/// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1516///
1517/// X = phi [ C1, BB1], [C2, BB2]
1518/// Y = add
1519/// Z = select X, Y, 0
1520///
1521/// because Y is not live in BB1/BB2.
1522static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1523 const SelectInst &SI) {
1524 // If the value is a non-instruction value like a constant or argument, it
1525 // can always be mapped.
1526 const Instruction *I = dyn_cast<Instruction>(V);
1527 if (!I) return true;
1528
1529 // If V is a PHI node defined in the same block as the condition PHI, we can
1530 // map the arguments.
1531 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1532
1533 if (const PHINode *VP = dyn_cast<PHINode>(I))
1534 if (VP->getParent() == CondPHI->getParent())
1535 return true;
1536
1537 // Otherwise, if the PHI and select are defined in the same block and if V is
1538 // defined in a different block, then we can transform it.
1539 if (SI.getParent() == CondPHI->getParent() &&
1540 I->getParent() != CondPHI->getParent())
1541 return true;
1542
1543 // Otherwise we have a 'hard' case and we can't tell without doing more
1544 // detailed dominator based analysis, punt.
1545 return false;
1546}
1547
1548/// We have an SPF (e.g. a min or max) of an SPF of the form:
1549/// SPF2(SPF1(A, B), C)
1550Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1551 SelectPatternFlavor SPF1,
1552 Value *A, Value *B,
1553 Instruction &Outer,
1554 SelectPatternFlavor SPF2, Value *C) {
1555 if (Outer.getType() != Inner->getType())
1556 return nullptr;
1557
1558 if (C == A || C == B) {
1559 // MAX(MAX(A, B), B) -> MAX(A, B)
1560 // MIN(MIN(a, b), a) -> MIN(a, b)
1561 // TODO: This could be done in instsimplify.
1562 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1563 return replaceInstUsesWith(Outer, Inner);
1564
1565 // MAX(MIN(a, b), a) -> a
1566 // MIN(MAX(a, b), a) -> a
1567 // TODO: This could be done in instsimplify.
1568 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1569 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1570 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1571 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1572 return replaceInstUsesWith(Outer, C);
1573 }
1574
1575 if (SPF1 == SPF2) {
1576 const APInt *CB, *CC;
1577 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1578 // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1579 // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1580 // TODO: This could be done in instsimplify.
1581 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1582 (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1583 (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1584 (SPF1 == SPF_SMAX && CB->sge(*CC)))
1585 return replaceInstUsesWith(Outer, Inner);
1586
1587 // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1588 // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1589 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1590 (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1591 (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1592 (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1593 Outer.replaceUsesOfWith(Inner, A);
1594 return &Outer;
1595 }
1596 }
1597 }
1598
1599 // max(max(A, B), min(A, B)) --> max(A, B)
1600 // min(min(A, B), max(A, B)) --> min(A, B)
1601 // TODO: This could be done in instsimplify.
1602 if (SPF1 == SPF2 &&
1603 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) ||
1604 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) ||
1605 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) ||
1606 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B))))))
1607 return replaceInstUsesWith(Outer, Inner);
1608
1609 // ABS(ABS(X)) -> ABS(X)
1610 // NABS(NABS(X)) -> NABS(X)
1611 // TODO: This could be done in instsimplify.
1612 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1613 return replaceInstUsesWith(Outer, Inner);
1614 }
1615
1616 // ABS(NABS(X)) -> ABS(X)
1617 // NABS(ABS(X)) -> NABS(X)
1618 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1619 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1620 SelectInst *SI = cast<SelectInst>(Inner);
1621 Value *NewSI =
1622 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1623 SI->getTrueValue(), SI->getName(), SI);
1624 return replaceInstUsesWith(Outer, NewSI);
1625 }
1626
1627 auto IsFreeOrProfitableToInvert =
1628 [&](Value *V, Value *&NotV, bool &ElidesXor) {
1629 if (match(V, m_Not(m_Value(NotV)))) {
1630 // If V has at most 2 uses then we can get rid of the xor operation
1631 // entirely.
1632 ElidesXor |= !V->hasNUsesOrMore(3);
1633 return true;
1634 }
1635
1636 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1637 NotV = nullptr;
1638 return true;
1639 }
1640
1641 return false;
1642 };
1643
1644 Value *NotA, *NotB, *NotC;
1645 bool ElidesXor = false;
1646
1647 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1648 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1649 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1650 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1651 //
1652 // This transform is performance neutral if we can elide at least one xor from
1653 // the set of three operands, since we'll be tacking on an xor at the very
1654 // end.
1655 if (SelectPatternResult::isMinOrMax(SPF1) &&
1656 SelectPatternResult::isMinOrMax(SPF2) &&
1657 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1658 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1659 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1660 if (!NotA)
1661 NotA = Builder.CreateNot(A);
1662 if (!NotB)
1663 NotB = Builder.CreateNot(B);
1664 if (!NotC)
1665 NotC = Builder.CreateNot(C);
1666
1667 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1668 NotB);
1669 Value *NewOuter = Builder.CreateNot(
1670 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1671 return replaceInstUsesWith(Outer, NewOuter);
1672 }
1673
1674 return nullptr;
1675}
1676
1677/// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1678/// This is even legal for FP.
1679static Instruction *foldAddSubSelect(SelectInst &SI,
1680 InstCombiner::BuilderTy &Builder) {
1681 Value *CondVal = SI.getCondition();
1682 Value *TrueVal = SI.getTrueValue();
1683 Value *FalseVal = SI.getFalseValue();
1684 auto *TI = dyn_cast<Instruction>(TrueVal);
1685 auto *FI = dyn_cast<Instruction>(FalseVal);
1686 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1687 return nullptr;
1688
1689 Instruction *AddOp = nullptr, *SubOp = nullptr;
1690 if ((TI->getOpcode() == Instruction::Sub &&
1691 FI->getOpcode() == Instruction::Add) ||
1692 (TI->getOpcode() == Instruction::FSub &&
1693 FI->getOpcode() == Instruction::FAdd)) {
1694 AddOp = FI;
1695 SubOp = TI;
1696 } else if ((FI->getOpcode() == Instruction::Sub &&
1697 TI->getOpcode() == Instruction::Add) ||
1698 (FI->getOpcode() == Instruction::FSub &&
1699 TI->getOpcode() == Instruction::FAdd)) {
1700 AddOp = TI;
1701 SubOp = FI;
1702 }
1703
1704 if (AddOp) {
1705 Value *OtherAddOp = nullptr;
1706 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1707 OtherAddOp = AddOp->getOperand(1);
1708 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1709 OtherAddOp = AddOp->getOperand(0);
1710 }
1711
1712 if (OtherAddOp) {
1713 // So at this point we know we have (Y -> OtherAddOp):
1714 // select C, (add X, Y), (sub X, Z)
1715 Value *NegVal; // Compute -Z
1716 if (SI.getType()->isFPOrFPVectorTy()) {
1717 NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1718 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1719 FastMathFlags Flags = AddOp->getFastMathFlags();
1720 Flags &= SubOp->getFastMathFlags();
1721 NegInst->setFastMathFlags(Flags);
1722 }
1723 } else {
1724 NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1725 }
1726
1727 Value *NewTrueOp = OtherAddOp;
1728 Value *NewFalseOp = NegVal;
1729 if (AddOp != TI)
1730 std::swap(NewTrueOp, NewFalseOp);
1731 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1732 SI.getName() + ".p", &SI);
1733
1734 if (SI.getType()->isFPOrFPVectorTy()) {
1735 Instruction *RI =
1736 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1737
1738 FastMathFlags Flags = AddOp->getFastMathFlags();
1739 Flags &= SubOp->getFastMathFlags();
1740 RI->setFastMathFlags(Flags);
1741 return RI;
1742 } else
1743 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1744 }
1745 }
1746 return nullptr;
1747}
1748
1749/// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1750/// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1751/// Along with a number of patterns similar to:
1752/// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1753/// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1754static Instruction *
1755foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) {
1756 Value *CondVal = SI.getCondition();
1757 Value *TrueVal = SI.getTrueValue();
1758 Value *FalseVal = SI.getFalseValue();
1759
1760 WithOverflowInst *II;
1761 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) ||
1762 !match(FalseVal, m_ExtractValue<0>(m_Specific(II))))
1763 return nullptr;
1764
1765 Value *X = II->getLHS();
1766 Value *Y = II->getRHS();
1767
1768 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) {
1769 Type *Ty = Limit->getType();
1770
1771 ICmpInst::Predicate Pred;
1772 Value *TrueVal, *FalseVal, *Op;
1773 const APInt *C;
1774 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)),
1775 m_Value(TrueVal), m_Value(FalseVal))))
1776 return false;
1777
1778 auto IsZeroOrOne = [](const APInt &C) {
1779 return C.isNullValue() || C.isOneValue();
1780 };
1781 auto IsMinMax = [&](Value *Min, Value *Max) {
1782 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
1783 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
1784 return match(Min, m_SpecificInt(MinVal)) &&
1785 match(Max, m_SpecificInt(MaxVal));
1786 };
1787
1788 if (Op != X && Op != Y)
1789 return false;
1790
1791 if (IsAdd) {
1792 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1793 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1794 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1795 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1796 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1797 IsMinMax(TrueVal, FalseVal))
1798 return true;
1799 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1800 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1801 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1802 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1803 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1804 IsMinMax(FalseVal, TrueVal))
1805 return true;
1806 } else {
1807 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1808 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1809 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) &&
1810 IsMinMax(TrueVal, FalseVal))
1811 return true;
1812 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1813 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1814 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) &&
1815 IsMinMax(FalseVal, TrueVal))
1816 return true;
1817 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1818 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1819 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) &&
1820 IsMinMax(FalseVal, TrueVal))
1821 return true;
1822 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1823 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1824 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) &&
1825 IsMinMax(TrueVal, FalseVal))
1826 return true;
1827 }
1828
1829 return false;
1830 };
1831
1832 Intrinsic::ID NewIntrinsicID;
1833 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow &&
1834 match(TrueVal, m_AllOnes()))
1835 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y
1836 NewIntrinsicID = Intrinsic::uadd_sat;
1837 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow &&
1838 match(TrueVal, m_Zero()))
1839 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y
1840 NewIntrinsicID = Intrinsic::usub_sat;
1841 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow &&
1842 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true))
1843 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1844 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1845 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1846 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1847 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1848 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y
1849 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1850 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y
1851 NewIntrinsicID = Intrinsic::sadd_sat;
1852 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow &&
1853 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false))
1854 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1855 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1856 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1857 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1858 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1859 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y
1860 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1861 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y
1862 NewIntrinsicID = Intrinsic::ssub_sat;
1863 else
1864 return nullptr;
1865
1866 Function *F =
1867 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType());
1868 return CallInst::Create(F, {X, Y});
1869}
1870
1871Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1872 Constant *C;
1873 if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1874 !match(Sel.getFalseValue(), m_Constant(C)))
1875 return nullptr;
1876
1877 Instruction *ExtInst;
1878 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1879 !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1880 return nullptr;
1881
1882 auto ExtOpcode = ExtInst->getOpcode();
1883 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1884 return nullptr;
1885
1886 // If we are extending from a boolean type or if we can create a select that
1887 // has the same size operands as its condition, try to narrow the select.
1888 Value *X = ExtInst->getOperand(0);
1889 Type *SmallType = X->getType();
1890 Value *Cond = Sel.getCondition();
1891 auto *Cmp = dyn_cast<CmpInst>(Cond);
1892 if (!SmallType->isIntOrIntVectorTy(1) &&
1893 (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1894 return nullptr;
1895
1896 // If the constant is the same after truncation to the smaller type and
1897 // extension to the original type, we can narrow the select.
1898 Type *SelType = Sel.getType();
1899 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1900 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1901 if (ExtC == C) {
1902 Value *TruncCVal = cast<Value>(TruncC);
1903 if (ExtInst == Sel.getFalseValue())
1904 std::swap(X, TruncCVal);
1905
1906 // select Cond, (ext X), C --> ext(select Cond, X, C')
1907 // select Cond, C, (ext X) --> ext(select Cond, C', X)
1908 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1909 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1910 }
1911
1912 // If one arm of the select is the extend of the condition, replace that arm
1913 // with the extension of the appropriate known bool value.
1914 if (Cond == X) {
1915 if (ExtInst == Sel.getTrueValue()) {
1916 // select X, (sext X), C --> select X, -1, C
1917 // select X, (zext X), C --> select X, 1, C
1918 Constant *One = ConstantInt::getTrue(SmallType);
1919 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1920 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1921 } else {
1922 // select X, C, (sext X) --> select X, C, 0
1923 // select X, C, (zext X) --> select X, C, 0
1924 Constant *Zero = ConstantInt::getNullValue(SelType);
1925 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1926 }
1927 }
1928
1929 return nullptr;
1930}
1931
1932/// Try to transform a vector select with a constant condition vector into a
1933/// shuffle for easier combining with other shuffles and insert/extract.
1934static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1935 Value *CondVal = SI.getCondition();
1936 Constant *CondC;
1937 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
8
Taking true branch
1938 return nullptr;
9
Returning null pointer, which participates in a condition later
1939
1940 unsigned NumElts = CondVal->getType()->getVectorNumElements();
1941 SmallVector<Constant *, 16> Mask;
1942 Mask.reserve(NumElts);
1943 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1944 for (unsigned i = 0; i != NumElts; ++i) {
1945 Constant *Elt = CondC->getAggregateElement(i);
1946 if (!Elt)
1947 return nullptr;
1948
1949 if (Elt->isOneValue()) {
1950 // If the select condition element is true, choose from the 1st vector.
1951 Mask.push_back(ConstantInt::get(Int32Ty, i));
1952 } else if (Elt->isNullValue()) {
1953 // If the select condition element is false, choose from the 2nd vector.
1954 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1955 } else if (isa<UndefValue>(Elt)) {
1956 // Undef in a select condition (choose one of the operands) does not mean
1957 // the same thing as undef in a shuffle mask (any value is acceptable), so
1958 // give up.
1959 return nullptr;
1960 } else {
1961 // Bail out on a constant expression.
1962 return nullptr;
1963 }
1964 }
1965
1966 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1967 ConstantVector::get(Mask));
1968}
1969
1970/// If we have a select of vectors with a scalar condition, try to convert that
1971/// to a vector select by splatting the condition. A splat may get folded with
1972/// other operations in IR and having all operands of a select be vector types
1973/// is likely better for vector codegen.
1974static Instruction *canonicalizeScalarSelectOfVecs(
1975 SelectInst &Sel, InstCombiner &IC) {
1976 Type *Ty = Sel.getType();
1977 if (!Ty->isVectorTy())
13
Calling 'Type::isVectorTy'
16
Returning from 'Type::isVectorTy'
17
Taking true branch
1978 return nullptr;
18
Returning null pointer, which participates in a condition later
1979
1980 // We can replace a single-use extract with constant index.
1981 Value *Cond = Sel.getCondition();
1982 if (!match(Cond, m_OneUse(m_ExtractElement(m_Value(), m_ConstantInt()))))
1983 return nullptr;
1984
1985 // select (extelt V, Index), T, F --> select (splat V, Index), T, F
1986 // Splatting the extracted condition reduces code (we could directly create a
1987 // splat shuffle of the source vector to eliminate the intermediate step).
1988 unsigned NumElts = Ty->getVectorNumElements();
1989 return IC.replaceOperand(Sel, 0, IC.Builder.CreateVectorSplat(NumElts, Cond));
1990}
1991
1992/// Reuse bitcasted operands between a compare and select:
1993/// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1994/// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1995static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1996 InstCombiner::BuilderTy &Builder) {
1997 Value *Cond = Sel.getCondition();
1998 Value *TVal = Sel.getTrueValue();
1999 Value *FVal = Sel.getFalseValue();
2000
2001 CmpInst::Predicate Pred;
2002 Value *A, *B;
2003 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
2004 return nullptr;
2005
2006 // The select condition is a compare instruction. If the select's true/false
2007 // values are already the same as the compare operands, there's nothing to do.
2008 if (TVal == A || TVal == B || FVal == A || FVal == B)
2009 return nullptr;
2010
2011 Value *C, *D;
2012 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
2013 return nullptr;
2014
2015 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
2016 Value *TSrc, *FSrc;
2017 if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
2018 !match(FVal, m_BitCast(m_Value(FSrc))))
2019 return nullptr;
2020
2021 // If the select true/false values are *different bitcasts* of the same source
2022 // operands, make the select operands the same as the compare operands and
2023 // cast the result. This is the canonical select form for min/max.
2024 Value *NewSel;
2025 if (TSrc == C && FSrc == D) {
2026 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
2027 // bitcast (select (cmp A, B), A, B)
2028 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
2029 } else if (TSrc == D && FSrc == C) {
2030 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
2031 // bitcast (select (cmp A, B), B, A)
2032 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
2033 } else {
2034 return nullptr;
2035 }
2036 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
2037}
2038
2039/// Try to eliminate select instructions that test the returned flag of cmpxchg
2040/// instructions.
2041///
2042/// If a select instruction tests the returned flag of a cmpxchg instruction and
2043/// selects between the returned value of the cmpxchg instruction its compare
2044/// operand, the result of the select will always be equal to its false value.
2045/// For example:
2046///
2047/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2048/// %1 = extractvalue { i64, i1 } %0, 1
2049/// %2 = extractvalue { i64, i1 } %0, 0
2050/// %3 = select i1 %1, i64 %compare, i64 %2
2051/// ret i64 %3
2052///
2053/// The returned value of the cmpxchg instruction (%2) is the original value
2054/// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
2055/// must have been equal to %compare. Thus, the result of the select is always
2056/// equal to %2, and the code can be simplified to:
2057///
2058/// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
2059/// %1 = extractvalue { i64, i1 } %0, 0
2060/// ret i64 %1
2061///
2062static Instruction *foldSelectCmpXchg(SelectInst &SI) {
2063 // A helper that determines if V is an extractvalue instruction whose
2064 // aggregate operand is a cmpxchg instruction and whose single index is equal
2065 // to I. If such conditions are true, the helper returns the cmpxchg
2066 // instruction; otherwise, a nullptr is returned.
2067 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
2068 auto *Extract = dyn_cast<ExtractValueInst>(V);
2069 if (!Extract)
2070 return nullptr;
2071 if (Extract->getIndices()[0] != I)
2072 return nullptr;
2073 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
2074 };
2075
2076 // If the select has a single user, and this user is a select instruction that
2077 // we can simplify, skip the cmpxchg simplification for now.
2078 if (SI.hasOneUse())
2079 if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
2080 if (Select->getCondition() == SI.getCondition())
2081 if (Select->getFalseValue() == SI.getTrueValue() ||
2082 Select->getTrueValue() == SI.getFalseValue())
2083 return nullptr;
2084
2085 // Ensure the select condition is the returned flag of a cmpxchg instruction.
2086 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
2087 if (!CmpXchg)
2088 return nullptr;
2089
2090 // Check the true value case: The true value of the select is the returned
2091 // value of the same cmpxchg used by the condition, and the false value is the
2092 // cmpxchg instruction's compare operand.
2093 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
2094 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
2095 SI.setTrueValue(SI.getFalseValue());
2096 return &SI;
2097 }
2098
2099 // Check the false value case: The false value of the select is the returned
2100 // value of the same cmpxchg used by the condition, and the true value is the
2101 // cmpxchg instruction's compare operand.
2102 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
2103 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
2104 SI.setTrueValue(SI.getFalseValue());
2105 return &SI;
2106 }
2107
2108 return nullptr;
2109}
2110
2111static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X,
2112 Value *Y,
2113 InstCombiner::BuilderTy &Builder) {
2114 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 2114, __PRETTY_FUNCTION__))
;
2115 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN ||
2116 SPF == SelectPatternFlavor::SPF_UMAX;
2117 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change
2118 // the constant value check to an assert.
2119 Value *A;
2120 const APInt *C1, *C2;
2121 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) &&
2122 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) {
2123 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1
2124 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1
2125 Value *NewMinMax = createMinMax(Builder, SPF, A,
2126 ConstantInt::get(X->getType(), *C2 - *C1));
2127 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax,
2128 ConstantInt::get(X->getType(), *C1));
2129 }
2130
2131 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) &&
2132 match(Y, m_APInt(C2)) && X->hasNUses(2)) {
2133 bool Overflow;
2134 APInt Diff = C2->ssub_ov(*C1, Overflow);
2135 if (!Overflow) {
2136 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1
2137 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1
2138 Value *NewMinMax = createMinMax(Builder, SPF, A,
2139 ConstantInt::get(X->getType(), Diff));
2140 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax,
2141 ConstantInt::get(X->getType(), *C1));
2142 }
2143 }
2144
2145 return nullptr;
2146}
2147
2148/// Match a sadd_sat or ssub_sat which is using min/max to clamp the value.
2149Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) {
2150 Type *Ty = MinMax1.getType();
2151
2152 // We are looking for a tree of:
2153 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B))))
2154 // Where the min and max could be reversed
2155 Instruction *MinMax2;
2156 BinaryOperator *AddSub;
2157 const APInt *MinValue, *MaxValue;
2158 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) {
2159 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue))))
2160 return nullptr;
2161 } else if (match(&MinMax1,
2162 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) {
2163 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue))))
2164 return nullptr;
2165 } else
2166 return nullptr;
2167
2168 // Check that the constants clamp a saturate, and that the new type would be
2169 // sensible to convert to.
2170 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1)
2171 return nullptr;
2172 // In what bitwidth can this be treated as saturating arithmetics?
2173 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1;
2174 // FIXME: This isn't quite right for vectors, but using the scalar type is a
2175 // good first approximation for what should be done there.
2176 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth))
2177 return nullptr;
2178
2179 // Also make sure that the number of uses is as expected. The "3"s are for the
2180 // the two items of min/max (the compare and the select).
2181 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3))
2182 return nullptr;
2183
2184 // Create the new type (which can be a vector type)
2185 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth);
2186 // Match the two extends from the add/sub
2187 Value *A, *B;
2188 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B)))))
2189 return nullptr;
2190 // And check the incoming values are of a type smaller than or equal to the
2191 // size of the saturation. Otherwise the higher bits can cause different
2192 // results.
2193 if (A->getType()->getScalarSizeInBits() > NewBitWidth ||
2194 B->getType()->getScalarSizeInBits() > NewBitWidth)
2195 return nullptr;
2196
2197 Intrinsic::ID IntrinsicID;
2198 if (AddSub->getOpcode() == Instruction::Add)
2199 IntrinsicID = Intrinsic::sadd_sat;
2200 else if (AddSub->getOpcode() == Instruction::Sub)
2201 IntrinsicID = Intrinsic::ssub_sat;
2202 else
2203 return nullptr;
2204
2205 // Finally create and return the sat intrinsic, truncated to the new type
2206 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy);
2207 Value *AT = Builder.CreateSExt(A, NewTy);
2208 Value *BT = Builder.CreateSExt(B, NewTy);
2209 Value *Sat = Builder.CreateCall(F, {AT, BT});
2210 return CastInst::Create(Instruction::SExt, Sat, Ty);
2211}
2212
2213/// Reduce a sequence of min/max with a common operand.
2214static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
2215 Value *RHS,
2216 InstCombiner::BuilderTy &Builder) {
2217 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-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 2217, __PRETTY_FUNCTION__))
;
2218 // TODO: Allow FP min/max with nnan/nsz.
2219 if (!LHS->getType()->isIntOrIntVectorTy())
2220 return nullptr;
2221
2222 // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
2223 Value *A, *B, *C, *D;
2224 SelectPatternResult L = matchSelectPattern(LHS, A, B);
2225 SelectPatternResult R = matchSelectPattern(RHS, C, D);
2226 if (SPF != L.Flavor || L.Flavor != R.Flavor)
2227 return nullptr;
2228
2229 // Look for a common operand. The use checks are different than usual because
2230 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
2231 // the select.
2232 Value *MinMaxOp = nullptr;
2233 Value *ThirdOp = nullptr;
2234 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
2235 // If the LHS is only used in this chain and the RHS is used outside of it,
2236 // reuse the RHS min/max because that will eliminate the LHS.
2237 if (D == A || C == A) {
2238 // min(min(a, b), min(c, a)) --> min(min(c, a), b)
2239 // min(min(a, b), min(a, d)) --> min(min(a, d), b)
2240 MinMaxOp = RHS;
2241 ThirdOp = B;
2242 } else if (D == B || C == B) {
2243 // min(min(a, b), min(c, b)) --> min(min(c, b), a)
2244 // min(min(a, b), min(b, d)) --> min(min(b, d), a)
2245 MinMaxOp = RHS;
2246 ThirdOp = A;
2247 }
2248 } else if (!RHS->hasNUsesOrMore(3)) {
2249 // Reuse the LHS. This will eliminate the RHS.
2250 if (D == A || D == B) {
2251 // min(min(a, b), min(c, a)) --> min(min(a, b), c)
2252 // min(min(a, b), min(c, b)) --> min(min(a, b), c)
2253 MinMaxOp = LHS;
2254 ThirdOp = C;
2255 } else if (C == A || C == B) {
2256 // min(min(a, b), min(b, d)) --> min(min(a, b), d)
2257 // min(min(a, b), min(c, b)) --> min(min(a, b), d)
2258 MinMaxOp = LHS;
2259 ThirdOp = D;
2260 }
2261 }
2262 if (!MinMaxOp || !ThirdOp)
2263 return nullptr;
2264
2265 CmpInst::Predicate P = getMinMaxPred(SPF);
2266 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
2267 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
2268}
2269
2270/// Try to reduce a rotate pattern that includes a compare and select into a
2271/// funnel shift intrinsic. Example:
2272/// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
2273/// --> call llvm.fshl.i32(a, a, b)
2274static Instruction *foldSelectRotate(SelectInst &Sel) {
2275 // The false value of the select must be a rotate of the true value.
2276 Value *Or0, *Or1;
2277 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
2278 return nullptr;
2279
2280 Value *TVal = Sel.getTrueValue();
2281 Value *SA0, *SA1;
2282 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
2283 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
2284 return nullptr;
2285
2286 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
2287 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
2288 if (ShiftOpcode0 == ShiftOpcode1)
2289 return nullptr;
2290
2291 // We have one of these patterns so far:
2292 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
2293 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
2294 // This must be a power-of-2 rotate for a bitmasking transform to be valid.
2295 unsigned Width = Sel.getType()->getScalarSizeInBits();
2296 if (!isPowerOf2_32(Width))
2297 return nullptr;
2298
2299 // Check the shift amounts to see if they are an opposite pair.
2300 Value *ShAmt;
2301 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
2302 ShAmt = SA0;
2303 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
2304 ShAmt = SA1;
2305 else
2306 return nullptr;
2307
2308 // Finally, see if the select is filtering out a shift-by-zero.
2309 Value *Cond = Sel.getCondition();
2310 ICmpInst::Predicate Pred;
2311 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
2312 Pred != ICmpInst::ICMP_EQ)
2313 return nullptr;
2314
2315 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
2316 // Convert to funnel shift intrinsic.
2317 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
2318 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
2319 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
2320 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
2321 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
2322}
2323
2324static Instruction *foldSelectToCopysign(SelectInst &Sel,
2325 InstCombiner::BuilderTy &Builder) {
2326 Value *Cond = Sel.getCondition();
2327 Value *TVal = Sel.getTrueValue();
2328 Value *FVal = Sel.getFalseValue();
2329 Type *SelType = Sel.getType();
2330
2331 // Match select ?, TC, FC where the constants are equal but negated.
2332 // TODO: Generalize to handle a negated variable operand?
2333 const APFloat *TC, *FC;
2334 if (!match(TVal, m_APFloat(TC)) || !match(FVal, m_APFloat(FC)) ||
2335 !abs(*TC).bitwiseIsEqual(abs(*FC)))
2336 return nullptr;
2337
2338 assert(TC != FC && "Expected equal select arms to simplify")((TC != FC && "Expected equal select arms to simplify"
) ? static_cast<void> (0) : __assert_fail ("TC != FC && \"Expected equal select arms to simplify\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp"
, 2338, __PRETTY_FUNCTION__))
;
2339
2340 Value *X;
2341 const APInt *C;
2342 bool IsTrueIfSignSet;
2343 ICmpInst::Predicate Pred;
2344 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_BitCast(m_Value(X)), m_APInt(C)))) ||
2345 !isSignBitCheck(Pred, *C, IsTrueIfSignSet) || X->getType() != SelType)
2346 return nullptr;
2347
2348 // If needed, negate the value that will be the sign argument of the copysign:
2349 // (bitcast X) < 0 ? -TC : TC --> copysign(TC, X)
2350 // (bitcast X) < 0 ? TC : -TC --> copysign(TC, -X)
2351 // (bitcast X) >= 0 ? -TC : TC --> copysign(TC, -X)
2352 // (bitcast X) >= 0 ? TC : -TC --> copysign(TC, X)
2353 if (IsTrueIfSignSet ^ TC->isNegative())
2354 X = Builder.CreateFNegFMF(X, &Sel);
2355
2356 // Canonicalize the magnitude argument as the positive constant since we do
2357 // not care about its sign.
2358 Value *MagArg = TC->isNegative() ? FVal : TVal;
2359 Function *F = Intrinsic::getDeclaration(Sel.getModule(), Intrinsic::copysign,
2360 Sel.getType());
2361 Instruction *CopySign = IntrinsicInst::Create(F, { MagArg, X });
2362 CopySign->setFastMathFlags(Sel.getFastMathFlags());
2363 return CopySign;
2364}
2365
2366Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2367 Value *CondVal = SI.getCondition();
2368 Value *TrueVal = SI.getTrueValue();
2369 Value *FalseVal = SI.getFalseValue();
1
'FalseVal' initialized here
2370 Type *SelType = SI.getType();
2371
2372 // FIXME: Remove this workaround when freeze related patches are done.
2373 // For select with undef operand which feeds into an equality comparison,
2374 // don't simplify it so loop unswitch can know the equality comparison
2375 // may have an undef operand. This is a workaround for PR31652 caused by
2376 // descrepancy about branch on undef between LoopUnswitch and GVN.
2377 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
2378 if (llvm::any_of(SI.users(), [&](User *U) {
2379 ICmpInst *CI = dyn_cast<ICmpInst>(U);
2380 if (CI && CI->isEquality())
2381 return true;
2382 return false;
2383 })) {
2384 return nullptr;
2385 }
2386 }
2387
2388 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
5
Assuming 'V' is null
6
Taking false branch
2389 SQ.getWithInstruction(&SI)))
2390 return replaceInstUsesWith(SI, V);
2391
2392 if (Instruction *I
10.1
'I' is null
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
2393 return I;
2394
2395 if (Instruction *I
19.1
'I' is null
19.1
'I' is null
19.1
'I' is null
19.1
'I' is null
19.1
'I' is null
= canonicalizeScalarSelectOfVecs(SI, *this))
12
Calling 'canonicalizeScalarSelectOfVecs'
19
Returning from 'canonicalizeScalarSelectOfVecs'
20
Taking false branch
2396 return I;
2397
2398 // Canonicalize a one-use integer compare with a non-canonical predicate by
2399 // inverting the predicate and swapping the select operands. This matches a
2400 // compare canonicalization for conditional branches.
2401 // TODO: Should we do the same for FP compares?
2402 CmpInst::Predicate Pred;
2403 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
21
Taking false branch
2404 !isCanonicalPredicate(Pred)) {
2405 // Swap true/false values and condition.
2406 CmpInst *Cond = cast<CmpInst>(CondVal);
2407 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2408 SI.swapValues();
2409 SI.swapProfMetadata();
2410 Worklist.push(Cond);
2411 return &SI;
2412 }
2413
2414 if (SelType->isIntOrIntVectorTy(1) &&
22
Assuming the condition is false
2415 TrueVal->getType() == CondVal->getType()) {
2416 if (match(TrueVal, m_One())) {
2417 // Change: A = select B, true, C --> A = or B, C
2418 return BinaryOperator::CreateOr(CondVal, FalseVal);
2419 }
2420 if (match(TrueVal, m_Zero())) {
2421 // Change: A = select B, false, C --> A = and !B, C
2422 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2423 return BinaryOperator::CreateAnd(NotCond, FalseVal);
2424 }
2425 if (match(FalseVal, m_Zero())) {
2426 // Change: A = select B, C, false --> A = and B, C
2427 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2428 }
2429 if (match(FalseVal, m_One())) {
2430 // Change: A = select B, C, true --> A = or !B, C
2431 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2432 return BinaryOperator::CreateOr(NotCond, TrueVal);
2433 }
2434
2435 // select a, a, b -> a | b
2436 // select a, b, a -> a & b
2437 if (CondVal == TrueVal)
2438 return BinaryOperator::CreateOr(CondVal, FalseVal);
2439 if (CondVal == FalseVal)
2440 return BinaryOperator::CreateAnd(CondVal, TrueVal);
2441
2442 // select a, ~a, b -> (~a) & b
2443 // select a, b, ~a -> (~a) | b
2444 if (match(TrueVal, m_Not(m_Specific(CondVal))))
2445 return BinaryOperator::CreateAnd(TrueVal, FalseVal);
2446 if (match(FalseVal, m_Not(m_Specific(CondVal))))
2447 return BinaryOperator::CreateOr(TrueVal, FalseVal);
2448 }
2449
2450 // Selecting between two integer or vector splat integer constants?
2451 //
2452 // Note that we don't handle a scalar select of vectors:
2453 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
2454 // because that may need 3 instructions to splat the condition value:
2455 // extend, insertelement, shufflevector.
2456 if (SelType->isIntOrIntVectorTy() &&
23
Calling 'Type::isIntOrIntVectorTy'
29
Returning from 'Type::isIntOrIntVectorTy'
2457 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
2458 // select C, 1, 0 -> zext C to int
2459 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
2460 return new ZExtInst(CondVal, SelType);
2461
2462 // select C, -1, 0 -> sext C to int
2463 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
2464 return new SExtInst(CondVal, SelType);
2465
2466 // select C, 0, 1 -> zext !C to int
2467 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
2468 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2469 return new ZExtInst(NotCond, SelType);
2470 }
2471
2472 // select C, 0, -1 -> sext !C to int
2473 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
2474 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
2475 return new SExtInst(NotCond, SelType);
2476 }
2477 }
2478
2479 // See if we are selecting two values based on a comparison of the two values.
2480 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
30.1
'FCI' is non-null
= dyn_cast<FCmpInst>(CondVal)) {
30
Assuming 'CondVal' is a 'FCmpInst'
31
Taking true branch
2481 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1);
2482 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) ||
32
Assuming 'Cmp0' is equal to 'TrueVal'
33
Assuming 'Cmp1' is equal to 'FalseVal'
2483 (Cmp0 == FalseVal && Cmp1 == TrueVal)) {
2484 // Canonicalize to use ordered comparisons by swapping the select
2485 // operands.
2486 //
2487 // e.g.
2488 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
2489 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
2490 FCmpInst::Predicate InvPred = FCI->getInversePredicate();
2491 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2492 // FIXME: The FMF should propagate from the select, not the fcmp.
2493 Builder.setFastMathFlags(FCI->getFastMathFlags());
2494 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1,
2495 FCI->getName() + ".inv");
2496 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal);
42
Passing null pointer value via 2nd parameter 'True'
43
Calling 'IRBuilderBase::CreateSelect'
2497 return replaceInstUsesWith(SI, NewSel);
2498 }
2499
2500 // NOTE: if we wanted to, this is where to detect MIN/MAX
2501 }
2502 }
2503
2504 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
2505 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
2506 // also require nnan because we do not want to unintentionally change the
2507 // sign of a NaN value.
2508 // FIXME: These folds should test/propagate FMF from the select, not the
2509 // fsub or fneg.
2510 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
2511 Instruction *FSub;
2512 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2513 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) &&
2514 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2515 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) {
2516 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub);
2517 return replaceInstUsesWith(SI, Fabs);
2518 }
2519 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
2520 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2521 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) &&
2522 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() &&
2523 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) {
2524 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub);
2525 return replaceInstUsesWith(SI, Fabs);
2526 }
2527 // With nnan and nsz:
2528 // (X < +/-0.0) ? -X : X --> fabs(X)
2529 // (X <= +/-0.0) ? -X : X --> fabs(X)
2530 Instruction *FNeg;
2531 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) &&
2532 match(TrueVal, m_FNeg(m_Specific(FalseVal))) &&
2533 match(TrueVal, m_Instruction(FNeg)) &&
2534 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2535 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
2536 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) {
2537 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg);
2538 return replaceInstUsesWith(SI, Fabs);
2539 }
2540 // With nnan and nsz:
2541 // (X > +/-0.0) ? X : -X --> fabs(X)
2542 // (X >= +/-0.0) ? X : -X --> fabs(X)
2543 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) &&
2544 match(FalseVal, m_FNeg(m_Specific(TrueVal))) &&
2545 match(FalseVal, m_Instruction(FNeg)) &&
2546 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() &&
2547 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE ||
2548 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) {
2549 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg);
2550 return replaceInstUsesWith(SI, Fabs);
2551 }
2552
2553 // See if we are selecting two values based on a comparison of the two values.
2554 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
2555 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
2556 return Result;
2557
2558 if (Instruction *Add = foldAddSubSelect(SI, Builder))
2559 return Add;
2560 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder))
2561 return Add;
2562
2563 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
2564 auto *TI = dyn_cast<Instruction>(TrueVal);
2565 auto *FI = dyn_cast<Instruction>(FalseVal);
2566 if (TI && FI && TI->getOpcode() == FI->getOpcode())
2567 if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
2568 return IV;
2569
2570 if (Instruction *I = foldSelectExtConst(SI))
2571 return I;
2572
2573 // See if we can fold the select into one of our operands.
2574 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
2575 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
2576 return FoldI;
2577
2578 Value *LHS, *RHS;
2579 Instruction::CastOps CastOp;
2580 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
2581 auto SPF = SPR.Flavor;
2582 if (SPF) {
2583 Value *LHS2, *RHS2;
2584 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
2585 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
2586 RHS2, SI, SPF, RHS))
2587 return R;
2588 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
2589 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
2590 RHS2, SI, SPF, LHS))
2591 return R;
2592 // TODO.
2593 // ABS(-X) -> ABS(X)
2594 }
2595
2596 if (SelectPatternResult::isMinOrMax(SPF)) {
2597 // Canonicalize so that
2598 // - type casts are outside select patterns.
2599 // - float clamp is transformed to min/max pattern
2600
2601 bool IsCastNeeded = LHS->getType() != SelType;
2602 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
2603 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
2604 if (IsCastNeeded ||
2605 (LHS->getType()->isFPOrFPVectorTy() &&
2606 ((CmpLHS != LHS && CmpLHS != RHS) ||
2607 (CmpRHS != LHS && CmpRHS != RHS)))) {
2608 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered);
2609
2610 Value *Cmp;
2611 if (CmpInst::isIntPredicate(MinMaxPred)) {
2612 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS);
2613 } else {
2614 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2615 auto FMF =
2616 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
2617 Builder.setFastMathFlags(FMF);
2618 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS);
2619 }
2620
2621 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
2622 if (!IsCastNeeded)
2623 return replaceInstUsesWith(SI, NewSI);
2624
2625 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
2626 return replaceInstUsesWith(SI, NewCast);
2627 }
2628
2629 // MAX(~a, ~b) -> ~MIN(a, b)
2630 // MAX(~a, C) -> ~MIN(a, ~C)
2631 // MIN(~a, ~b) -> ~MAX(a, b)
2632 // MIN(~a, C) -> ~MAX(a, ~C)
2633 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
2634 Value *A;
2635 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
2636 !isFreeToInvert(A, A->hasOneUse()) &&
2637 // Passing false to only consider m_Not and constants.
2638 isFreeToInvert(Y, false)) {
2639 Value *B = Builder.CreateNot(Y);
2640 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
2641 A, B);
2642 // Copy the profile metadata.
2643 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
2644 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
2645 // Swap the metadata if the operands are swapped.
2646 if (X == SI.getFalseValue() && Y == SI.getTrueValue())
2647 cast<SelectInst>(NewMinMax)->swapProfMetadata();
2648 }
2649
2650 return BinaryOperator::CreateNot(NewMinMax);
2651 }
2652
2653 return nullptr;
2654 };
2655
2656 if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
2657 return I;
2658 if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
2659 return I;
2660
2661 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder))
2662 return I;
2663
2664 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
2665 return I;
2666 if (Instruction *I = matchSAddSubSat(SI))
2667 return I;
2668 }
2669 }
2670
2671 // Canonicalize select of FP values where NaN and -0.0 are not valid as
2672 // minnum/maxnum intrinsics.
2673 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) {
2674 Value *X, *Y;
2675 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y))))
2676 return replaceInstUsesWith(
2677 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI));
2678
2679 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y))))
2680 return replaceInstUsesWith(
2681 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI));
2682 }
2683
2684 // See if we can fold the select into a phi node if the condition is a select.
2685 if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
2686 // The true/false values have to be live in the PHI predecessor's blocks.
2687 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
2688 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
2689 if (Instruction *NV = foldOpIntoPhi(SI, PN))
2690 return NV;
2691
2692 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
2693 if (TrueSI->getCondition()->getType() == CondVal->getType()) {
2694 // select(C, select(C, a, b), c) -> select(C, a, c)
2695 if (TrueSI->getCondition() == CondVal) {
2696 if (SI.getTrueValue() == TrueSI->getTrueValue())
2697 return nullptr;
2698 return replaceOperand(SI, 1, TrueSI->getTrueValue());
2699 }
2700 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
2701 // We choose this as normal form to enable folding on the And and shortening
2702 // paths for the values (this helps GetUnderlyingObjects() for example).
2703 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
2704 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
2705 SI.setOperand(0, And);
2706 SI.setOperand(1, TrueSI->getTrueValue());
2707 return &SI;
2708 }
2709 }
2710 }
2711 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
2712 if (FalseSI->getCondition()->getType() == CondVal->getType()) {
2713 // select(C, a, select(C, b, c)) -> select(C, a, c)
2714 if (FalseSI->getCondition() == CondVal) {
2715 if (SI.getFalseValue() == FalseSI->getFalseValue())
2716 return nullptr;
2717 return replaceOperand(SI, 2, FalseSI->getFalseValue());
2718 }
2719 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
2720 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
2721 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
2722 SI.setOperand(0, Or);
2723 SI.setOperand(2, FalseSI->getFalseValue());
2724 return &SI;
2725 }
2726 }
2727 }
2728
2729 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2730 // The select might be preventing a division by 0.
2731 switch (BO->getOpcode()) {
2732 default:
2733 return true;
2734 case Instruction::SRem:
2735 case Instruction::URem:
2736 case Instruction::SDiv:
2737 case Instruction::UDiv:
2738 return false;
2739 }
2740 };
2741
2742 // Try to simplify a binop sandwiched between 2 selects with the same
2743 // condition.
2744 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2745 BinaryOperator *TrueBO;
2746 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2747 canMergeSelectThroughBinop(TrueBO)) {
2748 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2749 if (TrueBOSI->getCondition() == CondVal) {
2750 TrueBO->setOperand(0, TrueBOSI->getTrueValue());
2751 Worklist.push(TrueBO);
2752 return &SI;
2753 }
2754 }
2755 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2756 if (TrueBOSI->getCondition() == CondVal) {
2757 TrueBO->setOperand(1, TrueBOSI->getTrueValue());
2758 Worklist.push(TrueBO);
2759 return &SI;
2760 }
2761 }
2762 }
2763
2764 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2765 BinaryOperator *FalseBO;
2766 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2767 canMergeSelectThroughBinop(FalseBO)) {
2768 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2769 if (FalseBOSI->getCondition() == CondVal) {
2770 FalseBO->setOperand(0, FalseBOSI->getFalseValue());
2771 Worklist.push(FalseBO);
2772 return &SI;
2773 }
2774 }
2775 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2776 if (FalseBOSI->getCondition() == CondVal) {
2777 FalseBO->setOperand(1, FalseBOSI->getFalseValue());
2778 Worklist.push(FalseBO);
2779 return &SI;
2780 }
2781 }
2782 }
2783
2784 Value *NotCond;
2785 if (match(CondVal, m_Not(m_Value(NotCond)))) {
2786 replaceOperand(SI, 0, NotCond);
2787 SI.swapValues();
2788 SI.swapProfMetadata();
2789 return &SI;
2790 }
2791
2792 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2793 unsigned VWidth = VecTy->getNumElements();
2794 APInt UndefElts(VWidth, 0);
2795 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2796 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2797 if (V != &SI)
2798 return replaceInstUsesWith(SI, V);
2799 return &SI;
2800 }
2801 }
2802
2803 // If we can compute the condition, there's no need for a select.
2804 // Like the above fold, we are attempting to reduce compile-time cost by
2805 // putting this fold here with limitations rather than in InstSimplify.
2806 // The motivation for this call into value tracking is to take advantage of
2807 // the assumption cache, so make sure that is populated.
2808 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2809 KnownBits Known(1);
2810 computeKnownBits(CondVal, Known, 0, &SI);
2811 if (Known.One.isOneValue())
2812 return replaceInstUsesWith(SI, TrueVal);
2813 if (Known.Zero.isOneValue())
2814 return replaceInstUsesWith(SI, FalseVal);
2815 }
2816
2817 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2818 return BitCastSel;
2819
2820 // Simplify selects that test the returned flag of cmpxchg instructions.
2821 if (Instruction *Select = foldSelectCmpXchg(SI))
2822 return Select;
2823
2824 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI, *this))
2825 return Select;
2826
2827 if (Instruction *Rot = foldSelectRotate(SI))
2828 return Rot;
2829
2830 if (Instruction *Copysign = foldSelectToCopysign(SI, Builder))
2831 return Copysign;
2832
2833 return nullptr;
2834}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/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-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h

1//===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- 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 defines the IRBuilder class, which is used as a convenient way
10// to create LLVM instructions with a consistent and simplified interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_IR_IRBUILDER_H
15#define LLVM_IR_IRBUILDER_H
16
17#include "llvm-c/Types.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/Constant.h"
24#include "llvm/IR/ConstantFolder.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DebugLoc.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/Module.h"
37#include "llvm/IR/Operator.h"
38#include "llvm/IR/Type.h"
39#include "llvm/IR/Value.h"
40#include "llvm/IR/ValueHandle.h"
41#include "llvm/Support/AtomicOrdering.h"
42#include "llvm/Support/CBindingWrapping.h"
43#include "llvm/Support/Casting.h"
44#include <cassert>
45#include <cstddef>
46#include <cstdint>
47#include <functional>
48#include <utility>
49
50namespace llvm {
51
52class APInt;
53class MDNode;
54class Use;
55
56/// This provides the default implementation of the IRBuilder
57/// 'InsertHelper' method that is called whenever an instruction is created by
58/// IRBuilder and needs to be inserted.
59///
60/// By default, this inserts the instruction at the insertion point.
61class IRBuilderDefaultInserter {
62public:
63 virtual ~IRBuilderDefaultInserter();
64
65 virtual void InsertHelper(Instruction *I, const Twine &Name,
66 BasicBlock *BB,
67 BasicBlock::iterator InsertPt) const {
68 if (BB) BB->getInstList().insert(InsertPt, I);
69 I->setName(Name);
70 }
71};
72
73/// Provides an 'InsertHelper' that calls a user-provided callback after
74/// performing the default insertion.
75class IRBuilderCallbackInserter : public IRBuilderDefaultInserter {
76 std::function<void(Instruction *)> Callback;
77
78public:
79 virtual ~IRBuilderCallbackInserter();
80
81 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
82 : Callback(std::move(Callback)) {}
83
84 void InsertHelper(Instruction *I, const Twine &Name,
85 BasicBlock *BB,
86 BasicBlock::iterator InsertPt) const override {
87 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
88 Callback(I);
89 }
90};
91
92/// Common base class shared among various IRBuilders.
93class IRBuilderBase {
94 DebugLoc CurDbgLocation;
95
96protected:
97 BasicBlock *BB;
98 BasicBlock::iterator InsertPt;
99 LLVMContext &Context;
100 const IRBuilderFolder &Folder;
101 const IRBuilderDefaultInserter &Inserter;
102
103 MDNode *DefaultFPMathTag;
104 FastMathFlags FMF;
105
106 bool IsFPConstrained;
107 fp::ExceptionBehavior DefaultConstrainedExcept;
108 fp::RoundingMode DefaultConstrainedRounding;
109
110 ArrayRef<OperandBundleDef> DefaultOperandBundles;
111
112public:
113 IRBuilderBase(LLVMContext &context, const IRBuilderFolder &Folder,
114 const IRBuilderDefaultInserter &Inserter,
115 MDNode *FPMathTag, ArrayRef<OperandBundleDef> OpBundles)
116 : Context(context), Folder(Folder), Inserter(Inserter),
117 DefaultFPMathTag(FPMathTag), IsFPConstrained(false),
118 DefaultConstrainedExcept(fp::ebStrict),
119 DefaultConstrainedRounding(fp::rmDynamic),
120 DefaultOperandBundles(OpBundles) {
121 ClearInsertionPoint();
122 }
123
124 /// Insert and return the specified instruction.
125 template<typename InstTy>
126 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
127 Inserter.InsertHelper(I, Name, BB, InsertPt);
128 SetInstDebugLocation(I);
129 return I;
130 }
131
132 /// No-op overload to handle constants.
133 Constant *Insert(Constant *C, const Twine& = "") const {
134 return C;
135 }
136
137 Value *Insert(Value *V, const Twine &Name = "") const {
138 if (Instruction *I = dyn_cast<Instruction>(V))
139 return Insert(I, Name);
140 assert(isa<Constant>(V))((isa<Constant>(V)) ? static_cast<void> (0) : __assert_fail
("isa<Constant>(V)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 140, __PRETTY_FUNCTION__))
;
141 return V;
142 }
143
144 //===--------------------------------------------------------------------===//
145 // Builder configuration methods
146 //===--------------------------------------------------------------------===//
147
148 /// Clear the insertion point: created instructions will not be
149 /// inserted into a block.
150 void ClearInsertionPoint() {
151 BB = nullptr;
152 InsertPt = BasicBlock::iterator();
153 }
154
155 BasicBlock *GetInsertBlock() const { return BB; }
156 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
157 LLVMContext &getContext() const { return Context; }
158
159 /// This specifies that created instructions should be appended to the
160 /// end of the specified block.
161 void SetInsertPoint(BasicBlock *TheBB) {
162 BB = TheBB;
163 InsertPt = BB->end();
164 }
165
166 /// This specifies that created instructions should be inserted before
167 /// the specified instruction.
168 void SetInsertPoint(Instruction *I) {
169 BB = I->getParent();
170 InsertPt = I->getIterator();
171 assert(InsertPt != BB->end() && "Can't read debug loc from end()")((InsertPt != BB->end() && "Can't read debug loc from end()"
) ? static_cast<void> (0) : __assert_fail ("InsertPt != BB->end() && \"Can't read debug loc from end()\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 171, __PRETTY_FUNCTION__))
;
172 SetCurrentDebugLocation(I->getDebugLoc());
173 }
174
175 /// This specifies that created instructions should be inserted at the
176 /// specified point.
177 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
178 BB = TheBB;
179 InsertPt = IP;
180 if (IP != TheBB->end())
181 SetCurrentDebugLocation(IP->getDebugLoc());
182 }
183
184 /// Set location information used by debugging information.
185 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
186
187 /// Get location information used by debugging information.
188 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
189
190 /// If this builder has a current debug location, set it on the
191 /// specified instruction.
192 void SetInstDebugLocation(Instruction *I) const {
193 if (CurDbgLocation)
194 I->setDebugLoc(CurDbgLocation);
195 }
196
197 /// Get the return type of the current function that we're emitting
198 /// into.
199 Type *getCurrentFunctionReturnType() const;
200
201 /// InsertPoint - A saved insertion point.
202 class InsertPoint {
203 BasicBlock *Block = nullptr;
204 BasicBlock::iterator Point;
205
206 public:
207 /// Creates a new insertion point which doesn't point to anything.
208 InsertPoint() = default;
209
210 /// Creates a new insertion point at the given location.
211 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
212 : Block(InsertBlock), Point(InsertPoint) {}
213
214 /// Returns true if this insert point is set.
215 bool isSet() const { return (Block != nullptr); }
216
217 BasicBlock *getBlock() const { return Block; }
218 BasicBlock::iterator getPoint() const { return Point; }
219 };
220
221 /// Returns the current insert point.
222 InsertPoint saveIP() const {
223 return InsertPoint(GetInsertBlock(), GetInsertPoint());
224 }
225
226 /// Returns the current insert point, clearing it in the process.
227 InsertPoint saveAndClearIP() {
228 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
229 ClearInsertionPoint();
230 return IP;
231 }
232
233 /// Sets the current insert point to a previously-saved location.
234 void restoreIP(InsertPoint IP) {
235 if (IP.isSet())
236 SetInsertPoint(IP.getBlock(), IP.getPoint());
237 else
238 ClearInsertionPoint();
239 }
240
241 /// Get the floating point math metadata being used.
242 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
243
244 /// Get the flags to be applied to created floating point ops
245 FastMathFlags getFastMathFlags() const { return FMF; }
246
247 /// Clear the fast-math flags.
248 void clearFastMathFlags() { FMF.clear(); }
249
250 /// Set the floating point math metadata to be used.
251 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
252
253 /// Set the fast-math flags to be used with generated fp-math operators
254 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
255
256 /// Enable/Disable use of constrained floating point math. When
257 /// enabled the CreateF<op>() calls instead create constrained
258 /// floating point intrinsic calls. Fast math flags are unaffected
259 /// by this setting.
260 void setIsFPConstrained(bool IsCon) { IsFPConstrained = IsCon; }
261
262 /// Query for the use of constrained floating point math
263 bool getIsFPConstrained() { return IsFPConstrained; }
264
265 /// Set the exception handling to be used with constrained floating point
266 void setDefaultConstrainedExcept(fp::ExceptionBehavior NewExcept) {
267 DefaultConstrainedExcept = NewExcept;
268 }
269
270 /// Set the rounding mode handling to be used with constrained floating point
271 void setDefaultConstrainedRounding(fp::RoundingMode NewRounding) {
272 DefaultConstrainedRounding = NewRounding;
273 }
274
275 /// Get the exception handling used with constrained floating point
276 fp::ExceptionBehavior getDefaultConstrainedExcept() {
277 return DefaultConstrainedExcept;
278 }
279
280 /// Get the rounding mode handling used with constrained floating point
281 fp::RoundingMode getDefaultConstrainedRounding() {
282 return DefaultConstrainedRounding;
283 }
284
285 void setConstrainedFPFunctionAttr() {
286 assert(BB && "Must have a basic block to set any function attributes!")((BB && "Must have a basic block to set any function attributes!"
) ? static_cast<void> (0) : __assert_fail ("BB && \"Must have a basic block to set any function attributes!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 286, __PRETTY_FUNCTION__))
;
287
288 Function *F = BB->getParent();
289 if (!F->hasFnAttribute(Attribute::StrictFP)) {
290 F->addFnAttr(Attribute::StrictFP);
291 }
292 }
293
294 void setConstrainedFPCallAttr(CallInst *I) {
295 if (!I->hasFnAttr(Attribute::StrictFP))
296 I->addAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
297 }
298
299 void setDefaultOperandBundles(ArrayRef<OperandBundleDef> OpBundles) {
300 DefaultOperandBundles = OpBundles;
301 }
302
303 //===--------------------------------------------------------------------===//
304 // RAII helpers.
305 //===--------------------------------------------------------------------===//
306
307 // RAII object that stores the current insertion point and restores it
308 // when the object is destroyed. This includes the debug location.
309 class InsertPointGuard {
310 IRBuilderBase &Builder;
311 AssertingVH<BasicBlock> Block;
312 BasicBlock::iterator Point;
313 DebugLoc DbgLoc;
314
315 public:
316 InsertPointGuard(IRBuilderBase &B)
317 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
318 DbgLoc(B.getCurrentDebugLocation()) {}
319
320 InsertPointGuard(const InsertPointGuard &) = delete;
321 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
322
323 ~InsertPointGuard() {
324 Builder.restoreIP(InsertPoint(Block, Point));
325 Builder.SetCurrentDebugLocation(DbgLoc);
326 }
327 };
328
329 // RAII object that stores the current fast math settings and restores
330 // them when the object is destroyed.
331 class FastMathFlagGuard {
332 IRBuilderBase &Builder;
333 FastMathFlags FMF;
334 MDNode *FPMathTag;
335
336 public:
337 FastMathFlagGuard(IRBuilderBase &B)
338 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
339
340 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
341 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
342
343 ~FastMathFlagGuard() {
344 Builder.FMF = FMF;
345 Builder.DefaultFPMathTag = FPMathTag;
346 }
347 };
348
349 // RAII object that stores the current default operand bundles and restores
350 // them when the object is destroyed.
351 class OperandBundlesGuard {
352 IRBuilderBase &Builder;
353 ArrayRef<OperandBundleDef> DefaultOperandBundles;
354
355 public:
356 OperandBundlesGuard(IRBuilderBase &B)
357 : Builder(B), DefaultOperandBundles(B.DefaultOperandBundles) {}
358
359 OperandBundlesGuard(const OperandBundlesGuard &) = delete;
360 OperandBundlesGuard &operator=(const OperandBundlesGuard &) = delete;
361
362 ~OperandBundlesGuard() {
363 Builder.DefaultOperandBundles = DefaultOperandBundles;
364 }
365 };
366
367
368 //===--------------------------------------------------------------------===//
369 // Miscellaneous creation methods.
370 //===--------------------------------------------------------------------===//
371
372 /// Make a new global variable with initializer type i8*
373 ///
374 /// Make a new global variable with an initializer that has array of i8 type
375 /// filled in with the null terminated string value specified. The new global
376 /// variable will be marked mergable with any others of the same contents. If
377 /// Name is specified, it is the name of the global variable created.
378 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
379 unsigned AddressSpace = 0);
380
381 /// Get a constant value representing either true or false.
382 ConstantInt *getInt1(bool V) {
383 return ConstantInt::get(getInt1Ty(), V);
384 }
385
386 /// Get the constant value for i1 true.
387 ConstantInt *getTrue() {
388 return ConstantInt::getTrue(Context);
389 }
390
391 /// Get the constant value for i1 false.
392 ConstantInt *getFalse() {
393 return ConstantInt::getFalse(Context);
394 }
395
396 /// Get a constant 8-bit value.
397 ConstantInt *getInt8(uint8_t C) {
398 return ConstantInt::get(getInt8Ty(), C);
399 }
400
401 /// Get a constant 16-bit value.
402 ConstantInt *getInt16(uint16_t C) {
403 return ConstantInt::get(getInt16Ty(), C);
404 }
405
406 /// Get a constant 32-bit value.
407 ConstantInt *getInt32(uint32_t C) {
408 return ConstantInt::get(getInt32Ty(), C);
409 }
410
411 /// Get a constant 64-bit value.
412 ConstantInt *getInt64(uint64_t C) {
413 return ConstantInt::get(getInt64Ty(), C);
414 }
415
416 /// Get a constant N-bit value, zero extended or truncated from
417 /// a 64-bit value.
418 ConstantInt *getIntN(unsigned N, uint64_t C) {
419 return ConstantInt::get(getIntNTy(N), C);
420 }
421
422 /// Get a constant integer value.
423 ConstantInt *getInt(const APInt &AI) {
424 return ConstantInt::get(Context, AI);
425 }
426
427 //===--------------------------------------------------------------------===//
428 // Type creation methods
429 //===--------------------------------------------------------------------===//
430
431 /// Fetch the type representing a single bit
432 IntegerType *getInt1Ty() {
433 return Type::getInt1Ty(Context);
434 }
435
436 /// Fetch the type representing an 8-bit integer.
437 IntegerType *getInt8Ty() {
438 return Type::getInt8Ty(Context);
439 }
440
441 /// Fetch the type representing a 16-bit integer.
442 IntegerType *getInt16Ty() {
443 return Type::getInt16Ty(Context);
444 }
445
446 /// Fetch the type representing a 32-bit integer.
447 IntegerType *getInt32Ty() {
448 return Type::getInt32Ty(Context);
449 }
450
451 /// Fetch the type representing a 64-bit integer.
452 IntegerType *getInt64Ty() {
453 return Type::getInt64Ty(Context);
454 }
455
456 /// Fetch the type representing a 128-bit integer.
457 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
458
459 /// Fetch the type representing an N-bit integer.
460 IntegerType *getIntNTy(unsigned N) {
461 return Type::getIntNTy(Context, N);
462 }
463
464 /// Fetch the type representing a 16-bit floating point value.
465 Type *getHalfTy() {
466 return Type::getHalfTy(Context);
467 }
468
469 /// Fetch the type representing a 32-bit floating point value.
470 Type *getFloatTy() {
471 return Type::getFloatTy(Context);
472 }
473
474 /// Fetch the type representing a 64-bit floating point value.
475 Type *getDoubleTy() {
476 return Type::getDoubleTy(Context);
477 }
478
479 /// Fetch the type representing void.
480 Type *getVoidTy() {
481 return Type::getVoidTy(Context);
482 }
483
484 /// Fetch the type representing a pointer to an 8-bit integer value.
485 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
486 return Type::getInt8PtrTy(Context, AddrSpace);
487 }
488
489 /// Fetch the type representing a pointer to an integer value.
490 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
491 return DL.getIntPtrType(Context, AddrSpace);
492 }
493
494 //===--------------------------------------------------------------------===//
495 // Intrinsic creation methods
496 //===--------------------------------------------------------------------===//
497
498 /// Create and insert a memset to the specified pointer and the
499 /// specified value.
500 ///
501 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
502 /// specified, it will be added to the instruction. Likewise with alias.scope
503 /// and noalias tags.
504 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size,
505 MaybeAlign Align, bool isVolatile = false,
506 MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
507 MDNode *NoAliasTag = nullptr) {
508 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
509 TBAATag, ScopeTag, NoAliasTag);
510 }
511
512 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, MaybeAlign Align,
513 bool isVolatile = false, MDNode *TBAATag = nullptr,
514 MDNode *ScopeTag = nullptr,
515 MDNode *NoAliasTag = nullptr);
516
517 /// Create and insert an element unordered-atomic memset of the region of
518 /// memory starting at the given pointer to the given value.
519 ///
520 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
521 /// specified, it will be added to the instruction. Likewise with alias.scope
522 /// and noalias tags.
523 /// FIXME: Remove this function once transition to Align is over.
524 /// Use the version that takes Align instead of this one.
525 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
526 CallInst *CreateElementUnorderedAtomicMemSet(CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
527 Value *Ptr, Value *Val, uint64_t Size, unsigned Alignment,CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
528 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
529 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
530 "Use the version that takes Align instead of this one")CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, uint64_t Size, unsigned Alignment, uint32_t ElementSize
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
{
531 return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
532 Align(Alignment), ElementSize,
533 TBAATag, ScopeTag, NoAliasTag);
534 }
535
536 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
537 uint64_t Size, Align Alignment,
538 uint32_t ElementSize,
539 MDNode *TBAATag = nullptr,
540 MDNode *ScopeTag = nullptr,
541 MDNode *NoAliasTag = nullptr) {
542 return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size),
543 Align(Alignment), ElementSize,
544 TBAATag, ScopeTag, NoAliasTag);
545 }
546
547 /// FIXME: Remove this function once transition to Align is over.
548 /// Use the version that takes Align instead of this one.
549 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
550 CallInst *CreateElementUnorderedAtomicMemSet(CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
551 Value *Ptr, Value *Val, Value *Size, unsigned Alignment,CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
552 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
553 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
554 "Use the version that takes Align instead of this one")CallInst *CreateElementUnorderedAtomicMemSet( Value *Ptr, Value
*Val, Value *Size, unsigned Alignment, uint32_t ElementSize,
MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes Align instead of this one"
)))
{
555 return CreateElementUnorderedAtomicMemSet(Ptr, Val, Size, Align(Alignment),
556 ElementSize, TBAATag, ScopeTag,
557 NoAliasTag);
558 }
559
560 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
561 Value *Size, Align Alignment,
562 uint32_t ElementSize,
563 MDNode *TBAATag = nullptr,
564 MDNode *ScopeTag = nullptr,
565 MDNode *NoAliasTag = nullptr);
566
567 /// Create and insert a memcpy between the specified pointers.
568 ///
569 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
570 /// specified, it will be added to the instruction. Likewise with alias.scope
571 /// and noalias tags.
572 /// FIXME: Remove this function once transition to Align is over.
573 /// Use the version that takes MaybeAlign instead of this one.
574 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
575 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
576 unsigned SrcAlign, uint64_t Size,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
577 bool isVolatile = false, MDNode *TBAATag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
578 MDNode *TBAAStructTag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
579 MDNode *ScopeTag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
580 MDNode *NoAliasTag = nullptr),CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
581 "Use the version that takes MaybeAlign instead")CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr,
MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
{
582 return CreateMemCpy(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
583 getInt64(Size), isVolatile, TBAATag, TBAAStructTag,
584 ScopeTag, NoAliasTag);
585 }
586
587 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
588 MaybeAlign SrcAlign, uint64_t Size,
589 bool isVolatile = false, MDNode *TBAATag = nullptr,
590 MDNode *TBAAStructTag = nullptr,
591 MDNode *ScopeTag = nullptr,
592 MDNode *NoAliasTag = nullptr) {
593 return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
594 isVolatile, TBAATag, TBAAStructTag, ScopeTag,
595 NoAliasTag);
596 }
597
598 /// FIXME: Remove this function once transition to Align is over.
599 /// Use the version that takes MaybeAlign instead of this one.
600 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
601 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
602 unsigned SrcAlign, Value *Size,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
603 bool isVolatile = false, MDNode *TBAATag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
604 MDNode *TBAAStructTag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
605 MDNode *ScopeTag = nullptr,CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
606 MDNode *NoAliasTag = nullptr),CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
607 "Use the version that takes MaybeAlign instead")CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *
Src, unsigned SrcAlign, Value *Size, bool isVolatile = false,
MDNode *TBAATag = nullptr, MDNode *TBAAStructTag = nullptr, MDNode
*ScopeTag = nullptr, MDNode *NoAliasTag = nullptr) __attribute__
((deprecated("Use the version that takes MaybeAlign instead")
))
;
608 CallInst *CreateMemCpy(Value *Dst, MaybeAlign DstAlign, Value *Src,
609 MaybeAlign SrcAlign, Value *Size,
610 bool isVolatile = false, MDNode *TBAATag = nullptr,
611 MDNode *TBAAStructTag = nullptr,
612 MDNode *ScopeTag = nullptr,
613 MDNode *NoAliasTag = nullptr);
614
615 CallInst *CreateMemCpyInline(Value *Dst, MaybeAlign DstAlign, Value *Src,
616 MaybeAlign SrcAlign, Value *Size);
617
618 /// Create and insert an element unordered-atomic memcpy between the
619 /// specified pointers.
620 ///
621 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
622 ///
623 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
624 /// specified, it will be added to the instruction. Likewise with alias.scope
625 /// and noalias tags.
626 CallInst *CreateElementUnorderedAtomicMemCpy(
627 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
628 uint32_t ElementSize, MDNode *TBAATag = nullptr,
629 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
630 MDNode *NoAliasTag = nullptr);
631
632 /// FIXME: Remove this function once transition to Align is over.
633 /// Use the version that takes Align instead of this one.
634 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemCpy(CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
635 Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
636 unsigned SrcAlign, uint64_t Size,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
637 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
638 MDNode *TBAAStructTag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
639 MDNode *ScopeTag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
640 MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
641 "Use the version that takes Align instead")CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
642 return CreateElementUnorderedAtomicMemCpy(
643 Dst, Align(DstAlign), Src, Align(SrcAlign), getInt64(Size), ElementSize,
644 TBAATag, TBAAStructTag, ScopeTag, NoAliasTag);
645 }
646
647 /// FIXME: Remove this function once transition to Align is over.
648 /// Use the version that takes Align instead of this one.
649 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemCpy(CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
650 Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
651 unsigned SrcAlign, Value *Size,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
652 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
653 MDNode *TBAAStructTag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
654 MDNode *ScopeTag = nullptr,CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
655 MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
656 "Use the version that takes Align instead")CallInst *CreateElementUnorderedAtomicMemCpy( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
657 return CreateElementUnorderedAtomicMemCpy(
658 Dst, Align(DstAlign), Src, Align(SrcAlign), Size, ElementSize, TBAATag,
659 TBAAStructTag, ScopeTag, NoAliasTag);
660 }
661
662 /// Create and insert a memmove between the specified
663 /// pointers.
664 ///
665 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
666 /// specified, it will be added to the instruction. Likewise with alias.scope
667 /// and noalias tags.
668 /// FIXME: Remove this function once transition to Align is over.
669 /// Use the version that takes MaybeAlign instead of this one.
670 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
671 CallInst *CreateMemMove(CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
672 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
673 uint64_t Size, bool isVolatile = false, MDNode *TBAATag = nullptr,CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
674 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
675 "Use the version that takes MaybeAlign")CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, uint64_t Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
{
676 return CreateMemMove(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
677 getInt64(Size), isVolatile, TBAATag, ScopeTag,
678 NoAliasTag);
679 }
680 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
681 MaybeAlign SrcAlign, uint64_t Size,
682 bool isVolatile = false, MDNode *TBAATag = nullptr,
683 MDNode *ScopeTag = nullptr,
684 MDNode *NoAliasTag = nullptr) {
685 return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
686 isVolatile, TBAATag, ScopeTag, NoAliasTag);
687 }
688 /// FIXME: Remove this function once transition to Align is over.
689 /// Use the version that takes MaybeAlign instead of this one.
690 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
691 CallInst *CreateMemMove(CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
692 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
693 Value *Size, bool isVolatile = false, MDNode *TBAATag = nullptr,CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
694 MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr),CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
695 "Use the version that takes MaybeAlign")CallInst *CreateMemMove( Value *Dst, unsigned DstAlign, Value
*Src, unsigned SrcAlign, Value *Size, bool isVolatile = false
, MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr, MDNode
*NoAliasTag = nullptr) __attribute__((deprecated("Use the version that takes MaybeAlign"
)))
{
696 return CreateMemMove(Dst, MaybeAlign(DstAlign), Src, MaybeAlign(SrcAlign),
697 Size, isVolatile, TBAATag, ScopeTag, NoAliasTag);
698 }
699 CallInst *CreateMemMove(Value *Dst, MaybeAlign DstAlign, Value *Src,
700 MaybeAlign SrcAlign, Value *Size,
701 bool isVolatile = false, MDNode *TBAATag = nullptr,
702 MDNode *ScopeTag = nullptr,
703 MDNode *NoAliasTag = nullptr);
704
705 /// \brief Create and insert an element unordered-atomic memmove between the
706 /// specified pointers.
707 ///
708 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
709 /// respectively.
710 ///
711 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
712 /// specified, it will be added to the instruction. Likewise with alias.scope
713 /// and noalias tags.
714 CallInst *CreateElementUnorderedAtomicMemMove(
715 Value *Dst, Align DstAlign, Value *Src, Align SrcAlign, Value *Size,
716 uint32_t ElementSize, MDNode *TBAATag = nullptr,
717 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
718 MDNode *NoAliasTag = nullptr);
719
720 /// FIXME: Remove this function once transition to Align is over.
721 /// Use the version that takes Align instead of this one.
722 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemMove(CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
723 Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
724 unsigned SrcAlign, uint64_t Size,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
725 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
726 MDNode *TBAAStructTag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
727 MDNode *ScopeTag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
728 MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
729 "Use the version that takes Align instead")CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, uint64_t Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
730 return CreateElementUnorderedAtomicMemMove(
731 Dst, Align(DstAlign), Src, Align(SrcAlign), getInt64(Size), ElementSize,
732 TBAATag, TBAAStructTag, ScopeTag, NoAliasTag);
733 }
734
735 /// FIXME: Remove this function once transition to Align is over.
736 /// Use the version that takes Align instead of this one.
737 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateElementUnorderedAtomicMemMove(CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
738 Value *Dst, unsigned DstAlign, Value *Src,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
739 unsigned SrcAlign, Value *Size,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
740 uint32_t ElementSize, MDNode *TBAATag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
741 MDNode *TBAAStructTag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
742 MDNode *ScopeTag = nullptr,CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
743 MDNode *NoAliasTag = nullptr),CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
744 "Use the version that takes Align instead")CallInst *CreateElementUnorderedAtomicMemMove( Value *Dst, unsigned
DstAlign, Value *Src, unsigned SrcAlign, Value *Size, uint32_t
ElementSize, MDNode *TBAATag = nullptr, MDNode *TBAAStructTag
= nullptr, MDNode *ScopeTag = nullptr, MDNode *NoAliasTag = nullptr
) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
745 return CreateElementUnorderedAtomicMemMove(
746 Dst, Align(DstAlign), Src, Align(SrcAlign), Size, ElementSize, TBAATag,
747 TBAAStructTag, ScopeTag, NoAliasTag);
748 }
749
750 /// Create a vector fadd reduction intrinsic of the source vector.
751 /// The first parameter is a scalar accumulator value for ordered reductions.
752 CallInst *CreateFAddReduce(Value *Acc, Value *Src);
753
754 /// Create a vector fmul reduction intrinsic of the source vector.
755 /// The first parameter is a scalar accumulator value for ordered reductions.
756 CallInst *CreateFMulReduce(Value *Acc, Value *Src);
757
758 /// Create a vector int add reduction intrinsic of the source vector.
759 CallInst *CreateAddReduce(Value *Src);
760
761 /// Create a vector int mul reduction intrinsic of the source vector.
762 CallInst *CreateMulReduce(Value *Src);
763
764 /// Create a vector int AND reduction intrinsic of the source vector.
765 CallInst *CreateAndReduce(Value *Src);
766
767 /// Create a vector int OR reduction intrinsic of the source vector.
768 CallInst *CreateOrReduce(Value *Src);
769
770 /// Create a vector int XOR reduction intrinsic of the source vector.
771 CallInst *CreateXorReduce(Value *Src);
772
773 /// Create a vector integer max reduction intrinsic of the source
774 /// vector.
775 CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
776
777 /// Create a vector integer min reduction intrinsic of the source
778 /// vector.
779 CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
780
781 /// Create a vector float max reduction intrinsic of the source
782 /// vector.
783 CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
784
785 /// Create a vector float min reduction intrinsic of the source
786 /// vector.
787 CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
788
789 /// Create a lifetime.start intrinsic.
790 ///
791 /// If the pointer isn't i8* it will be converted.
792 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
793
794 /// Create a lifetime.end intrinsic.
795 ///
796 /// If the pointer isn't i8* it will be converted.
797 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
798
799 /// Create a call to invariant.start intrinsic.
800 ///
801 /// If the pointer isn't i8* it will be converted.
802 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
803
804 /// Create a call to Masked Load intrinsic
805 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value
*Mask, Value *PassThru = nullptr, const Twine &Name = ""
) __attribute__((deprecated("Use the version that takes Align instead"
)))
806 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value *Mask,CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value
*Mask, Value *PassThru = nullptr, const Twine &Name = ""
) __attribute__((deprecated("Use the version that takes Align instead"
)))
807 Value *PassThru = nullptr,CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value
*Mask, Value *PassThru = nullptr, const Twine &Name = ""
) __attribute__((deprecated("Use the version that takes Align instead"
)))
808 const Twine &Name = ""),CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value
*Mask, Value *PassThru = nullptr, const Twine &Name = ""
) __attribute__((deprecated("Use the version that takes Align instead"
)))
809 "Use the version that takes Align instead")CallInst *CreateMaskedLoad(Value *Ptr, unsigned Alignment, Value
*Mask, Value *PassThru = nullptr, const Twine &Name = ""
) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
810 return CreateMaskedLoad(Ptr, assumeAligned(Alignment), Mask, PassThru,
811 Name);
812 }
813 CallInst *CreateMaskedLoad(Value *Ptr, Align Alignment, Value *Mask,
814 Value *PassThru = nullptr, const Twine &Name = "");
815
816 /// Create a call to Masked Store intrinsic
817 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMaskedStore(Value *Val, Value *Ptr,CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Alignment
, Value *Mask) __attribute__((deprecated("Use the version that takes Align instead"
)))
818 unsigned Alignment,CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Alignment
, Value *Mask) __attribute__((deprecated("Use the version that takes Align instead"
)))
819 Value *Mask),CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Alignment
, Value *Mask) __attribute__((deprecated("Use the version that takes Align instead"
)))
820 "Use the version that takes Align instead")CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Alignment
, Value *Mask) __attribute__((deprecated("Use the version that takes Align instead"
)))
{
821 return CreateMaskedStore(Val, Ptr, assumeAligned(Alignment), Mask);
822 }
823
824 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, Align Alignment,
825 Value *Mask);
826
827 /// Create a call to Masked Gather intrinsic
828 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
829 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
830 Value *Mask = nullptr,CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
831 Value *PassThru = nullptr,CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
832 const Twine &Name = ""),CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
833 "Use the version that takes Align instead")CallInst *CreateMaskedGather(Value *Ptrs, unsigned Alignment,
Value *Mask = nullptr, Value *PassThru = nullptr, const Twine
&Name = "") __attribute__((deprecated("Use the version that takes Align instead"
)))
{
834 return CreateMaskedGather(Ptrs, Align(Alignment), Mask, PassThru, Name);
835 }
836
837 /// Create a call to Masked Gather intrinsic
838 CallInst *CreateMaskedGather(Value *Ptrs, Align Alignment,
839 Value *Mask = nullptr, Value *PassThru = nullptr,
840 const Twine &Name = "");
841
842 /// Create a call to Masked Scatter intrinsic
843 LLVM_ATTRIBUTE_DEPRECATED(CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned
Alignment, Value *Mask = nullptr) __attribute__((deprecated(
"Use the version that takes Align instead")))
844 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Alignment,CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned
Alignment, Value *Mask = nullptr) __attribute__((deprecated(
"Use the version that takes Align instead")))
845 Value *Mask = nullptr),CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned
Alignment, Value *Mask = nullptr) __attribute__((deprecated(
"Use the version that takes Align instead")))
846 "Use the version that takes Align instead")CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned
Alignment, Value *Mask = nullptr) __attribute__((deprecated(
"Use the version that takes Align instead")))
{
847 return CreateMaskedScatter(Val, Ptrs, Align(Alignment), Mask);
848 }
849
850 /// Create a call to Masked Scatter intrinsic
851 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, Align Alignment,
852 Value *Mask = nullptr);
853
854 /// Create an assume intrinsic call that allows the optimizer to
855 /// assume that the provided condition will be true.
856 CallInst *CreateAssumption(Value *Cond);
857
858 /// Create a call to the experimental.gc.statepoint intrinsic to
859 /// start a new statepoint sequence.
860 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
861 Value *ActualCallee,
862 ArrayRef<Value *> CallArgs,
863 ArrayRef<Value *> DeoptArgs,
864 ArrayRef<Value *> GCArgs,
865 const Twine &Name = "");
866
867 /// Create a call to the experimental.gc.statepoint intrinsic to
868 /// start a new statepoint sequence.
869 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
870 Value *ActualCallee, uint32_t Flags,
871 ArrayRef<Use> CallArgs,
872 ArrayRef<Use> TransitionArgs,
873 ArrayRef<Use> DeoptArgs,
874 ArrayRef<Value *> GCArgs,
875 const Twine &Name = "");
876
877 /// Conveninence function for the common case when CallArgs are filled
878 /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
879 /// .get()'ed to get the Value pointer.
880 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
881 Value *ActualCallee, ArrayRef<Use> CallArgs,
882 ArrayRef<Value *> DeoptArgs,
883 ArrayRef<Value *> GCArgs,
884 const Twine &Name = "");
885
886 /// Create an invoke to the experimental.gc.statepoint intrinsic to
887 /// start a new statepoint sequence.
888 InvokeInst *
889 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
890 Value *ActualInvokee, BasicBlock *NormalDest,
891 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
892 ArrayRef<Value *> DeoptArgs,
893 ArrayRef<Value *> GCArgs, const Twine &Name = "");
894
895 /// Create an invoke to the experimental.gc.statepoint intrinsic to
896 /// start a new statepoint sequence.
897 InvokeInst *CreateGCStatepointInvoke(
898 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
899 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
900 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
901 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
902 const Twine &Name = "");
903
904 // Convenience function for the common case when CallArgs are filled in using
905 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
906 // get the Value *.
907 InvokeInst *
908 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
909 Value *ActualInvokee, BasicBlock *NormalDest,
910 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
911 ArrayRef<Value *> DeoptArgs,
912 ArrayRef<Value *> GCArgs, const Twine &Name = "");
913
914 /// Create a call to the experimental.gc.result intrinsic to extract
915 /// the result from a call wrapped in a statepoint.
916 CallInst *CreateGCResult(Instruction *Statepoint,
917 Type *ResultType,
918 const Twine &Name = "");
919
920 /// Create a call to the experimental.gc.relocate intrinsics to
921 /// project the relocated value of one pointer from the statepoint.
922 CallInst *CreateGCRelocate(Instruction *Statepoint,
923 int BaseOffset,
924 int DerivedOffset,
925 Type *ResultType,
926 const Twine &Name = "");
927
928 /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
929 /// type.
930 CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
931 Instruction *FMFSource = nullptr,
932 const Twine &Name = "");
933
934 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
935 /// first type.
936 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
937 Instruction *FMFSource = nullptr,
938 const Twine &Name = "");
939
940 /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
941 /// \p FMFSource is provided, copy fast-math-flags from that instruction to
942 /// the intrinsic.
943 CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
944 ArrayRef<Value *> Args,
945 Instruction *FMFSource = nullptr,
946 const Twine &Name = "");
947
948 /// Create call to the minnum intrinsic.
949 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
950 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
951 }
952
953 /// Create call to the maxnum intrinsic.
954 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
955 return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
956 }
957
958 /// Create call to the minimum intrinsic.
959 CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
960 return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
961 }
962
963 /// Create call to the maximum intrinsic.
964 CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
965 return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
966 }
967
968private:
969 /// Create a call to a masked intrinsic with given Id.
970 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
971 ArrayRef<Type *> OverloadedTypes,
972 const Twine &Name = "");
973
974 Value *getCastedInt8PtrValue(Value *Ptr);
975
976 //===--------------------------------------------------------------------===//
977 // Instruction creation methods: Terminators
978 //===--------------------------------------------------------------------===//
979
980private:
981 /// Helper to add branch weight and unpredictable metadata onto an
982 /// instruction.
983 /// \returns The annotated instruction.
984 template <typename InstTy>
985 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
986 if (Weights)
987 I->setMetadata(LLVMContext::MD_prof, Weights);
988 if (Unpredictable)
989 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
990 return I;
991 }
992
993public:
994 /// Create a 'ret void' instruction.
995 ReturnInst *CreateRetVoid() {
996 return Insert(ReturnInst::Create(Context));
997 }
998
999 /// Create a 'ret <val>' instruction.
1000 ReturnInst *CreateRet(Value *V) {
1001 return Insert(ReturnInst::Create(Context, V));
1002 }
1003
1004 /// Create a sequence of N insertvalue instructions,
1005 /// with one Value from the retVals array each, that build a aggregate
1006 /// return value one value at a time, and a ret instruction to return
1007 /// the resulting aggregate value.
1008 ///
1009 /// This is a convenience function for code that uses aggregate return values
1010 /// as a vehicle for having multiple return values.
1011 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
1012 Value *V = UndefValue::get(getCurrentFunctionReturnType());
1013 for (unsigned i = 0; i != N; ++i)
1014 V = CreateInsertValue(V, retVals[i], i, "mrv");
1015 return Insert(ReturnInst::Create(Context, V));
1016 }
1017
1018 /// Create an unconditional 'br label X' instruction.
1019 BranchInst *CreateBr(BasicBlock *Dest) {
1020 return Insert(BranchInst::Create(Dest));
1021 }
1022
1023 /// Create a conditional 'br Cond, TrueDest, FalseDest'
1024 /// instruction.
1025 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
1026 MDNode *BranchWeights = nullptr,
1027 MDNode *Unpredictable = nullptr) {
1028 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
1029 BranchWeights, Unpredictable));
1030 }
1031
1032 /// Create a conditional 'br Cond, TrueDest, FalseDest'
1033 /// instruction. Copy branch meta data if available.
1034 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
1035 Instruction *MDSrc) {
1036 BranchInst *Br = BranchInst::Create(True, False, Cond);
1037 if (MDSrc) {
1038 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
1039 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
1040 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
1041 }
1042 return Insert(Br);
1043 }
1044
1045 /// Create a switch instruction with the specified value, default dest,
1046 /// and with a hint for the number of cases that will be added (for efficient
1047 /// allocation).
1048 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
1049 MDNode *BranchWeights = nullptr,
1050 MDNode *Unpredictable = nullptr) {
1051 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
1052 BranchWeights, Unpredictable));
1053 }
1054
1055 /// Create an indirect branch instruction with the specified address
1056 /// operand, with an optional hint for the number of destinations that will be
1057 /// added (for efficient allocation).
1058 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
1059 return Insert(IndirectBrInst::Create(Addr, NumDests));
1060 }
1061
1062 /// Create an invoke instruction.
1063 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1064 BasicBlock *NormalDest, BasicBlock *UnwindDest,
1065 ArrayRef<Value *> Args,
1066 ArrayRef<OperandBundleDef> OpBundles,
1067 const Twine &Name = "") {
1068 return Insert(
1069 InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args, OpBundles),
1070 Name);
1071 }
1072 InvokeInst *CreateInvoke(FunctionType *Ty, Value *Callee,
1073 BasicBlock *NormalDest, BasicBlock *UnwindDest,
1074 ArrayRef<Value *> Args = None,
1075 const Twine &Name = "") {
1076 return Insert(InvokeInst::Create(Ty, Callee, NormalDest, UnwindDest, Args),
1077 Name);
1078 }
1079
1080 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1081 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1082 ArrayRef<OperandBundleDef> OpBundles,
1083 const Twine &Name = "") {
1084 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1085 NormalDest, UnwindDest, Args, OpBundles, Name);
1086 }
1087
1088 InvokeInst *CreateInvoke(FunctionCallee Callee, BasicBlock *NormalDest,
1089 BasicBlock *UnwindDest,
1090 ArrayRef<Value *> Args = None,
1091 const Twine &Name = "") {
1092 return CreateInvoke(Callee.getFunctionType(), Callee.getCallee(),
1093 NormalDest, UnwindDest, Args, Name);
1094 }
1095
1096 // Deprecated [opaque pointer types]
1097 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
1098 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
1099 ArrayRef<OperandBundleDef> OpBundles,
1100 const Twine &Name = "") {
1101 return CreateInvoke(
1102 cast<FunctionType>(
1103 cast<PointerType>(Callee->getType())->getElementType()),
1104 Callee, NormalDest, UnwindDest, Args, OpBundles, Name);
1105 }
1106
1107 // Deprecated [opaque pointer types]
1108 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
1109 BasicBlock *UnwindDest,
1110 ArrayRef<Value *> Args = None,
1111 const Twine &Name = "") {
1112 return CreateInvoke(
1113 cast<FunctionType>(
1114 cast<PointerType>(Callee->getType())->getElementType()),
1115 Callee, NormalDest, UnwindDest, Args, Name);
1116 }
1117
1118 /// \brief Create a callbr instruction.
1119 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1120 BasicBlock *DefaultDest,
1121 ArrayRef<BasicBlock *> IndirectDests,
1122 ArrayRef<Value *> Args = None,
1123 const Twine &Name = "") {
1124 return Insert(CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests,
1125 Args), Name);
1126 }
1127 CallBrInst *CreateCallBr(FunctionType *Ty, Value *Callee,
1128 BasicBlock *DefaultDest,
1129 ArrayRef<BasicBlock *> IndirectDests,
1130 ArrayRef<Value *> Args,
1131 ArrayRef<OperandBundleDef> OpBundles,
1132 const Twine &Name = "") {
1133 return Insert(
1134 CallBrInst::Create(Ty, Callee, DefaultDest, IndirectDests, Args,
1135 OpBundles), Name);
1136 }
1137
1138 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1139 ArrayRef<BasicBlock *> IndirectDests,
1140 ArrayRef<Value *> Args = None,
1141 const Twine &Name = "") {
1142 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1143 DefaultDest, IndirectDests, Args, Name);
1144 }
1145 CallBrInst *CreateCallBr(FunctionCallee Callee, BasicBlock *DefaultDest,
1146 ArrayRef<BasicBlock *> IndirectDests,
1147 ArrayRef<Value *> Args,
1148 ArrayRef<OperandBundleDef> OpBundles,
1149 const Twine &Name = "") {
1150 return CreateCallBr(Callee.getFunctionType(), Callee.getCallee(),
1151 DefaultDest, IndirectDests, Args, Name);
1152 }
1153
1154 ResumeInst *CreateResume(Value *Exn) {
1155 return Insert(ResumeInst::Create(Exn));
1156 }
1157
1158 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
1159 BasicBlock *UnwindBB = nullptr) {
1160 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
1161 }
1162
1163 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
1164 unsigned NumHandlers,
1165 const Twine &Name = "") {
1166 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
1167 Name);
1168 }
1169
1170 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
1171 const Twine &Name = "") {
1172 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
1173 }
1174
1175 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
1176 ArrayRef<Value *> Args = None,
1177 const Twine &Name = "") {
1178 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
1179 }
1180
1181 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
1182 return Insert(CatchReturnInst::Create(CatchPad, BB));
1183 }
1184
1185 UnreachableInst *CreateUnreachable() {
1186 return Insert(new UnreachableInst(Context));
1187 }
1188
1189 //===--------------------------------------------------------------------===//
1190 // Instruction creation methods: Binary Operators
1191 //===--------------------------------------------------------------------===//
1192private:
1193 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
1194 Value *LHS, Value *RHS,
1195 const Twine &Name,
1196 bool HasNUW, bool HasNSW) {
1197 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
1198 if (HasNUW) BO->setHasNoUnsignedWrap();
1199 if (HasNSW) BO->setHasNoSignedWrap();
1200 return BO;
1201 }
1202
1203 Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
1204 FastMathFlags FMF) const {
1205 if (!FPMD)
1206 FPMD = DefaultFPMathTag;
1207 if (FPMD)
1208 I->setMetadata(LLVMContext::MD_fpmath, FPMD);
1209 I->setFastMathFlags(FMF);
1210 return I;
1211 }
1212
1213 Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
1214 Value *R, const Twine &Name) const {
1215 auto *LC = dyn_cast<Constant>(L);
1216 auto *RC = dyn_cast<Constant>(R);
1217 return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
1218 }
1219
1220 Value *getConstrainedFPRounding(Optional<fp::RoundingMode> Rounding) {
1221 fp::RoundingMode UseRounding = DefaultConstrainedRounding;
1222
1223 if (Rounding.hasValue())
1224 UseRounding = Rounding.getValue();
1225
1226 Optional<StringRef> RoundingStr = RoundingModeToStr(UseRounding);
1227 assert(RoundingStr.hasValue() && "Garbage strict rounding mode!")((RoundingStr.hasValue() && "Garbage strict rounding mode!"
) ? static_cast<void> (0) : __assert_fail ("RoundingStr.hasValue() && \"Garbage strict rounding mode!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1227, __PRETTY_FUNCTION__))
;
1228 auto *RoundingMDS = MDString::get(Context, RoundingStr.getValue());
1229
1230 return MetadataAsValue::get(Context, RoundingMDS);
1231 }
1232
1233 Value *getConstrainedFPExcept(Optional<fp::ExceptionBehavior> Except) {
1234 fp::ExceptionBehavior UseExcept = DefaultConstrainedExcept;
1235
1236 if (Except.hasValue())
1237 UseExcept = Except.getValue();
1238
1239 Optional<StringRef> ExceptStr = ExceptionBehaviorToStr(UseExcept);
1240 assert(ExceptStr.hasValue() && "Garbage strict exception behavior!")((ExceptStr.hasValue() && "Garbage strict exception behavior!"
) ? static_cast<void> (0) : __assert_fail ("ExceptStr.hasValue() && \"Garbage strict exception behavior!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1240, __PRETTY_FUNCTION__))
;
1241 auto *ExceptMDS = MDString::get(Context, ExceptStr.getValue());
1242
1243 return MetadataAsValue::get(Context, ExceptMDS);
1244 }
1245
1246 Value *getConstrainedFPPredicate(CmpInst::Predicate Predicate) {
1247 assert(CmpInst::isFPPredicate(Predicate) &&((CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst
::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE &&
"Invalid constrained FP comparison predicate!") ? static_cast
<void> (0) : __assert_fail ("CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE && \"Invalid constrained FP comparison predicate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1250, __PRETTY_FUNCTION__))
1248 Predicate != CmpInst::FCMP_FALSE &&((CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst
::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE &&
"Invalid constrained FP comparison predicate!") ? static_cast
<void> (0) : __assert_fail ("CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE && \"Invalid constrained FP comparison predicate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1250, __PRETTY_FUNCTION__))
1249 Predicate != CmpInst::FCMP_TRUE &&((CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst
::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE &&
"Invalid constrained FP comparison predicate!") ? static_cast
<void> (0) : __assert_fail ("CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE && \"Invalid constrained FP comparison predicate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1250, __PRETTY_FUNCTION__))
1250 "Invalid constrained FP comparison predicate!")((CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst
::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE &&
"Invalid constrained FP comparison predicate!") ? static_cast
<void> (0) : __assert_fail ("CmpInst::isFPPredicate(Predicate) && Predicate != CmpInst::FCMP_FALSE && Predicate != CmpInst::FCMP_TRUE && \"Invalid constrained FP comparison predicate!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/IR/IRBuilder.h"
, 1250, __PRETTY_FUNCTION__))
;
1251
1252 StringRef PredicateStr = CmpInst::getPredicateName(Predicate);
1253 auto *PredicateMDS = MDString::get(Context, PredicateStr);
1254
1255 return MetadataAsValue::get(Context, PredicateMDS);
1256 }
1257
1258public:
1259 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
1260 bool HasNUW = false, bool HasNSW = false) {
1261 if (auto *LC = dyn_cast<Constant>(LHS))
1262 if (auto *RC = dyn_cast<Constant>(RHS))
1263 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
1264 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
1265 HasNUW, HasNSW);
1266 }
1267
1268 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1269 return CreateAdd(LHS, RHS, Name, false, true);
1270 }
1271
1272 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
1273 return CreateAdd(LHS, RHS, Name, true, false);
1274 }
1275
1276 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
1277 bool HasNUW = false, bool HasNSW = false) {
1278 if (auto *LC = dyn_cast<Constant>(LHS))
1279 if (auto *RC = dyn_cast<Constant>(RHS))
1280 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
1281 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
1282 HasNUW, HasNSW);
1283 }
1284
1285 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1286 return CreateSub(LHS, RHS, Name, false, true);
1287 }
1288
1289 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1290 return CreateSub(LHS, RHS, Name, true, false);
1291 }
1292
1293 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
1294 bool HasNUW = false, bool HasNSW = false) {
1295 if (auto *LC = dyn_cast<Constant>(LHS))
1296 if (auto *RC = dyn_cast<Constant>(RHS))
1297 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1298 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1299 HasNUW, HasNSW);
1300 }
1301
1302 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1303 return CreateMul(LHS, RHS, Name, false, true);
1304 }
1305
1306 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1307 return CreateMul(LHS, RHS, Name, true, false);
1308 }
1309
1310 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1311 bool isExact = false) {
1312 if (auto *LC = dyn_cast<Constant>(LHS))
1313 if (auto *RC = dyn_cast<Constant>(RHS))
1314 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1315 if (!isExact)
1316 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1317 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1318 }
1319
1320 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1321 return CreateUDiv(LHS, RHS, Name, true);
1322 }
1323
1324 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1325 bool isExact = false) {
1326 if (auto *LC = dyn_cast<Constant>(LHS))
1327 if (auto *RC = dyn_cast<Constant>(RHS))
1328 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1329 if (!isExact)
1330 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1331 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1332 }
1333
1334 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1335 return CreateSDiv(LHS, RHS, Name, true);
1336 }
1337
1338 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1339 if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1340 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1341 }
1342
1343 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1344 if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1345 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1346 }
1347
1348 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1349 bool HasNUW = false, bool HasNSW = false) {
1350 if (auto *LC = dyn_cast<Constant>(LHS))
1351 if (auto *RC = dyn_cast<Constant>(RHS))
1352 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1353 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1354 HasNUW, HasNSW);
1355 }
1356
1357 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1358 bool HasNUW = false, bool HasNSW = false) {
1359 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1360 HasNUW, HasNSW);
1361 }
1362
1363 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1364 bool HasNUW = false, bool HasNSW = false) {
1365 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1366 HasNUW, HasNSW);
1367 }
1368
1369 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1370 bool isExact = false) {
1371 if (auto *LC = dyn_cast<Constant>(LHS))
1372 if (auto *RC = dyn_cast<Constant>(RHS))
1373 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1374 if (!isExact)
1375 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1376 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1377 }
1378
1379 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1380 bool isExact = false) {
1381 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1382 }
1383
1384 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1385 bool isExact = false) {
1386 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1387 }
1388
1389 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1390 bool isExact = false) {
1391 if (auto *LC = dyn_cast<Constant>(LHS))
1392 if (auto *RC = dyn_cast<Constant>(RHS))
1393 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1394 if (!isExact)
1395 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1396 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1397 }
1398
1399 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1400 bool isExact = false) {
1401 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1402 }
1403
1404 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1405 bool isExact = false) {
1406 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1407 }
1408
1409 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1410 if (auto *RC = dyn_cast<Constant>(RHS)) {
1411 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isMinusOne())
1412 return LHS; // LHS & -1 -> LHS
1413 if (auto *LC = dyn_cast<Constant>(LHS))
1414 return Insert(Folder.CreateAnd(LC, RC), Name);
1415 }
1416 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1417 }
1418
1419 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1420 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1421 }
1422
1423 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1424 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1425 }
1426
1427 Value *CreateAnd(ArrayRef<Value*> Ops) {