Bug Summary

File:llvm/lib/Transforms/InstCombine/InstCombineInternal.h
Warning:line 412, column 5
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name InstructionCombining.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 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Transforms/InstCombine -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/lib/Transforms/InstCombine -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp

1//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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// InstructionCombining - Combine instructions to form fewer, simple
10// instructions. This pass does not modify the CFG. This pass is where
11// algebraic simplification happens.
12//
13// This pass combines things like:
14// %Y = add i32 %X, 1
15// %Z = add i32 %Y, 1
16// into:
17// %Z = add i32 %X, 2
18//
19// This is a simple worklist driven algorithm.
20//
21// This pass guarantees that the following canonicalizations are performed on
22// the program:
23// 1. If a binary operator has a constant operand, it is moved to the RHS
24// 2. Bitwise operators with constant operands are always grouped so that
25// shifts are performed first, then or's, then and's, then xor's.
26// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
27// 4. All cmp instructions on boolean values are replaced with logical ops
28// 5. add X, X is represented as (X*2) => (X << 1)
29// 6. Multiplies with a power-of-two constant argument are transformed into
30// shifts.
31// ... etc.
32//
33//===----------------------------------------------------------------------===//
34
35#include "InstCombineInternal.h"
36#include "llvm-c/Initialization.h"
37#include "llvm-c/Transforms/InstCombine.h"
38#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/None.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include "llvm/ADT/Statistic.h"
45#include "llvm/ADT/TinyPtrVector.h"
46#include "llvm/Analysis/AliasAnalysis.h"
47#include "llvm/Analysis/AssumptionCache.h"
48#include "llvm/Analysis/BasicAliasAnalysis.h"
49#include "llvm/Analysis/BlockFrequencyInfo.h"
50#include "llvm/Analysis/CFG.h"
51#include "llvm/Analysis/ConstantFolding.h"
52#include "llvm/Analysis/EHPersonalities.h"
53#include "llvm/Analysis/GlobalsModRef.h"
54#include "llvm/Analysis/InstructionSimplify.h"
55#include "llvm/Analysis/LazyBlockFrequencyInfo.h"
56#include "llvm/Analysis/LoopInfo.h"
57#include "llvm/Analysis/MemoryBuiltins.h"
58#include "llvm/Analysis/OptimizationRemarkEmitter.h"
59#include "llvm/Analysis/ProfileSummaryInfo.h"
60#include "llvm/Analysis/TargetFolder.h"
61#include "llvm/Analysis/TargetLibraryInfo.h"
62#include "llvm/Analysis/TargetTransformInfo.h"
63#include "llvm/Analysis/ValueTracking.h"
64#include "llvm/Analysis/VectorUtils.h"
65#include "llvm/IR/BasicBlock.h"
66#include "llvm/IR/CFG.h"
67#include "llvm/IR/Constant.h"
68#include "llvm/IR/Constants.h"
69#include "llvm/IR/DIBuilder.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DerivedTypes.h"
72#include "llvm/IR/Dominators.h"
73#include "llvm/IR/Function.h"
74#include "llvm/IR/GetElementPtrTypeIterator.h"
75#include "llvm/IR/IRBuilder.h"
76#include "llvm/IR/InstrTypes.h"
77#include "llvm/IR/Instruction.h"
78#include "llvm/IR/Instructions.h"
79#include "llvm/IR/IntrinsicInst.h"
80#include "llvm/IR/Intrinsics.h"
81#include "llvm/IR/LegacyPassManager.h"
82#include "llvm/IR/Metadata.h"
83#include "llvm/IR/Operator.h"
84#include "llvm/IR/PassManager.h"
85#include "llvm/IR/PatternMatch.h"
86#include "llvm/IR/Type.h"
87#include "llvm/IR/Use.h"
88#include "llvm/IR/User.h"
89#include "llvm/IR/Value.h"
90#include "llvm/IR/ValueHandle.h"
91#include "llvm/InitializePasses.h"
92#include "llvm/Pass.h"
93#include "llvm/Support/CBindingWrapping.h"
94#include "llvm/Support/Casting.h"
95#include "llvm/Support/CommandLine.h"
96#include "llvm/Support/Compiler.h"
97#include "llvm/Support/Debug.h"
98#include "llvm/Support/DebugCounter.h"
99#include "llvm/Support/ErrorHandling.h"
100#include "llvm/Support/KnownBits.h"
101#include "llvm/Support/raw_ostream.h"
102#include "llvm/Transforms/InstCombine/InstCombine.h"
103#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
104#include "llvm/Transforms/Utils/Local.h"
105#include <algorithm>
106#include <cassert>
107#include <cstdint>
108#include <memory>
109#include <string>
110#include <utility>
111
112using namespace llvm;
113using namespace llvm::PatternMatch;
114
115#define DEBUG_TYPE"instcombine" "instcombine"
116
117STATISTIC(NumWorklistIterations,static llvm::Statistic NumWorklistIterations = {"instcombine"
, "NumWorklistIterations", "Number of instruction combining iterations performed"
}
118 "Number of instruction combining iterations performed")static llvm::Statistic NumWorklistIterations = {"instcombine"
, "NumWorklistIterations", "Number of instruction combining iterations performed"
}
;
119
120STATISTIC(NumCombined , "Number of insts combined")static llvm::Statistic NumCombined = {"instcombine", "NumCombined"
, "Number of insts combined"}
;
121STATISTIC(NumConstProp, "Number of constant folds")static llvm::Statistic NumConstProp = {"instcombine", "NumConstProp"
, "Number of constant folds"}
;
122STATISTIC(NumDeadInst , "Number of dead inst eliminated")static llvm::Statistic NumDeadInst = {"instcombine", "NumDeadInst"
, "Number of dead inst eliminated"}
;
123STATISTIC(NumSunkInst , "Number of instructions sunk")static llvm::Statistic NumSunkInst = {"instcombine", "NumSunkInst"
, "Number of instructions sunk"}
;
124STATISTIC(NumExpand, "Number of expansions")static llvm::Statistic NumExpand = {"instcombine", "NumExpand"
, "Number of expansions"}
;
125STATISTIC(NumFactor , "Number of factorizations")static llvm::Statistic NumFactor = {"instcombine", "NumFactor"
, "Number of factorizations"}
;
126STATISTIC(NumReassoc , "Number of reassociations")static llvm::Statistic NumReassoc = {"instcombine", "NumReassoc"
, "Number of reassociations"}
;
127DEBUG_COUNTER(VisitCounter, "instcombine-visit",static const unsigned VisitCounter = DebugCounter::registerCounter
("instcombine-visit", "Controls which instructions are visited"
)
128 "Controls which instructions are visited")static const unsigned VisitCounter = DebugCounter::registerCounter
("instcombine-visit", "Controls which instructions are visited"
)
;
129
130// FIXME: these limits eventually should be as low as 2.
131static constexpr unsigned InstCombineDefaultMaxIterations = 1000;
132#ifndef NDEBUG
133static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 100;
134#else
135static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold = 1000;
136#endif
137
138static cl::opt<bool>
139EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
140 cl::init(true));
141
142static cl::opt<unsigned> LimitMaxIterations(
143 "instcombine-max-iterations",
144 cl::desc("Limit the maximum number of instruction combining iterations"),
145 cl::init(InstCombineDefaultMaxIterations));
146
147static cl::opt<unsigned> InfiniteLoopDetectionThreshold(
148 "instcombine-infinite-loop-threshold",
149 cl::desc("Number of instruction combining iterations considered an "
150 "infinite loop"),
151 cl::init(InstCombineDefaultInfiniteLoopThreshold), cl::Hidden);
152
153static cl::opt<unsigned>
154MaxArraySize("instcombine-maxarray-size", cl::init(1024),
155 cl::desc("Maximum array size considered when doing a combine"));
156
157// FIXME: Remove this flag when it is no longer necessary to convert
158// llvm.dbg.declare to avoid inaccurate debug info. Setting this to false
159// increases variable availability at the cost of accuracy. Variables that
160// cannot be promoted by mem2reg or SROA will be described as living in memory
161// for their entire lifetime. However, passes like DSE and instcombine can
162// delete stores to the alloca, leading to misleading and inaccurate debug
163// information. This flag can be removed when those passes are fixed.
164static cl::opt<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
165 cl::Hidden, cl::init(true));
166
167Optional<Instruction *>
168InstCombiner::targetInstCombineIntrinsic(IntrinsicInst &II) {
169 // Handle target specific intrinsics
170 if (II.getCalledFunction()->isTargetIntrinsic()) {
171 return TTI.instCombineIntrinsic(*this, II);
172 }
173 return None;
174}
175
176Optional<Value *> InstCombiner::targetSimplifyDemandedUseBitsIntrinsic(
177 IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
178 bool &KnownBitsComputed) {
179 // Handle target specific intrinsics
180 if (II.getCalledFunction()->isTargetIntrinsic()) {
181 return TTI.simplifyDemandedUseBitsIntrinsic(*this, II, DemandedMask, Known,
182 KnownBitsComputed);
183 }
184 return None;
185}
186
187Optional<Value *> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic(
188 IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts, APInt &UndefElts2,
189 APInt &UndefElts3,
190 std::function<void(Instruction *, unsigned, APInt, APInt &)>
191 SimplifyAndSetOp) {
192 // Handle target specific intrinsics
193 if (II.getCalledFunction()->isTargetIntrinsic()) {
194 return TTI.simplifyDemandedVectorEltsIntrinsic(
195 *this, II, DemandedElts, UndefElts, UndefElts2, UndefElts3,
196 SimplifyAndSetOp);
197 }
198 return None;
199}
200
201Value *InstCombinerImpl::EmitGEPOffset(User *GEP) {
202 return llvm::EmitGEPOffset(&Builder, DL, GEP);
203}
204
205/// Return true if it is desirable to convert an integer computation from a
206/// given bit width to a new bit width.
207/// We don't want to convert from a legal to an illegal type or from a smaller
208/// to a larger illegal type. A width of '1' is always treated as a legal type
209/// because i1 is a fundamental type in IR, and there are many specialized
210/// optimizations for i1 types. Widths of 8, 16 or 32 are equally treated as
211/// legal to convert to, in order to open up more combining opportunities.
212/// NOTE: this treats i8, i16 and i32 specially, due to them being so common
213/// from frontend languages.
214bool InstCombinerImpl::shouldChangeType(unsigned FromWidth,
215 unsigned ToWidth) const {
216 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
217 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
218
219 // Convert to widths of 8, 16 or 32 even if they are not legal types. Only
220 // shrink types, to prevent infinite loops.
221 if (ToWidth < FromWidth && (ToWidth == 8 || ToWidth == 16 || ToWidth == 32))
222 return true;
223
224 // If this is a legal integer from type, and the result would be an illegal
225 // type, don't do the transformation.
226 if (FromLegal && !ToLegal)
227 return false;
228
229 // Otherwise, if both are illegal, do not increase the size of the result. We
230 // do allow things like i160 -> i64, but not i64 -> i160.
231 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
232 return false;
233
234 return true;
235}
236
237/// Return true if it is desirable to convert a computation from 'From' to 'To'.
238/// We don't want to convert from a legal to an illegal type or from a smaller
239/// to a larger illegal type. i1 is always treated as a legal type because it is
240/// a fundamental type in IR, and there are many specialized optimizations for
241/// i1 types.
242bool InstCombinerImpl::shouldChangeType(Type *From, Type *To) const {
243 // TODO: This could be extended to allow vectors. Datalayout changes might be
244 // needed to properly support that.
245 if (!From->isIntegerTy() || !To->isIntegerTy())
246 return false;
247
248 unsigned FromWidth = From->getPrimitiveSizeInBits();
249 unsigned ToWidth = To->getPrimitiveSizeInBits();
250 return shouldChangeType(FromWidth, ToWidth);
251}
252
253// Return true, if No Signed Wrap should be maintained for I.
254// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
255// where both B and C should be ConstantInts, results in a constant that does
256// not overflow. This function only handles the Add and Sub opcodes. For
257// all other opcodes, the function conservatively returns false.
258static bool maintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
259 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
260 if (!OBO || !OBO->hasNoSignedWrap())
261 return false;
262
263 // We reason about Add and Sub Only.
264 Instruction::BinaryOps Opcode = I.getOpcode();
265 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
266 return false;
267
268 const APInt *BVal, *CVal;
269 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
270 return false;
271
272 bool Overflow = false;
273 if (Opcode == Instruction::Add)
274 (void)BVal->sadd_ov(*CVal, Overflow);
275 else
276 (void)BVal->ssub_ov(*CVal, Overflow);
277
278 return !Overflow;
279}
280
281static bool hasNoUnsignedWrap(BinaryOperator &I) {
282 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
283 return OBO && OBO->hasNoUnsignedWrap();
284}
285
286static bool hasNoSignedWrap(BinaryOperator &I) {
287 auto *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
288 return OBO && OBO->hasNoSignedWrap();
289}
290
291/// Conservatively clears subclassOptionalData after a reassociation or
292/// commutation. We preserve fast-math flags when applicable as they can be
293/// preserved.
294static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
295 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
296 if (!FPMO) {
297 I.clearSubclassOptionalData();
298 return;
299 }
300
301 FastMathFlags FMF = I.getFastMathFlags();
302 I.clearSubclassOptionalData();
303 I.setFastMathFlags(FMF);
304}
305
306/// Combine constant operands of associative operations either before or after a
307/// cast to eliminate one of the associative operations:
308/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
309/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
310static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1,
311 InstCombinerImpl &IC) {
312 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
313 if (!Cast || !Cast->hasOneUse())
314 return false;
315
316 // TODO: Enhance logic for other casts and remove this check.
317 auto CastOpcode = Cast->getOpcode();
318 if (CastOpcode != Instruction::ZExt)
319 return false;
320
321 // TODO: Enhance logic for other BinOps and remove this check.
322 if (!BinOp1->isBitwiseLogicOp())
323 return false;
324
325 auto AssocOpcode = BinOp1->getOpcode();
326 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
327 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
328 return false;
329
330 Constant *C1, *C2;
331 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
332 !match(BinOp2->getOperand(1), m_Constant(C2)))
333 return false;
334
335 // TODO: This assumes a zext cast.
336 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
337 // to the destination type might lose bits.
338
339 // Fold the constants together in the destination type:
340 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
341 Type *DestTy = C1->getType();
342 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
343 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
344 IC.replaceOperand(*Cast, 0, BinOp2->getOperand(0));
345 IC.replaceOperand(*BinOp1, 1, FoldedC);
346 return true;
347}
348
349// Simplifies IntToPtr/PtrToInt RoundTrip Cast To BitCast.
350// inttoptr ( ptrtoint (x) ) --> x
351Value *InstCombinerImpl::simplifyIntToPtrRoundTripCast(Value *Val) {
352 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val);
353 if (IntToPtr && DL.getPointerTypeSizeInBits(IntToPtr->getDestTy()) ==
354 DL.getTypeSizeInBits(IntToPtr->getSrcTy())) {
355 auto *PtrToInt = dyn_cast<PtrToIntInst>(IntToPtr->getOperand(0));
356 Type *CastTy = IntToPtr->getDestTy();
357 if (PtrToInt &&
358 CastTy->getPointerAddressSpace() ==
359 PtrToInt->getSrcTy()->getPointerAddressSpace() &&
360 DL.getPointerTypeSizeInBits(PtrToInt->getSrcTy()) ==
361 DL.getTypeSizeInBits(PtrToInt->getDestTy())) {
362 return CastInst::CreateBitOrPointerCast(PtrToInt->getOperand(0), CastTy,
363 "", PtrToInt);
364 }
365 }
366 return nullptr;
367}
368
369/// This performs a few simplifications for operators that are associative or
370/// commutative:
371///
372/// Commutative operators:
373///
374/// 1. Order operands such that they are listed from right (least complex) to
375/// left (most complex). This puts constants before unary operators before
376/// binary operators.
377///
378/// Associative operators:
379///
380/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
381/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
382///
383/// Associative and commutative operators:
384///
385/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
386/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
387/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
388/// if C1 and C2 are constants.
389bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
390 Instruction::BinaryOps Opcode = I.getOpcode();
391 bool Changed = false;
392
393 do {
394 // Order operands such that they are listed from right (least complex) to
395 // left (most complex). This puts constants before unary operators before
396 // binary operators.
397 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
398 getComplexity(I.getOperand(1)))
399 Changed = !I.swapOperands();
400
401 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
402 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
403
404 if (I.isAssociative()) {
405 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
406 if (Op0 && Op0->getOpcode() == Opcode) {
407 Value *A = Op0->getOperand(0);
408 Value *B = Op0->getOperand(1);
409 Value *C = I.getOperand(1);
410
411 // Does "B op C" simplify?
412 if (Value *V = SimplifyBinOp(Opcode, B, C, SQ.getWithInstruction(&I))) {
413 // It simplifies to V. Form "A op V".
414 replaceOperand(I, 0, A);
415 replaceOperand(I, 1, V);
416 bool IsNUW = hasNoUnsignedWrap(I) && hasNoUnsignedWrap(*Op0);
417 bool IsNSW = maintainNoSignedWrap(I, B, C) && hasNoSignedWrap(*Op0);
418
419 // Conservatively clear all optional flags since they may not be
420 // preserved by the reassociation. Reset nsw/nuw based on the above
421 // analysis.
422 ClearSubclassDataAfterReassociation(I);
423
424 // Note: this is only valid because SimplifyBinOp doesn't look at
425 // the operands to Op0.
426 if (IsNUW)
427 I.setHasNoUnsignedWrap(true);
428
429 if (IsNSW)
430 I.setHasNoSignedWrap(true);
431
432 Changed = true;
433 ++NumReassoc;
434 continue;
435 }
436 }
437
438 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
439 if (Op1 && Op1->getOpcode() == Opcode) {
440 Value *A = I.getOperand(0);
441 Value *B = Op1->getOperand(0);
442 Value *C = Op1->getOperand(1);
443
444 // Does "A op B" simplify?
445 if (Value *V = SimplifyBinOp(Opcode, A, B, SQ.getWithInstruction(&I))) {
446 // It simplifies to V. Form "V op C".
447 replaceOperand(I, 0, V);
448 replaceOperand(I, 1, C);
449 // Conservatively clear the optional flags, since they may not be
450 // preserved by the reassociation.
451 ClearSubclassDataAfterReassociation(I);
452 Changed = true;
453 ++NumReassoc;
454 continue;
455 }
456 }
457 }
458
459 if (I.isAssociative() && I.isCommutative()) {
460 if (simplifyAssocCastAssoc(&I, *this)) {
461 Changed = true;
462 ++NumReassoc;
463 continue;
464 }
465
466 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
467 if (Op0 && Op0->getOpcode() == Opcode) {
468 Value *A = Op0->getOperand(0);
469 Value *B = Op0->getOperand(1);
470 Value *C = I.getOperand(1);
471
472 // Does "C op A" simplify?
473 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
474 // It simplifies to V. Form "V op B".
475 replaceOperand(I, 0, V);
476 replaceOperand(I, 1, B);
477 // Conservatively clear the optional flags, since they may not be
478 // preserved by the reassociation.
479 ClearSubclassDataAfterReassociation(I);
480 Changed = true;
481 ++NumReassoc;
482 continue;
483 }
484 }
485
486 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
487 if (Op1 && Op1->getOpcode() == Opcode) {
488 Value *A = I.getOperand(0);
489 Value *B = Op1->getOperand(0);
490 Value *C = Op1->getOperand(1);
491
492 // Does "C op A" simplify?
493 if (Value *V = SimplifyBinOp(Opcode, C, A, SQ.getWithInstruction(&I))) {
494 // It simplifies to V. Form "B op V".
495 replaceOperand(I, 0, B);
496 replaceOperand(I, 1, V);
497 // Conservatively clear the optional flags, since they may not be
498 // preserved by the reassociation.
499 ClearSubclassDataAfterReassociation(I);
500 Changed = true;
501 ++NumReassoc;
502 continue;
503 }
504 }
505
506 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
507 // if C1 and C2 are constants.
508 Value *A, *B;
509 Constant *C1, *C2;
510 if (Op0 && Op1 &&
511 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
512 match(Op0, m_OneUse(m_BinOp(m_Value(A), m_Constant(C1)))) &&
513 match(Op1, m_OneUse(m_BinOp(m_Value(B), m_Constant(C2))))) {
514 bool IsNUW = hasNoUnsignedWrap(I) &&
515 hasNoUnsignedWrap(*Op0) &&
516 hasNoUnsignedWrap(*Op1);
517 BinaryOperator *NewBO = (IsNUW && Opcode == Instruction::Add) ?
518 BinaryOperator::CreateNUW(Opcode, A, B) :
519 BinaryOperator::Create(Opcode, A, B);
520
521 if (isa<FPMathOperator>(NewBO)) {
522 FastMathFlags Flags = I.getFastMathFlags();
523 Flags &= Op0->getFastMathFlags();
524 Flags &= Op1->getFastMathFlags();
525 NewBO->setFastMathFlags(Flags);
526 }
527 InsertNewInstWith(NewBO, I);
528 NewBO->takeName(Op1);
529 replaceOperand(I, 0, NewBO);
530 replaceOperand(I, 1, ConstantExpr::get(Opcode, C1, C2));
531 // Conservatively clear the optional flags, since they may not be
532 // preserved by the reassociation.
533 ClearSubclassDataAfterReassociation(I);
534 if (IsNUW)
535 I.setHasNoUnsignedWrap(true);
536
537 Changed = true;
538 continue;
539 }
540 }
541
542 // No further simplifications.
543 return Changed;
544 } while (true);
545}
546
547/// Return whether "X LOp (Y ROp Z)" is always equal to
548/// "(X LOp Y) ROp (X LOp Z)".
549static bool leftDistributesOverRight(Instruction::BinaryOps LOp,
550 Instruction::BinaryOps ROp) {
551 // X & (Y | Z) <--> (X & Y) | (X & Z)
552 // X & (Y ^ Z) <--> (X & Y) ^ (X & Z)
553 if (LOp == Instruction::And)
554 return ROp == Instruction::Or || ROp == Instruction::Xor;
555
556 // X | (Y & Z) <--> (X | Y) & (X | Z)
557 if (LOp == Instruction::Or)
558 return ROp == Instruction::And;
559
560 // X * (Y + Z) <--> (X * Y) + (X * Z)
561 // X * (Y - Z) <--> (X * Y) - (X * Z)
562 if (LOp == Instruction::Mul)
563 return ROp == Instruction::Add || ROp == Instruction::Sub;
564
565 return false;
566}
567
568/// Return whether "(X LOp Y) ROp Z" is always equal to
569/// "(X ROp Z) LOp (Y ROp Z)".
570static bool rightDistributesOverLeft(Instruction::BinaryOps LOp,
571 Instruction::BinaryOps ROp) {
572 if (Instruction::isCommutative(ROp))
573 return leftDistributesOverRight(ROp, LOp);
574
575 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
576 return Instruction::isBitwiseLogicOp(LOp) && Instruction::isShift(ROp);
577
578 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
579 // but this requires knowing that the addition does not overflow and other
580 // such subtleties.
581}
582
583/// This function returns identity value for given opcode, which can be used to
584/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
585static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
586 if (isa<Constant>(V))
587 return nullptr;
588
589 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
590}
591
592/// This function predicates factorization using distributive laws. By default,
593/// it just returns the 'Op' inputs. But for special-cases like
594/// 'add(shl(X, 5), ...)', this function will have TopOpcode == Instruction::Add
595/// and Op = shl(X, 5). The 'shl' is treated as the more general 'mul X, 32' to
596/// allow more factorization opportunities.
597static Instruction::BinaryOps
598getBinOpsForFactorization(Instruction::BinaryOps TopOpcode, BinaryOperator *Op,
599 Value *&LHS, Value *&RHS) {
600 assert(Op && "Expected a binary operator")(static_cast <bool> (Op && "Expected a binary operator"
) ? void (0) : __assert_fail ("Op && \"Expected a binary operator\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 600, __extension__ __PRETTY_FUNCTION__))
;
601 LHS = Op->getOperand(0);
602 RHS = Op->getOperand(1);
603 if (TopOpcode == Instruction::Add || TopOpcode == Instruction::Sub) {
604 Constant *C;
605 if (match(Op, m_Shl(m_Value(), m_Constant(C)))) {
606 // X << C --> X * (1 << C)
607 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), C);
608 return Instruction::Mul;
609 }
610 // TODO: We can add other conversions e.g. shr => div etc.
611 }
612 return Op->getOpcode();
613}
614
615/// This tries to simplify binary operations by factorizing out common terms
616/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
617Value *InstCombinerImpl::tryFactorization(BinaryOperator &I,
618 Instruction::BinaryOps InnerOpcode,
619 Value *A, Value *B, Value *C,
620 Value *D) {
621 assert(A && B && C && D && "All values must be provided")(static_cast <bool> (A && B && C &&
D && "All values must be provided") ? void (0) : __assert_fail
("A && B && C && D && \"All values must be provided\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 621, __extension__ __PRETTY_FUNCTION__))
;
622
623 Value *V = nullptr;
624 Value *SimplifiedInst = nullptr;
625 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
626 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
627
628 // Does "X op' Y" always equal "Y op' X"?
629 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
630
631 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
632 if (leftDistributesOverRight(InnerOpcode, TopLevelOpcode))
633 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
634 // commutative case, "(A op' B) op (C op' A)"?
635 if (A == C || (InnerCommutative && A == D)) {
636 if (A != C)
637 std::swap(C, D);
638 // Consider forming "A op' (B op D)".
639 // If "B op D" simplifies then it can be formed with no cost.
640 V = SimplifyBinOp(TopLevelOpcode, B, D, SQ.getWithInstruction(&I));
641 // If "B op D" doesn't simplify then only go on if both of the existing
642 // operations "A op' B" and "C op' D" will be zapped as no longer used.
643 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
644 V = Builder.CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
645 if (V) {
646 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, A, V);
647 }
648 }
649
650 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
651 if (!SimplifiedInst && rightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
652 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
653 // commutative case, "(A op' B) op (B op' D)"?
654 if (B == D || (InnerCommutative && B == C)) {
655 if (B != D)
656 std::swap(C, D);
657 // Consider forming "(A op C) op' B".
658 // If "A op C" simplifies then it can be formed with no cost.
659 V = SimplifyBinOp(TopLevelOpcode, A, C, SQ.getWithInstruction(&I));
660
661 // If "A op C" doesn't simplify then only go on if both of the existing
662 // operations "A op' B" and "C op' D" will be zapped as no longer used.
663 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
664 V = Builder.CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
665 if (V) {
666 SimplifiedInst = Builder.CreateBinOp(InnerOpcode, V, B);
667 }
668 }
669
670 if (SimplifiedInst) {
671 ++NumFactor;
672 SimplifiedInst->takeName(&I);
673
674 // Check if we can add NSW/NUW flags to SimplifiedInst. If so, set them.
675 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
676 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
677 bool HasNSW = false;
678 bool HasNUW = false;
679 if (isa<OverflowingBinaryOperator>(&I)) {
680 HasNSW = I.hasNoSignedWrap();
681 HasNUW = I.hasNoUnsignedWrap();
682 }
683
684 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS)) {
685 HasNSW &= LOBO->hasNoSignedWrap();
686 HasNUW &= LOBO->hasNoUnsignedWrap();
687 }
688
689 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS)) {
690 HasNSW &= ROBO->hasNoSignedWrap();
691 HasNUW &= ROBO->hasNoUnsignedWrap();
692 }
693
694 if (TopLevelOpcode == Instruction::Add &&
695 InnerOpcode == Instruction::Mul) {
696 // We can propagate 'nsw' if we know that
697 // %Y = mul nsw i16 %X, C
698 // %Z = add nsw i16 %Y, %X
699 // =>
700 // %Z = mul nsw i16 %X, C+1
701 //
702 // iff C+1 isn't INT_MIN
703 const APInt *CInt;
704 if (match(V, m_APInt(CInt))) {
705 if (!CInt->isMinSignedValue())
706 BO->setHasNoSignedWrap(HasNSW);
707 }
708
709 // nuw can be propagated with any constant or nuw value.
710 BO->setHasNoUnsignedWrap(HasNUW);
711 }
712 }
713 }
714 }
715 return SimplifiedInst;
716}
717
718/// This tries to simplify binary operations which some other binary operation
719/// distributes over either by factorizing out common terms
720/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
721/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
722/// Returns the simplified value, or null if it didn't simplify.
723Value *InstCombinerImpl::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
724 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
725 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
726 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
727 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
728
729 {
730 // Factorization.
731 Value *A, *B, *C, *D;
732 Instruction::BinaryOps LHSOpcode, RHSOpcode;
733 if (Op0)
734 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
735 if (Op1)
736 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
737
738 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
739 // a common term.
740 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
741 if (Value *V = tryFactorization(I, LHSOpcode, A, B, C, D))
742 return V;
743
744 // The instruction has the form "(A op' B) op (C)". Try to factorize common
745 // term.
746 if (Op0)
747 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
748 if (Value *V = tryFactorization(I, LHSOpcode, A, B, RHS, Ident))
749 return V;
750
751 // The instruction has the form "(B) op (C op' D)". Try to factorize common
752 // term.
753 if (Op1)
754 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
755 if (Value *V = tryFactorization(I, RHSOpcode, LHS, Ident, C, D))
756 return V;
757 }
758
759 // Expansion.
760 if (Op0 && rightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
761 // The instruction has the form "(A op' B) op C". See if expanding it out
762 // to "(A op C) op' (B op C)" results in simplifications.
763 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
764 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
765
766 // Disable the use of undef because it's not safe to distribute undef.
767 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
768 Value *L = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
769 Value *R = SimplifyBinOp(TopLevelOpcode, B, C, SQDistributive);
770
771 // Do "A op C" and "B op C" both simplify?
772 if (L && R) {
773 // They do! Return "L op' R".
774 ++NumExpand;
775 C = Builder.CreateBinOp(InnerOpcode, L, R);
776 C->takeName(&I);
777 return C;
778 }
779
780 // Does "A op C" simplify to the identity value for the inner opcode?
781 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
782 // They do! Return "B op C".
783 ++NumExpand;
784 C = Builder.CreateBinOp(TopLevelOpcode, B, C);
785 C->takeName(&I);
786 return C;
787 }
788
789 // Does "B op C" simplify to the identity value for the inner opcode?
790 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
791 // They do! Return "A op C".
792 ++NumExpand;
793 C = Builder.CreateBinOp(TopLevelOpcode, A, C);
794 C->takeName(&I);
795 return C;
796 }
797 }
798
799 if (Op1 && leftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
800 // The instruction has the form "A op (B op' C)". See if expanding it out
801 // to "(A op B) op' (A op C)" results in simplifications.
802 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
803 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
804
805 // Disable the use of undef because it's not safe to distribute undef.
806 auto SQDistributive = SQ.getWithInstruction(&I).getWithoutUndef();
807 Value *L = SimplifyBinOp(TopLevelOpcode, A, B, SQDistributive);
808 Value *R = SimplifyBinOp(TopLevelOpcode, A, C, SQDistributive);
809
810 // Do "A op B" and "A op C" both simplify?
811 if (L && R) {
812 // They do! Return "L op' R".
813 ++NumExpand;
814 A = Builder.CreateBinOp(InnerOpcode, L, R);
815 A->takeName(&I);
816 return A;
817 }
818
819 // Does "A op B" simplify to the identity value for the inner opcode?
820 if (L && L == ConstantExpr::getBinOpIdentity(InnerOpcode, L->getType())) {
821 // They do! Return "A op C".
822 ++NumExpand;
823 A = Builder.CreateBinOp(TopLevelOpcode, A, C);
824 A->takeName(&I);
825 return A;
826 }
827
828 // Does "A op C" simplify to the identity value for the inner opcode?
829 if (R && R == ConstantExpr::getBinOpIdentity(InnerOpcode, R->getType())) {
830 // They do! Return "A op B".
831 ++NumExpand;
832 A = Builder.CreateBinOp(TopLevelOpcode, A, B);
833 A->takeName(&I);
834 return A;
835 }
836 }
837
838 return SimplifySelectsFeedingBinaryOp(I, LHS, RHS);
839}
840
841Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
842 Value *LHS,
843 Value *RHS) {
844 Value *A, *B, *C, *D, *E, *F;
845 bool LHSIsSelect = match(LHS, m_Select(m_Value(A), m_Value(B), m_Value(C)));
846 bool RHSIsSelect = match(RHS, m_Select(m_Value(D), m_Value(E), m_Value(F)));
847 if (!LHSIsSelect && !RHSIsSelect)
848 return nullptr;
849
850 FastMathFlags FMF;
851 BuilderTy::FastMathFlagGuard Guard(Builder);
852 if (isa<FPMathOperator>(&I)) {
853 FMF = I.getFastMathFlags();
854 Builder.setFastMathFlags(FMF);
855 }
856
857 Instruction::BinaryOps Opcode = I.getOpcode();
858 SimplifyQuery Q = SQ.getWithInstruction(&I);
859
860 Value *Cond, *True = nullptr, *False = nullptr;
861 if (LHSIsSelect && RHSIsSelect && A == D) {
862 // (A ? B : C) op (A ? E : F) -> A ? (B op E) : (C op F)
863 Cond = A;
864 True = SimplifyBinOp(Opcode, B, E, FMF, Q);
865 False = SimplifyBinOp(Opcode, C, F, FMF, Q);
866
867 if (LHS->hasOneUse() && RHS->hasOneUse()) {
868 if (False && !True)
869 True = Builder.CreateBinOp(Opcode, B, E);
870 else if (True && !False)
871 False = Builder.CreateBinOp(Opcode, C, F);
872 }
873 } else if (LHSIsSelect && LHS->hasOneUse()) {
874 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
875 Cond = A;
876 True = SimplifyBinOp(Opcode, B, RHS, FMF, Q);
877 False = SimplifyBinOp(Opcode, C, RHS, FMF, Q);
878 } else if (RHSIsSelect && RHS->hasOneUse()) {
879 // X op (D ? E : F) -> D ? (X op E) : (X op F)
880 Cond = D;
881 True = SimplifyBinOp(Opcode, LHS, E, FMF, Q);
882 False = SimplifyBinOp(Opcode, LHS, F, FMF, Q);
883 }
884
885 if (!True || !False)
886 return nullptr;
887
888 Value *SI = Builder.CreateSelect(Cond, True, False);
889 SI->takeName(&I);
890 return SI;
891}
892
893/// Freely adapt every user of V as-if V was changed to !V.
894/// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
895void InstCombinerImpl::freelyInvertAllUsersOf(Value *I) {
896 for (User *U : I->users()) {
897 switch (cast<Instruction>(U)->getOpcode()) {
898 case Instruction::Select: {
899 auto *SI = cast<SelectInst>(U);
900 SI->swapValues();
901 SI->swapProfMetadata();
902 break;
903 }
904 case Instruction::Br:
905 cast<BranchInst>(U)->swapSuccessors(); // swaps prof metadata too
906 break;
907 case Instruction::Xor:
908 replaceInstUsesWith(cast<Instruction>(*U), I);
909 break;
910 default:
911 llvm_unreachable("Got unexpected user - out of sync with "::llvm::llvm_unreachable_internal("Got unexpected user - out of sync with "
"canFreelyInvertAllUsersOf() ?", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 912)
912 "canFreelyInvertAllUsersOf() ?")::llvm::llvm_unreachable_internal("Got unexpected user - out of sync with "
"canFreelyInvertAllUsersOf() ?", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 912)
;
913 }
914 }
915}
916
917/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
918/// constant zero (which is the 'negate' form).
919Value *InstCombinerImpl::dyn_castNegVal(Value *V) const {
920 Value *NegV;
921 if (match(V, m_Neg(m_Value(NegV))))
922 return NegV;
923
924 // Constants can be considered to be negated values if they can be folded.
925 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
926 return ConstantExpr::getNeg(C);
927
928 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
929 if (C->getType()->getElementType()->isIntegerTy())
930 return ConstantExpr::getNeg(C);
931
932 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
933 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
934 Constant *Elt = CV->getAggregateElement(i);
935 if (!Elt)
936 return nullptr;
937
938 if (isa<UndefValue>(Elt))
939 continue;
940
941 if (!isa<ConstantInt>(Elt))
942 return nullptr;
943 }
944 return ConstantExpr::getNeg(CV);
945 }
946
947 // Negate integer vector splats.
948 if (auto *CV = dyn_cast<Constant>(V))
949 if (CV->getType()->isVectorTy() &&
950 CV->getType()->getScalarType()->isIntegerTy() && CV->getSplatValue())
951 return ConstantExpr::getNeg(CV);
952
953 return nullptr;
954}
955
956static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
957 InstCombiner::BuilderTy &Builder) {
958 if (auto *Cast = dyn_cast<CastInst>(&I))
959 return Builder.CreateCast(Cast->getOpcode(), SO, I.getType());
960
961 if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
962 assert(canConstantFoldCallTo(II, cast<Function>(II->getCalledOperand())) &&(static_cast <bool> (canConstantFoldCallTo(II, cast<
Function>(II->getCalledOperand())) && "Expected constant-foldable intrinsic"
) ? void (0) : __assert_fail ("canConstantFoldCallTo(II, cast<Function>(II->getCalledOperand())) && \"Expected constant-foldable intrinsic\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
963 "Expected constant-foldable intrinsic")(static_cast <bool> (canConstantFoldCallTo(II, cast<
Function>(II->getCalledOperand())) && "Expected constant-foldable intrinsic"
) ? void (0) : __assert_fail ("canConstantFoldCallTo(II, cast<Function>(II->getCalledOperand())) && \"Expected constant-foldable intrinsic\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 963, __extension__ __PRETTY_FUNCTION__))
;
964 Intrinsic::ID IID = II->getIntrinsicID();
965 if (II->getNumArgOperands() == 1)
966 return Builder.CreateUnaryIntrinsic(IID, SO);
967
968 // This works for real binary ops like min/max (where we always expect the
969 // constant operand to be canonicalized as op1) and unary ops with a bonus
970 // constant argument like ctlz/cttz.
971 // TODO: Handle non-commutative binary intrinsics as below for binops.
972 assert(II->getNumArgOperands() == 2 && "Expected binary intrinsic")(static_cast <bool> (II->getNumArgOperands() == 2 &&
"Expected binary intrinsic") ? void (0) : __assert_fail ("II->getNumArgOperands() == 2 && \"Expected binary intrinsic\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 972, __extension__ __PRETTY_FUNCTION__))
;
973 assert(isa<Constant>(II->getArgOperand(1)) && "Expected constant operand")(static_cast <bool> (isa<Constant>(II->getArgOperand
(1)) && "Expected constant operand") ? void (0) : __assert_fail
("isa<Constant>(II->getArgOperand(1)) && \"Expected constant operand\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 973, __extension__ __PRETTY_FUNCTION__))
;
974 return Builder.CreateBinaryIntrinsic(IID, SO, II->getArgOperand(1));
975 }
976
977 assert(I.isBinaryOp() && "Unexpected opcode for select folding")(static_cast <bool> (I.isBinaryOp() && "Unexpected opcode for select folding"
) ? void (0) : __assert_fail ("I.isBinaryOp() && \"Unexpected opcode for select folding\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 977, __extension__ __PRETTY_FUNCTION__))
;
978
979 // Figure out if the constant is the left or the right argument.
980 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
981 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
982
983 if (auto *SOC = dyn_cast<Constant>(SO)) {
984 if (ConstIsRHS)
985 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
986 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
987 }
988
989 Value *Op0 = SO, *Op1 = ConstOperand;
990 if (!ConstIsRHS)
991 std::swap(Op0, Op1);
992
993 auto *BO = cast<BinaryOperator>(&I);
994 Value *RI = Builder.CreateBinOp(BO->getOpcode(), Op0, Op1,
995 SO->getName() + ".op");
996 auto *FPInst = dyn_cast<Instruction>(RI);
997 if (FPInst && isa<FPMathOperator>(FPInst))
998 FPInst->copyFastMathFlags(BO);
999 return RI;
1000}
1001
1002Instruction *InstCombinerImpl::FoldOpIntoSelect(Instruction &Op,
1003 SelectInst *SI) {
1004 // Don't modify shared select instructions.
1005 if (!SI->hasOneUse())
1006 return nullptr;
1007
1008 Value *TV = SI->getTrueValue();
1009 Value *FV = SI->getFalseValue();
1010 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
1011 return nullptr;
1012
1013 // Bool selects with constant operands can be folded to logical ops.
1014 if (SI->getType()->isIntOrIntVectorTy(1))
1015 return nullptr;
1016
1017 // If it's a bitcast involving vectors, make sure it has the same number of
1018 // elements on both sides.
1019 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
1020 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
1021 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
1022
1023 // Verify that either both or neither are vectors.
1024 if ((SrcTy == nullptr) != (DestTy == nullptr))
1025 return nullptr;
1026
1027 // If vectors, verify that they have the same number of elements.
1028 if (SrcTy && SrcTy->getElementCount() != DestTy->getElementCount())
1029 return nullptr;
1030 }
1031
1032 // Test if a CmpInst instruction is used exclusively by a select as
1033 // part of a minimum or maximum operation. If so, refrain from doing
1034 // any other folding. This helps out other analyses which understand
1035 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
1036 // and CodeGen. And in this case, at least one of the comparison
1037 // operands has at least one user besides the compare (the select),
1038 // which would often largely negate the benefit of folding anyway.
1039 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
1040 if (CI->hasOneUse()) {
1041 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
1042
1043 // FIXME: This is a hack to avoid infinite looping with min/max patterns.
1044 // We have to ensure that vector constants that only differ with
1045 // undef elements are treated as equivalent.
1046 auto areLooselyEqual = [](Value *A, Value *B) {
1047 if (A == B)
1048 return true;
1049
1050 // Test for vector constants.
1051 Constant *ConstA, *ConstB;
1052 if (!match(A, m_Constant(ConstA)) || !match(B, m_Constant(ConstB)))
1053 return false;
1054
1055 // TODO: Deal with FP constants?
1056 if (!A->getType()->isIntOrIntVectorTy() || A->getType() != B->getType())
1057 return false;
1058
1059 // Compare for equality including undefs as equal.
1060 auto *Cmp = ConstantExpr::getCompare(ICmpInst::ICMP_EQ, ConstA, ConstB);
1061 const APInt *C;
1062 return match(Cmp, m_APIntAllowUndef(C)) && C->isOneValue();
1063 };
1064
1065 if ((areLooselyEqual(TV, Op0) && areLooselyEqual(FV, Op1)) ||
1066 (areLooselyEqual(FV, Op0) && areLooselyEqual(TV, Op1)))
1067 return nullptr;
1068 }
1069 }
1070
1071 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, Builder);
1072 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, Builder);
1073 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
1074}
1075
1076static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
1077 InstCombiner::BuilderTy &Builder) {
1078 bool ConstIsRHS = isa<Constant>(I->getOperand(1));
1079 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
1080
1081 if (auto *InC = dyn_cast<Constant>(InV)) {
1082 if (ConstIsRHS)
1083 return ConstantExpr::get(I->getOpcode(), InC, C);
1084 return ConstantExpr::get(I->getOpcode(), C, InC);
1085 }
1086
1087 Value *Op0 = InV, *Op1 = C;
1088 if (!ConstIsRHS)
1089 std::swap(Op0, Op1);
1090
1091 Value *RI = Builder.CreateBinOp(I->getOpcode(), Op0, Op1, "phi.bo");
1092 auto *FPInst = dyn_cast<Instruction>(RI);
1093 if (FPInst && isa<FPMathOperator>(FPInst))
1094 FPInst->copyFastMathFlags(I);
1095 return RI;
1096}
1097
1098Instruction *InstCombinerImpl::foldOpIntoPhi(Instruction &I, PHINode *PN) {
1099 unsigned NumPHIValues = PN->getNumIncomingValues();
1100 if (NumPHIValues == 0)
1101 return nullptr;
1102
1103 // We normally only transform phis with a single use. However, if a PHI has
1104 // multiple uses and they are all the same operation, we can fold *all* of the
1105 // uses into the PHI.
1106 if (!PN->hasOneUse()) {
1107 // Walk the use list for the instruction, comparing them to I.
1108 for (User *U : PN->users()) {
1109 Instruction *UI = cast<Instruction>(U);
1110 if (UI != &I && !I.isIdenticalTo(UI))
1111 return nullptr;
1112 }
1113 // Otherwise, we can replace *all* users with the new PHI we form.
1114 }
1115
1116 // Check to see if all of the operands of the PHI are simple constants
1117 // (constantint/constantfp/undef). If there is one non-constant value,
1118 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1119 // bail out. We don't do arbitrary constant expressions here because moving
1120 // their computation can be expensive without a cost model.
1121 BasicBlock *NonConstBB = nullptr;
1122 for (unsigned i = 0; i != NumPHIValues; ++i) {
1123 Value *InVal = PN->getIncomingValue(i);
1124 // If I is a freeze instruction, count undef as a non-constant.
1125 if (match(InVal, m_ImmConstant()) &&
1126 (!isa<FreezeInst>(I) || isGuaranteedNotToBeUndefOrPoison(InVal)))
1127 continue;
1128
1129 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
1130 if (NonConstBB) return nullptr; // More than one non-const value.
1131
1132 NonConstBB = PN->getIncomingBlock(i);
1133
1134 // If the InVal is an invoke at the end of the pred block, then we can't
1135 // insert a computation after it without breaking the edge.
1136 if (isa<InvokeInst>(InVal))
1137 if (cast<Instruction>(InVal)->getParent() == NonConstBB)
1138 return nullptr;
1139
1140 // If the incoming non-constant value is in I's block, we will remove one
1141 // instruction, but insert another equivalent one, leading to infinite
1142 // instcombine.
1143 if (isPotentiallyReachable(I.getParent(), NonConstBB, nullptr, &DT, LI))
1144 return nullptr;
1145 }
1146
1147 // If there is exactly one non-constant value, we can insert a copy of the
1148 // operation in that block. However, if this is a critical edge, we would be
1149 // inserting the computation on some other paths (e.g. inside a loop). Only
1150 // do this if the pred block is unconditionally branching into the phi block.
1151 // Also, make sure that the pred block is not dead code.
1152 if (NonConstBB != nullptr) {
1153 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1154 if (!BI || !BI->isUnconditional() || !DT.isReachableFromEntry(NonConstBB))
1155 return nullptr;
1156 }
1157
1158 // Okay, we can do the transformation: create the new PHI node.
1159 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
1160 InsertNewInstBefore(NewPN, *PN);
1161 NewPN->takeName(PN);
1162
1163 // If we are going to have to insert a new computation, do so right before the
1164 // predecessor's terminator.
1165 if (NonConstBB)
1166 Builder.SetInsertPoint(NonConstBB->getTerminator());
1167
1168 // Next, add all of the operands to the PHI.
1169 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1170 // We only currently try to fold the condition of a select when it is a phi,
1171 // not the true/false values.
1172 Value *TrueV = SI->getTrueValue();
1173 Value *FalseV = SI->getFalseValue();
1174 BasicBlock *PhiTransBB = PN->getParent();
1175 for (unsigned i = 0; i != NumPHIValues; ++i) {
1176 BasicBlock *ThisBB = PN->getIncomingBlock(i);
1177 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
1178 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
1179 Value *InV = nullptr;
1180 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
1181 // even if currently isNullValue gives false.
1182 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
1183 // For vector constants, we cannot use isNullValue to fold into
1184 // FalseVInPred versus TrueVInPred. When we have individual nonzero
1185 // elements in the vector, we will incorrectly fold InC to
1186 // `TrueVInPred`.
1187 if (InC && isa<ConstantInt>(InC))
1188 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
1189 else {
1190 // Generate the select in the same block as PN's current incoming block.
1191 // Note: ThisBB need not be the NonConstBB because vector constants
1192 // which are constants by definition are handled here.
1193 // FIXME: This can lead to an increase in IR generation because we might
1194 // generate selects for vector constant phi operand, that could not be
1195 // folded to TrueVInPred or FalseVInPred as done for ConstantInt. For
1196 // non-vector phis, this transformation was always profitable because
1197 // the select would be generated exactly once in the NonConstBB.
1198 Builder.SetInsertPoint(ThisBB->getTerminator());
1199 InV = Builder.CreateSelect(PN->getIncomingValue(i), TrueVInPred,
1200 FalseVInPred, "phi.sel");
1201 }
1202 NewPN->addIncoming(InV, ThisBB);
1203 }
1204 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
1205 Constant *C = cast<Constant>(I.getOperand(1));
1206 for (unsigned i = 0; i != NumPHIValues; ++i) {
1207 Value *InV = nullptr;
1208 if (auto *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1209 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1210 else
1211 InV = Builder.CreateCmp(CI->getPredicate(), PN->getIncomingValue(i),
1212 C, "phi.cmp");
1213 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1214 }
1215 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
1216 for (unsigned i = 0; i != NumPHIValues; ++i) {
1217 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i),
1218 Builder);
1219 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1220 }
1221 } else if (isa<FreezeInst>(&I)) {
1222 for (unsigned i = 0; i != NumPHIValues; ++i) {
1223 Value *InV;
1224 if (NonConstBB == PN->getIncomingBlock(i))
1225 InV = Builder.CreateFreeze(PN->getIncomingValue(i), "phi.fr");
1226 else
1227 InV = PN->getIncomingValue(i);
1228 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1229 }
1230 } else {
1231 CastInst *CI = cast<CastInst>(&I);
1232 Type *RetTy = CI->getType();
1233 for (unsigned i = 0; i != NumPHIValues; ++i) {
1234 Value *InV;
1235 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
1236 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1237 else
1238 InV = Builder.CreateCast(CI->getOpcode(), PN->getIncomingValue(i),
1239 I.getType(), "phi.cast");
1240 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1241 }
1242 }
1243
1244 for (User *U : make_early_inc_range(PN->users())) {
1245 Instruction *User = cast<Instruction>(U);
1246 if (User == &I) continue;
1247 replaceInstUsesWith(*User, NewPN);
1248 eraseInstFromFunction(*User);
1249 }
1250 return replaceInstUsesWith(I, NewPN);
1251}
1252
1253Instruction *InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator &I) {
1254 if (!isa<Constant>(I.getOperand(1)))
1255 return nullptr;
1256
1257 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1258 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1259 return NewSel;
1260 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1261 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1262 return NewPhi;
1263 }
1264 return nullptr;
1265}
1266
1267/// Given a pointer type and a constant offset, determine whether or not there
1268/// is a sequence of GEP indices into the pointed type that will land us at the
1269/// specified offset. If so, fill them into NewIndices and return the resultant
1270/// element type, otherwise return null.
1271Type *
1272InstCombinerImpl::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1273 SmallVectorImpl<Value *> &NewIndices) {
1274 Type *Ty = PtrTy->getElementType();
1275 if (!Ty->isSized())
1276 return nullptr;
1277
1278 // Start with the index over the outer type. Note that the type size
1279 // might be zero (even if the offset isn't zero) if the indexed type
1280 // is something like [0 x {int, int}]
1281 Type *IndexTy = DL.getIndexType(PtrTy);
1282 int64_t FirstIdx = 0;
1283 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1284 FirstIdx = Offset/TySize;
1285 Offset -= FirstIdx*TySize;
1286
1287 // Handle hosts where % returns negative instead of values [0..TySize).
1288 if (Offset < 0) {
1289 --FirstIdx;
1290 Offset += TySize;
1291 assert(Offset >= 0)(static_cast <bool> (Offset >= 0) ? void (0) : __assert_fail
("Offset >= 0", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1291, __extension__ __PRETTY_FUNCTION__))
;
1292 }
1293 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset")(static_cast <bool> ((uint64_t)Offset < (uint64_t)TySize
&& "Out of range offset") ? void (0) : __assert_fail
("(uint64_t)Offset < (uint64_t)TySize && \"Out of range offset\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1293, __extension__ __PRETTY_FUNCTION__))
;
1294 }
1295
1296 NewIndices.push_back(ConstantInt::get(IndexTy, FirstIdx));
1297
1298 // Index into the types. If we fail, set OrigBase to null.
1299 while (Offset) {
1300 // Indexing into tail padding between struct/array elements.
1301 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1302 return nullptr;
1303
1304 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1305 const StructLayout *SL = DL.getStructLayout(STy);
1306 assert(Offset < (int64_t)SL->getSizeInBytes() &&(static_cast <bool> (Offset < (int64_t)SL->getSizeInBytes
() && "Offset must stay within the indexed type") ? void
(0) : __assert_fail ("Offset < (int64_t)SL->getSizeInBytes() && \"Offset must stay within the indexed type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1307, __extension__ __PRETTY_FUNCTION__))
1307 "Offset must stay within the indexed type")(static_cast <bool> (Offset < (int64_t)SL->getSizeInBytes
() && "Offset must stay within the indexed type") ? void
(0) : __assert_fail ("Offset < (int64_t)SL->getSizeInBytes() && \"Offset must stay within the indexed type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1307, __extension__ __PRETTY_FUNCTION__))
;
1308
1309 unsigned Elt = SL->getElementContainingOffset(Offset);
1310 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1311 Elt));
1312
1313 Offset -= SL->getElementOffset(Elt);
1314 Ty = STy->getElementType(Elt);
1315 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1316 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1317 assert(EltSize && "Cannot index into a zero-sized array")(static_cast <bool> (EltSize && "Cannot index into a zero-sized array"
) ? void (0) : __assert_fail ("EltSize && \"Cannot index into a zero-sized array\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1317, __extension__ __PRETTY_FUNCTION__))
;
1318 NewIndices.push_back(ConstantInt::get(IndexTy,Offset/EltSize));
1319 Offset %= EltSize;
1320 Ty = AT->getElementType();
1321 } else {
1322 // Otherwise, we can't index into the middle of this atomic type, bail.
1323 return nullptr;
1324 }
1325 }
1326
1327 return Ty;
1328}
1329
1330static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1331 // If this GEP has only 0 indices, it is the same pointer as
1332 // Src. If Src is not a trivial GEP too, don't combine
1333 // the indices.
1334 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1335 !Src.hasOneUse())
1336 return false;
1337 return true;
1338}
1339
1340/// Return a value X such that Val = X * Scale, or null if none.
1341/// If the multiplication is known not to overflow, then NoSignedWrap is set.
1342Value *InstCombinerImpl::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1343 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!")(static_cast <bool> (isa<IntegerType>(Val->getType
()) && "Can only descale integers!") ? void (0) : __assert_fail
("isa<IntegerType>(Val->getType()) && \"Can only descale integers!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1343, __extension__ __PRETTY_FUNCTION__))
;
1344 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==(static_cast <bool> (cast<IntegerType>(Val->getType
())->getBitWidth() == Scale.getBitWidth() && "Scale not compatible with value!"
) ? void (0) : __assert_fail ("cast<IntegerType>(Val->getType())->getBitWidth() == Scale.getBitWidth() && \"Scale not compatible with value!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1345, __extension__ __PRETTY_FUNCTION__))
1345 Scale.getBitWidth() && "Scale not compatible with value!")(static_cast <bool> (cast<IntegerType>(Val->getType
())->getBitWidth() == Scale.getBitWidth() && "Scale not compatible with value!"
) ? void (0) : __assert_fail ("cast<IntegerType>(Val->getType())->getBitWidth() == Scale.getBitWidth() && \"Scale not compatible with value!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1345, __extension__ __PRETTY_FUNCTION__))
;
1346
1347 // If Val is zero or Scale is one then Val = Val * Scale.
1348 if (match(Val, m_Zero()) || Scale == 1) {
1349 NoSignedWrap = true;
1350 return Val;
1351 }
1352
1353 // If Scale is zero then it does not divide Val.
1354 if (Scale.isMinValue())
1355 return nullptr;
1356
1357 // Look through chains of multiplications, searching for a constant that is
1358 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1359 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1360 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1361 // down from Val:
1362 //
1363 // Val = M1 * X || Analysis starts here and works down
1364 // M1 = M2 * Y || Doesn't descend into terms with more
1365 // M2 = Z * 4 \/ than one use
1366 //
1367 // Then to modify a term at the bottom:
1368 //
1369 // Val = M1 * X
1370 // M1 = Z * Y || Replaced M2 with Z
1371 //
1372 // Then to work back up correcting nsw flags.
1373
1374 // Op - the term we are currently analyzing. Starts at Val then drills down.
1375 // Replaced with its descaled value before exiting from the drill down loop.
1376 Value *Op = Val;
1377
1378 // Parent - initially null, but after drilling down notes where Op came from.
1379 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1380 // 0'th operand of Val.
1381 std::pair<Instruction *, unsigned> Parent;
1382
1383 // Set if the transform requires a descaling at deeper levels that doesn't
1384 // overflow.
1385 bool RequireNoSignedWrap = false;
1386
1387 // Log base 2 of the scale. Negative if not a power of 2.
1388 int32_t logScale = Scale.exactLogBase2();
1389
1390 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1391 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1392 // If Op is a constant divisible by Scale then descale to the quotient.
1393 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1394 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1395 if (!Remainder.isMinValue())
1396 // Not divisible by Scale.
1397 return nullptr;
1398 // Replace with the quotient in the parent.
1399 Op = ConstantInt::get(CI->getType(), Quotient);
1400 NoSignedWrap = true;
1401 break;
1402 }
1403
1404 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1405 if (BO->getOpcode() == Instruction::Mul) {
1406 // Multiplication.
1407 NoSignedWrap = BO->hasNoSignedWrap();
1408 if (RequireNoSignedWrap && !NoSignedWrap)
1409 return nullptr;
1410
1411 // There are three cases for multiplication: multiplication by exactly
1412 // the scale, multiplication by a constant different to the scale, and
1413 // multiplication by something else.
1414 Value *LHS = BO->getOperand(0);
1415 Value *RHS = BO->getOperand(1);
1416
1417 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1418 // Multiplication by a constant.
1419 if (CI->getValue() == Scale) {
1420 // Multiplication by exactly the scale, replace the multiplication
1421 // by its left-hand side in the parent.
1422 Op = LHS;
1423 break;
1424 }
1425
1426 // Otherwise drill down into the constant.
1427 if (!Op->hasOneUse())
1428 return nullptr;
1429
1430 Parent = std::make_pair(BO, 1);
1431 continue;
1432 }
1433
1434 // Multiplication by something else. Drill down into the left-hand side
1435 // since that's where the reassociate pass puts the good stuff.
1436 if (!Op->hasOneUse())
1437 return nullptr;
1438
1439 Parent = std::make_pair(BO, 0);
1440 continue;
1441 }
1442
1443 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1444 isa<ConstantInt>(BO->getOperand(1))) {
1445 // Multiplication by a power of 2.
1446 NoSignedWrap = BO->hasNoSignedWrap();
1447 if (RequireNoSignedWrap && !NoSignedWrap)
1448 return nullptr;
1449
1450 Value *LHS = BO->getOperand(0);
1451 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1452 getLimitedValue(Scale.getBitWidth());
1453 // Op = LHS << Amt.
1454
1455 if (Amt == logScale) {
1456 // Multiplication by exactly the scale, replace the multiplication
1457 // by its left-hand side in the parent.
1458 Op = LHS;
1459 break;
1460 }
1461 if (Amt < logScale || !Op->hasOneUse())
1462 return nullptr;
1463
1464 // Multiplication by more than the scale. Reduce the multiplying amount
1465 // by the scale in the parent.
1466 Parent = std::make_pair(BO, 1);
1467 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1468 break;
1469 }
1470 }
1471
1472 if (!Op->hasOneUse())
1473 return nullptr;
1474
1475 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1476 if (Cast->getOpcode() == Instruction::SExt) {
1477 // Op is sign-extended from a smaller type, descale in the smaller type.
1478 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1479 APInt SmallScale = Scale.trunc(SmallSize);
1480 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1481 // descale Op as (sext Y) * Scale. In order to have
1482 // sext (Y * SmallScale) = (sext Y) * Scale
1483 // some conditions need to hold however: SmallScale must sign-extend to
1484 // Scale and the multiplication Y * SmallScale should not overflow.
1485 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1486 // SmallScale does not sign-extend to Scale.
1487 return nullptr;
1488 assert(SmallScale.exactLogBase2() == logScale)(static_cast <bool> (SmallScale.exactLogBase2() == logScale
) ? void (0) : __assert_fail ("SmallScale.exactLogBase2() == logScale"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1488, __extension__ __PRETTY_FUNCTION__))
;
1489 // Require that Y * SmallScale must not overflow.
1490 RequireNoSignedWrap = true;
1491
1492 // Drill down through the cast.
1493 Parent = std::make_pair(Cast, 0);
1494 Scale = SmallScale;
1495 continue;
1496 }
1497
1498 if (Cast->getOpcode() == Instruction::Trunc) {
1499 // Op is truncated from a larger type, descale in the larger type.
1500 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1501 // trunc (Y * sext Scale) = (trunc Y) * Scale
1502 // always holds. However (trunc Y) * Scale may overflow even if
1503 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1504 // from this point up in the expression (see later).
1505 if (RequireNoSignedWrap)
1506 return nullptr;
1507
1508 // Drill down through the cast.
1509 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1510 Parent = std::make_pair(Cast, 0);
1511 Scale = Scale.sext(LargeSize);
1512 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1513 logScale = -1;
1514 assert(Scale.exactLogBase2() == logScale)(static_cast <bool> (Scale.exactLogBase2() == logScale)
? void (0) : __assert_fail ("Scale.exactLogBase2() == logScale"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1514, __extension__ __PRETTY_FUNCTION__))
;
1515 continue;
1516 }
1517 }
1518
1519 // Unsupported expression, bail out.
1520 return nullptr;
1521 }
1522
1523 // If Op is zero then Val = Op * Scale.
1524 if (match(Op, m_Zero())) {
1525 NoSignedWrap = true;
1526 return Op;
1527 }
1528
1529 // We know that we can successfully descale, so from here on we can safely
1530 // modify the IR. Op holds the descaled version of the deepest term in the
1531 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1532 // not to overflow.
1533
1534 if (!Parent.first)
1535 // The expression only had one term.
1536 return Op;
1537
1538 // Rewrite the parent using the descaled version of its operand.
1539 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!")(static_cast <bool> (Parent.first->hasOneUse() &&
"Drilled down when more than one use!") ? void (0) : __assert_fail
("Parent.first->hasOneUse() && \"Drilled down when more than one use!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1539, __extension__ __PRETTY_FUNCTION__))
;
1540 assert(Op != Parent.first->getOperand(Parent.second) &&(static_cast <bool> (Op != Parent.first->getOperand(
Parent.second) && "Descaling was a no-op?") ? void (0
) : __assert_fail ("Op != Parent.first->getOperand(Parent.second) && \"Descaling was a no-op?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1541, __extension__ __PRETTY_FUNCTION__))
1541 "Descaling was a no-op?")(static_cast <bool> (Op != Parent.first->getOperand(
Parent.second) && "Descaling was a no-op?") ? void (0
) : __assert_fail ("Op != Parent.first->getOperand(Parent.second) && \"Descaling was a no-op?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1541, __extension__ __PRETTY_FUNCTION__))
;
1542 replaceOperand(*Parent.first, Parent.second, Op);
1543 Worklist.push(Parent.first);
1544
1545 // Now work back up the expression correcting nsw flags. The logic is based
1546 // on the following observation: if X * Y is known not to overflow as a signed
1547 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1548 // then X * Z will not overflow as a signed multiplication either. As we work
1549 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1550 // current level has strictly smaller absolute value than the original.
1551 Instruction *Ancestor = Parent.first;
1552 do {
1553 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1554 // If the multiplication wasn't nsw then we can't say anything about the
1555 // value of the descaled multiplication, and we have to clear nsw flags
1556 // from this point on up.
1557 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1558 NoSignedWrap &= OpNoSignedWrap;
1559 if (NoSignedWrap != OpNoSignedWrap) {
1560 BO->setHasNoSignedWrap(NoSignedWrap);
1561 Worklist.push(Ancestor);
1562 }
1563 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1564 // The fact that the descaled input to the trunc has smaller absolute
1565 // value than the original input doesn't tell us anything useful about
1566 // the absolute values of the truncations.
1567 NoSignedWrap = false;
1568 }
1569 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&(static_cast <bool> ((Ancestor->getOpcode() != Instruction
::SExt || NoSignedWrap) && "Failed to keep proper track of nsw flags while drilling down?"
) ? void (0) : __assert_fail ("(Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && \"Failed to keep proper track of nsw flags while drilling down?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1570, __extension__ __PRETTY_FUNCTION__))
1570 "Failed to keep proper track of nsw flags while drilling down?")(static_cast <bool> ((Ancestor->getOpcode() != Instruction
::SExt || NoSignedWrap) && "Failed to keep proper track of nsw flags while drilling down?"
) ? void (0) : __assert_fail ("(Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) && \"Failed to keep proper track of nsw flags while drilling down?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1570, __extension__ __PRETTY_FUNCTION__))
;
1571
1572 if (Ancestor == Val)
1573 // Got to the top, all done!
1574 return Val;
1575
1576 // Move up one level in the expression.
1577 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!")(static_cast <bool> (Ancestor->hasOneUse() &&
"Drilled down when more than one use!") ? void (0) : __assert_fail
("Ancestor->hasOneUse() && \"Drilled down when more than one use!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1577, __extension__ __PRETTY_FUNCTION__))
;
1578 Ancestor = Ancestor->user_back();
1579 } while (true);
1580}
1581
1582Instruction *InstCombinerImpl::foldVectorBinop(BinaryOperator &Inst) {
1583 if (!isa<VectorType>(Inst.getType()))
1584 return nullptr;
1585
1586 BinaryOperator::BinaryOps Opcode = Inst.getOpcode();
1587 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1588 assert(cast<VectorType>(LHS->getType())->getElementCount() ==(static_cast <bool> (cast<VectorType>(LHS->getType
())->getElementCount() == cast<VectorType>(Inst.getType
())->getElementCount()) ? void (0) : __assert_fail ("cast<VectorType>(LHS->getType())->getElementCount() == cast<VectorType>(Inst.getType())->getElementCount()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1589, __extension__ __PRETTY_FUNCTION__))
1589 cast<VectorType>(Inst.getType())->getElementCount())(static_cast <bool> (cast<VectorType>(LHS->getType
())->getElementCount() == cast<VectorType>(Inst.getType
())->getElementCount()) ? void (0) : __assert_fail ("cast<VectorType>(LHS->getType())->getElementCount() == cast<VectorType>(Inst.getType())->getElementCount()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1589, __extension__ __PRETTY_FUNCTION__))
;
1590 assert(cast<VectorType>(RHS->getType())->getElementCount() ==(static_cast <bool> (cast<VectorType>(RHS->getType
())->getElementCount() == cast<VectorType>(Inst.getType
())->getElementCount()) ? void (0) : __assert_fail ("cast<VectorType>(RHS->getType())->getElementCount() == cast<VectorType>(Inst.getType())->getElementCount()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1591, __extension__ __PRETTY_FUNCTION__))
1591 cast<VectorType>(Inst.getType())->getElementCount())(static_cast <bool> (cast<VectorType>(RHS->getType
())->getElementCount() == cast<VectorType>(Inst.getType
())->getElementCount()) ? void (0) : __assert_fail ("cast<VectorType>(RHS->getType())->getElementCount() == cast<VectorType>(Inst.getType())->getElementCount()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1591, __extension__ __PRETTY_FUNCTION__))
;
1592
1593 // If both operands of the binop are vector concatenations, then perform the
1594 // narrow binop on each pair of the source operands followed by concatenation
1595 // of the results.
1596 Value *L0, *L1, *R0, *R1;
1597 ArrayRef<int> Mask;
1598 if (match(LHS, m_Shuffle(m_Value(L0), m_Value(L1), m_Mask(Mask))) &&
1599 match(RHS, m_Shuffle(m_Value(R0), m_Value(R1), m_SpecificMask(Mask))) &&
1600 LHS->hasOneUse() && RHS->hasOneUse() &&
1601 cast<ShuffleVectorInst>(LHS)->isConcat() &&
1602 cast<ShuffleVectorInst>(RHS)->isConcat()) {
1603 // This transform does not have the speculative execution constraint as
1604 // below because the shuffle is a concatenation. The new binops are
1605 // operating on exactly the same elements as the existing binop.
1606 // TODO: We could ease the mask requirement to allow different undef lanes,
1607 // but that requires an analysis of the binop-with-undef output value.
1608 Value *NewBO0 = Builder.CreateBinOp(Opcode, L0, R0);
1609 if (auto *BO = dyn_cast<BinaryOperator>(NewBO0))
1610 BO->copyIRFlags(&Inst);
1611 Value *NewBO1 = Builder.CreateBinOp(Opcode, L1, R1);
1612 if (auto *BO = dyn_cast<BinaryOperator>(NewBO1))
1613 BO->copyIRFlags(&Inst);
1614 return new ShuffleVectorInst(NewBO0, NewBO1, Mask);
1615 }
1616
1617 // It may not be safe to reorder shuffles and things like div, urem, etc.
1618 // because we may trap when executing those ops on unknown vector elements.
1619 // See PR20059.
1620 if (!isSafeToSpeculativelyExecute(&Inst))
1621 return nullptr;
1622
1623 auto createBinOpShuffle = [&](Value *X, Value *Y, ArrayRef<int> M) {
1624 Value *XY = Builder.CreateBinOp(Opcode, X, Y);
1625 if (auto *BO = dyn_cast<BinaryOperator>(XY))
1626 BO->copyIRFlags(&Inst);
1627 return new ShuffleVectorInst(XY, UndefValue::get(XY->getType()), M);
1628 };
1629
1630 // If both arguments of the binary operation are shuffles that use the same
1631 // mask and shuffle within a single vector, move the shuffle after the binop.
1632 Value *V1, *V2;
1633 if (match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))) &&
1634 match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(Mask))) &&
1635 V1->getType() == V2->getType() &&
1636 (LHS->hasOneUse() || RHS->hasOneUse() || LHS == RHS)) {
1637 // Op(shuffle(V1, Mask), shuffle(V2, Mask)) -> shuffle(Op(V1, V2), Mask)
1638 return createBinOpShuffle(V1, V2, Mask);
1639 }
1640
1641 // If both arguments of a commutative binop are select-shuffles that use the
1642 // same mask with commuted operands, the shuffles are unnecessary.
1643 if (Inst.isCommutative() &&
1644 match(LHS, m_Shuffle(m_Value(V1), m_Value(V2), m_Mask(Mask))) &&
1645 match(RHS,
1646 m_Shuffle(m_Specific(V2), m_Specific(V1), m_SpecificMask(Mask)))) {
1647 auto *LShuf = cast<ShuffleVectorInst>(LHS);
1648 auto *RShuf = cast<ShuffleVectorInst>(RHS);
1649 // TODO: Allow shuffles that contain undefs in the mask?
1650 // That is legal, but it reduces undef knowledge.
1651 // TODO: Allow arbitrary shuffles by shuffling after binop?
1652 // That might be legal, but we have to deal with poison.
1653 if (LShuf->isSelect() &&
1654 !is_contained(LShuf->getShuffleMask(), UndefMaskElem) &&
1655 RShuf->isSelect() &&
1656 !is_contained(RShuf->getShuffleMask(), UndefMaskElem)) {
1657 // Example:
1658 // LHS = shuffle V1, V2, <0, 5, 6, 3>
1659 // RHS = shuffle V2, V1, <0, 5, 6, 3>
1660 // LHS + RHS --> (V10+V20, V21+V11, V22+V12, V13+V23) --> V1 + V2
1661 Instruction *NewBO = BinaryOperator::Create(Opcode, V1, V2);
1662 NewBO->copyIRFlags(&Inst);
1663 return NewBO;
1664 }
1665 }
1666
1667 // If one argument is a shuffle within one vector and the other is a constant,
1668 // try moving the shuffle after the binary operation. This canonicalization
1669 // intends to move shuffles closer to other shuffles and binops closer to
1670 // other binops, so they can be folded. It may also enable demanded elements
1671 // transforms.
1672 Constant *C;
1673 auto *InstVTy = dyn_cast<FixedVectorType>(Inst.getType());
1674 if (InstVTy &&
1675 match(&Inst,
1676 m_c_BinOp(m_OneUse(m_Shuffle(m_Value(V1), m_Undef(), m_Mask(Mask))),
1677 m_ImmConstant(C))) &&
1678 cast<FixedVectorType>(V1->getType())->getNumElements() <=
1679 InstVTy->getNumElements()) {
1680 assert(InstVTy->getScalarType() == V1->getType()->getScalarType() &&(static_cast <bool> (InstVTy->getScalarType() == V1->
getType()->getScalarType() && "Shuffle should not change scalar type"
) ? void (0) : __assert_fail ("InstVTy->getScalarType() == V1->getType()->getScalarType() && \"Shuffle should not change scalar type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1681, __extension__ __PRETTY_FUNCTION__))
1681 "Shuffle should not change scalar type")(static_cast <bool> (InstVTy->getScalarType() == V1->
getType()->getScalarType() && "Shuffle should not change scalar type"
) ? void (0) : __assert_fail ("InstVTy->getScalarType() == V1->getType()->getScalarType() && \"Shuffle should not change scalar type\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1681, __extension__ __PRETTY_FUNCTION__))
;
1682
1683 // Find constant NewC that has property:
1684 // shuffle(NewC, ShMask) = C
1685 // If such constant does not exist (example: ShMask=<0,0> and C=<1,2>)
1686 // reorder is not possible. A 1-to-1 mapping is not required. Example:
1687 // ShMask = <1,1,2,2> and C = <5,5,6,6> --> NewC = <undef,5,6,undef>
1688 bool ConstOp1 = isa<Constant>(RHS);
1689 ArrayRef<int> ShMask = Mask;
1690 unsigned SrcVecNumElts =
1691 cast<FixedVectorType>(V1->getType())->getNumElements();
1692 UndefValue *UndefScalar = UndefValue::get(C->getType()->getScalarType());
1693 SmallVector<Constant *, 16> NewVecC(SrcVecNumElts, UndefScalar);
1694 bool MayChange = true;
1695 unsigned NumElts = InstVTy->getNumElements();
1696 for (unsigned I = 0; I < NumElts; ++I) {
1697 Constant *CElt = C->getAggregateElement(I);
1698 if (ShMask[I] >= 0) {
1699 assert(ShMask[I] < (int)NumElts && "Not expecting narrowing shuffle")(static_cast <bool> (ShMask[I] < (int)NumElts &&
"Not expecting narrowing shuffle") ? void (0) : __assert_fail
("ShMask[I] < (int)NumElts && \"Not expecting narrowing shuffle\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 1699, __extension__ __PRETTY_FUNCTION__))
;
1700 Constant *NewCElt = NewVecC[ShMask[I]];
1701 // Bail out if:
1702 // 1. The constant vector contains a constant expression.
1703 // 2. The shuffle needs an element of the constant vector that can't
1704 // be mapped to a new constant vector.
1705 // 3. This is a widening shuffle that copies elements of V1 into the
1706 // extended elements (extending with undef is allowed).
1707 if (!CElt || (!isa<UndefValue>(NewCElt) && NewCElt != CElt) ||
1708 I >= SrcVecNumElts) {
1709 MayChange = false;
1710 break;
1711 }
1712 NewVecC[ShMask[I]] = CElt;
1713 }
1714 // If this is a widening shuffle, we must be able to extend with undef
1715 // elements. If the original binop does not produce an undef in the high
1716 // lanes, then this transform is not safe.
1717 // Similarly for undef lanes due to the shuffle mask, we can only
1718 // transform binops that preserve undef.
1719 // TODO: We could shuffle those non-undef constant values into the
1720 // result by using a constant vector (rather than an undef vector)
1721 // as operand 1 of the new binop, but that might be too aggressive
1722 // for target-independent shuffle creation.
1723 if (I >= SrcVecNumElts || ShMask[I] < 0) {
1724 Constant *MaybeUndef =
1725 ConstOp1 ? ConstantExpr::get(Opcode, UndefScalar, CElt)
1726 : ConstantExpr::get(Opcode, CElt, UndefScalar);
1727 if (!match(MaybeUndef, m_Undef())) {
1728 MayChange = false;
1729 break;
1730 }
1731 }
1732 }
1733 if (MayChange) {
1734 Constant *NewC = ConstantVector::get(NewVecC);
1735 // It may not be safe to execute a binop on a vector with undef elements
1736 // because the entire instruction can be folded to undef or create poison
1737 // that did not exist in the original code.
1738 if (Inst.isIntDivRem() || (Inst.isShift() && ConstOp1))
1739 NewC = getSafeVectorConstantForBinop(Opcode, NewC, ConstOp1);
1740
1741 // Op(shuffle(V1, Mask), C) -> shuffle(Op(V1, NewC), Mask)
1742 // Op(C, shuffle(V1, Mask)) -> shuffle(Op(NewC, V1), Mask)
1743 Value *NewLHS = ConstOp1 ? V1 : NewC;
1744 Value *NewRHS = ConstOp1 ? NewC : V1;
1745 return createBinOpShuffle(NewLHS, NewRHS, Mask);
1746 }
1747 }
1748
1749 // Try to reassociate to sink a splat shuffle after a binary operation.
1750 if (Inst.isAssociative() && Inst.isCommutative()) {
1751 // Canonicalize shuffle operand as LHS.
1752 if (isa<ShuffleVectorInst>(RHS))
1753 std::swap(LHS, RHS);
1754
1755 Value *X;
1756 ArrayRef<int> MaskC;
1757 int SplatIndex;
1758 BinaryOperator *BO;
1759 if (!match(LHS,
1760 m_OneUse(m_Shuffle(m_Value(X), m_Undef(), m_Mask(MaskC)))) ||
1761 !match(MaskC, m_SplatOrUndefMask(SplatIndex)) ||
1762 X->getType() != Inst.getType() || !match(RHS, m_OneUse(m_BinOp(BO))) ||
1763 BO->getOpcode() != Opcode)
1764 return nullptr;
1765
1766 // FIXME: This may not be safe if the analysis allows undef elements. By
1767 // moving 'Y' before the splat shuffle, we are implicitly assuming
1768 // that it is not undef/poison at the splat index.
1769 Value *Y, *OtherOp;
1770 if (isSplatValue(BO->getOperand(0), SplatIndex)) {
1771 Y = BO->getOperand(0);
1772 OtherOp = BO->getOperand(1);
1773 } else if (isSplatValue(BO->getOperand(1), SplatIndex)) {
1774 Y = BO->getOperand(1);
1775 OtherOp = BO->getOperand(0);
1776 } else {
1777 return nullptr;
1778 }
1779
1780 // X and Y are splatted values, so perform the binary operation on those
1781 // values followed by a splat followed by the 2nd binary operation:
1782 // bo (splat X), (bo Y, OtherOp) --> bo (splat (bo X, Y)), OtherOp
1783 Value *NewBO = Builder.CreateBinOp(Opcode, X, Y);
1784 SmallVector<int, 8> NewMask(MaskC.size(), SplatIndex);
1785 Value *NewSplat = Builder.CreateShuffleVector(NewBO, NewMask);
1786 Instruction *R = BinaryOperator::Create(Opcode, NewSplat, OtherOp);
1787
1788 // Intersect FMF on both new binops. Other (poison-generating) flags are
1789 // dropped to be safe.
1790 if (isa<FPMathOperator>(R)) {
1791 R->copyFastMathFlags(&Inst);
1792 R->andIRFlags(BO);
1793 }
1794 if (auto *NewInstBO = dyn_cast<BinaryOperator>(NewBO))
1795 NewInstBO->copyIRFlags(R);
1796 return R;
1797 }
1798
1799 return nullptr;
1800}
1801
1802/// Try to narrow the width of a binop if at least 1 operand is an extend of
1803/// of a value. This requires a potentially expensive known bits check to make
1804/// sure the narrow op does not overflow.
1805Instruction *InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator &BO) {
1806 // We need at least one extended operand.
1807 Value *Op0 = BO.getOperand(0), *Op1 = BO.getOperand(1);
1808
1809 // If this is a sub, we swap the operands since we always want an extension
1810 // on the RHS. The LHS can be an extension or a constant.
1811 if (BO.getOpcode() == Instruction::Sub)
1812 std::swap(Op0, Op1);
1813
1814 Value *X;
1815 bool IsSext = match(Op0, m_SExt(m_Value(X)));
1816 if (!IsSext && !match(Op0, m_ZExt(m_Value(X))))
1817 return nullptr;
1818
1819 // If both operands are the same extension from the same source type and we
1820 // can eliminate at least one (hasOneUse), this might work.
1821 CastInst::CastOps CastOpc = IsSext ? Instruction::SExt : Instruction::ZExt;
1822 Value *Y;
1823 if (!(match(Op1, m_ZExtOrSExt(m_Value(Y))) && X->getType() == Y->getType() &&
1824 cast<Operator>(Op1)->getOpcode() == CastOpc &&
1825 (Op0->hasOneUse() || Op1->hasOneUse()))) {
1826 // If that did not match, see if we have a suitable constant operand.
1827 // Truncating and extending must produce the same constant.
1828 Constant *WideC;
1829 if (!Op0->hasOneUse() || !match(Op1, m_Constant(WideC)))
1830 return nullptr;
1831 Constant *NarrowC = ConstantExpr::getTrunc(WideC, X->getType());
1832 if (ConstantExpr::getCast(CastOpc, NarrowC, BO.getType()) != WideC)
1833 return nullptr;
1834 Y = NarrowC;
1835 }
1836
1837 // Swap back now that we found our operands.
1838 if (BO.getOpcode() == Instruction::Sub)
1839 std::swap(X, Y);
1840
1841 // Both operands have narrow versions. Last step: the math must not overflow
1842 // in the narrow width.
1843 if (!willNotOverflow(BO.getOpcode(), X, Y, BO, IsSext))
1844 return nullptr;
1845
1846 // bo (ext X), (ext Y) --> ext (bo X, Y)
1847 // bo (ext X), C --> ext (bo X, C')
1848 Value *NarrowBO = Builder.CreateBinOp(BO.getOpcode(), X, Y, "narrow");
1849 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NarrowBO)) {
1850 if (IsSext)
1851 NewBinOp->setHasNoSignedWrap();
1852 else
1853 NewBinOp->setHasNoUnsignedWrap();
1854 }
1855 return CastInst::Create(CastOpc, NarrowBO, BO.getType());
1856}
1857
1858static bool isMergedGEPInBounds(GEPOperator &GEP1, GEPOperator &GEP2) {
1859 // At least one GEP must be inbounds.
1860 if (!GEP1.isInBounds() && !GEP2.isInBounds())
1861 return false;
1862
1863 return (GEP1.isInBounds() || GEP1.hasAllZeroIndices()) &&
1864 (GEP2.isInBounds() || GEP2.hasAllZeroIndices());
1865}
1866
1867/// Thread a GEP operation with constant indices through the constant true/false
1868/// arms of a select.
1869static Instruction *foldSelectGEP(GetElementPtrInst &GEP,
1870 InstCombiner::BuilderTy &Builder) {
1871 if (!GEP.hasAllConstantIndices())
1872 return nullptr;
1873
1874 Instruction *Sel;
1875 Value *Cond;
1876 Constant *TrueC, *FalseC;
1877 if (!match(GEP.getPointerOperand(), m_Instruction(Sel)) ||
1878 !match(Sel,
1879 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
1880 return nullptr;
1881
1882 // gep (select Cond, TrueC, FalseC), IndexC --> select Cond, TrueC', FalseC'
1883 // Propagate 'inbounds' and metadata from existing instructions.
1884 // Note: using IRBuilder to create the constants for efficiency.
1885 SmallVector<Value *, 4> IndexC(GEP.indices());
1886 bool IsInBounds = GEP.isInBounds();
1887 Type *Ty = GEP.getSourceElementType();
1888 Value *NewTrueC = IsInBounds ? Builder.CreateInBoundsGEP(Ty, TrueC, IndexC)
1889 : Builder.CreateGEP(Ty, TrueC, IndexC);
1890 Value *NewFalseC = IsInBounds ? Builder.CreateInBoundsGEP(Ty, FalseC, IndexC)
1891 : Builder.CreateGEP(Ty, FalseC, IndexC);
1892 return SelectInst::Create(Cond, NewTrueC, NewFalseC, "", nullptr, Sel);
1893}
1894
1895Instruction *InstCombinerImpl::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1896 SmallVector<Value *, 8> Ops(GEP.operands());
1897 Type *GEPType = GEP.getType();
1898 Type *GEPEltType = GEP.getSourceElementType();
1899 bool IsGEPSrcEleScalable = isa<ScalableVectorType>(GEPEltType);
1900 if (Value *V = SimplifyGEPInst(GEPEltType, Ops, SQ.getWithInstruction(&GEP)))
1901 return replaceInstUsesWith(GEP, V);
1902
1903 // For vector geps, use the generic demanded vector support.
1904 // Skip if GEP return type is scalable. The number of elements is unknown at
1905 // compile-time.
1906 if (auto *GEPFVTy = dyn_cast<FixedVectorType>(GEPType)) {
1907 auto VWidth = GEPFVTy->getNumElements();
1908 APInt UndefElts(VWidth, 0);
1909 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1910 if (Value *V = SimplifyDemandedVectorElts(&GEP, AllOnesEltMask,
1911 UndefElts)) {
1912 if (V != &GEP)
1913 return replaceInstUsesWith(GEP, V);
1914 return &GEP;
1915 }
1916
1917 // TODO: 1) Scalarize splat operands, 2) scalarize entire instruction if
1918 // possible (decide on canonical form for pointer broadcast), 3) exploit
1919 // undef elements to decrease demanded bits
1920 }
1921
1922 Value *PtrOp = GEP.getOperand(0);
1923
1924 // Eliminate unneeded casts for indices, and replace indices which displace
1925 // by multiples of a zero size type with zero.
1926 bool MadeChange = false;
1927
1928 // Index width may not be the same width as pointer width.
1929 // Data layout chooses the right type based on supported integer types.
1930 Type *NewScalarIndexTy =
1931 DL.getIndexType(GEP.getPointerOperandType()->getScalarType());
1932
1933 gep_type_iterator GTI = gep_type_begin(GEP);
1934 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1935 ++I, ++GTI) {
1936 // Skip indices into struct types.
1937 if (GTI.isStruct())
1938 continue;
1939
1940 Type *IndexTy = (*I)->getType();
1941 Type *NewIndexType =
1942 IndexTy->isVectorTy()
1943 ? VectorType::get(NewScalarIndexTy,
1944 cast<VectorType>(IndexTy)->getElementCount())
1945 : NewScalarIndexTy;
1946
1947 // If the element type has zero size then any index over it is equivalent
1948 // to an index of zero, so replace it with zero if it is not zero already.
1949 Type *EltTy = GTI.getIndexedType();
1950 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy).isZero())
1951 if (!isa<Constant>(*I) || !match(I->get(), m_Zero())) {
1952 *I = Constant::getNullValue(NewIndexType);
1953 MadeChange = true;
1954 }
1955
1956 if (IndexTy != NewIndexType) {
1957 // If we are using a wider index than needed for this platform, shrink
1958 // it to what we need. If narrower, sign-extend it to what we need.
1959 // This explicit cast can make subsequent optimizations more obvious.
1960 *I = Builder.CreateIntCast(*I, NewIndexType, true);
1961 MadeChange = true;
1962 }
1963 }
1964 if (MadeChange)
1965 return &GEP;
1966
1967 // Check to see if the inputs to the PHI node are getelementptr instructions.
1968 if (auto *PN = dyn_cast<PHINode>(PtrOp)) {
1969 auto *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1970 if (!Op1)
1971 return nullptr;
1972
1973 // Don't fold a GEP into itself through a PHI node. This can only happen
1974 // through the back-edge of a loop. Folding a GEP into itself means that
1975 // the value of the previous iteration needs to be stored in the meantime,
1976 // thus requiring an additional register variable to be live, but not
1977 // actually achieving anything (the GEP still needs to be executed once per
1978 // loop iteration).
1979 if (Op1 == &GEP)
1980 return nullptr;
1981
1982 int DI = -1;
1983
1984 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1985 auto *Op2 = dyn_cast<GetElementPtrInst>(*I);
1986 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1987 return nullptr;
1988
1989 // As for Op1 above, don't try to fold a GEP into itself.
1990 if (Op2 == &GEP)
1991 return nullptr;
1992
1993 // Keep track of the type as we walk the GEP.
1994 Type *CurTy = nullptr;
1995
1996 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1997 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1998 return nullptr;
1999
2000 if (Op1->getOperand(J) != Op2->getOperand(J)) {
2001 if (DI == -1) {
2002 // We have not seen any differences yet in the GEPs feeding the
2003 // PHI yet, so we record this one if it is allowed to be a
2004 // variable.
2005
2006 // The first two arguments can vary for any GEP, the rest have to be
2007 // static for struct slots
2008 if (J > 1) {
2009 assert(CurTy && "No current type?")(static_cast <bool> (CurTy && "No current type?"
) ? void (0) : __assert_fail ("CurTy && \"No current type?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2009, __extension__ __PRETTY_FUNCTION__))
;
2010 if (CurTy->isStructTy())
2011 return nullptr;
2012 }
2013
2014 DI = J;
2015 } else {
2016 // The GEP is different by more than one input. While this could be
2017 // extended to support GEPs that vary by more than one variable it
2018 // doesn't make sense since it greatly increases the complexity and
2019 // would result in an R+R+R addressing mode which no backend
2020 // directly supports and would need to be broken into several
2021 // simpler instructions anyway.
2022 return nullptr;
2023 }
2024 }
2025
2026 // Sink down a layer of the type for the next iteration.
2027 if (J > 0) {
2028 if (J == 1) {
2029 CurTy = Op1->getSourceElementType();
2030 } else {
2031 CurTy =
2032 GetElementPtrInst::getTypeAtIndex(CurTy, Op1->getOperand(J));
2033 }
2034 }
2035 }
2036 }
2037
2038 // If not all GEPs are identical we'll have to create a new PHI node.
2039 // Check that the old PHI node has only one use so that it will get
2040 // removed.
2041 if (DI != -1 && !PN->hasOneUse())
2042 return nullptr;
2043
2044 auto *NewGEP = cast<GetElementPtrInst>(Op1->clone());
2045 if (DI == -1) {
2046 // All the GEPs feeding the PHI are identical. Clone one down into our
2047 // BB so that it can be merged with the current GEP.
2048 } else {
2049 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
2050 // into the current block so it can be merged, and create a new PHI to
2051 // set that index.
2052 PHINode *NewPN;
2053 {
2054 IRBuilderBase::InsertPointGuard Guard(Builder);
2055 Builder.SetInsertPoint(PN);
2056 NewPN = Builder.CreatePHI(Op1->getOperand(DI)->getType(),
2057 PN->getNumOperands());
2058 }
2059
2060 for (auto &I : PN->operands())
2061 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
2062 PN->getIncomingBlock(I));
2063
2064 NewGEP->setOperand(DI, NewPN);
2065 }
2066
2067 GEP.getParent()->getInstList().insert(
2068 GEP.getParent()->getFirstInsertionPt(), NewGEP);
2069 replaceOperand(GEP, 0, NewGEP);
2070 PtrOp = NewGEP;
2071 }
2072
2073 // Combine Indices - If the source pointer to this getelementptr instruction
2074 // is a getelementptr instruction, combine the indices of the two
2075 // getelementptr instructions into a single instruction.
2076 if (auto *Src = dyn_cast<GEPOperator>(PtrOp)) {
2077 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
2078 return nullptr;
2079
2080 if (Src->getNumOperands() == 2 && GEP.getNumOperands() == 2 &&
2081 Src->hasOneUse()) {
2082 Value *GO1 = GEP.getOperand(1);
2083 Value *SO1 = Src->getOperand(1);
2084
2085 if (LI) {
2086 // Try to reassociate loop invariant GEP chains to enable LICM.
2087 if (Loop *L = LI->getLoopFor(GEP.getParent())) {
2088 // Reassociate the two GEPs if SO1 is variant in the loop and GO1 is
2089 // invariant: this breaks the dependence between GEPs and allows LICM
2090 // to hoist the invariant part out of the loop.
2091 if (L->isLoopInvariant(GO1) && !L->isLoopInvariant(SO1)) {
2092 // We have to be careful here.
2093 // We have something like:
2094 // %src = getelementptr <ty>, <ty>* %base, <ty> %idx
2095 // %gep = getelementptr <ty>, <ty>* %src, <ty> %idx2
2096 // If we just swap idx & idx2 then we could inadvertantly
2097 // change %src from a vector to a scalar, or vice versa.
2098 // Cases:
2099 // 1) %base a scalar & idx a scalar & idx2 a vector
2100 // => Swapping idx & idx2 turns %src into a vector type.
2101 // 2) %base a scalar & idx a vector & idx2 a scalar
2102 // => Swapping idx & idx2 turns %src in a scalar type
2103 // 3) %base, %idx, and %idx2 are scalars
2104 // => %src & %gep are scalars
2105 // => swapping idx & idx2 is safe
2106 // 4) %base a vector
2107 // => %src is a vector
2108 // => swapping idx & idx2 is safe.
2109 auto *SO0 = Src->getOperand(0);
2110 auto *SO0Ty = SO0->getType();
2111 if (!isa<VectorType>(GEPType) || // case 3
2112 isa<VectorType>(SO0Ty)) { // case 4
2113 Src->setOperand(1, GO1);
2114 GEP.setOperand(1, SO1);
2115 return &GEP;
2116 } else {
2117 // Case 1 or 2
2118 // -- have to recreate %src & %gep
2119 // put NewSrc at same location as %src
2120 Builder.SetInsertPoint(cast<Instruction>(PtrOp));
2121 Value *NewSrc =
2122 Builder.CreateGEP(GEPEltType, SO0, GO1, Src->getName());
2123 // Propagate 'inbounds' if the new source was not constant-folded.
2124 if (auto *NewSrcGEPI = dyn_cast<GetElementPtrInst>(NewSrc))
2125 NewSrcGEPI->setIsInBounds(Src->isInBounds());
2126 GetElementPtrInst *NewGEP =
2127 GetElementPtrInst::Create(GEPEltType, NewSrc, {SO1});
2128 NewGEP->setIsInBounds(GEP.isInBounds());
2129 return NewGEP;
2130 }
2131 }
2132 }
2133 }
2134 }
2135
2136 // Note that if our source is a gep chain itself then we wait for that
2137 // chain to be resolved before we perform this transformation. This
2138 // avoids us creating a TON of code in some cases.
2139 if (auto *SrcGEP = dyn_cast<GEPOperator>(Src->getOperand(0)))
2140 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
2141 return nullptr; // Wait until our source is folded to completion.
2142
2143 SmallVector<Value*, 8> Indices;
2144
2145 // Find out whether the last index in the source GEP is a sequential idx.
2146 bool EndsWithSequential = false;
2147 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
2148 I != E; ++I)
2149 EndsWithSequential = I.isSequential();
2150
2151 // Can we combine the two pointer arithmetics offsets?
2152 if (EndsWithSequential) {
2153 // Replace: gep (gep %P, long B), long A, ...
2154 // With: T = long A+B; gep %P, T, ...
2155 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
2156 Value *GO1 = GEP.getOperand(1);
2157
2158 // If they aren't the same type, then the input hasn't been processed
2159 // by the loop above yet (which canonicalizes sequential index types to
2160 // intptr_t). Just avoid transforming this until the input has been
2161 // normalized.
2162 if (SO1->getType() != GO1->getType())
2163 return nullptr;
2164
2165 Value *Sum =
2166 SimplifyAddInst(GO1, SO1, false, false, SQ.getWithInstruction(&GEP));
2167 // Only do the combine when we are sure the cost after the
2168 // merge is never more than that before the merge.
2169 if (Sum == nullptr)
2170 return nullptr;
2171
2172 // Update the GEP in place if possible.
2173 if (Src->getNumOperands() == 2) {
2174 GEP.setIsInBounds(isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP)));
2175 replaceOperand(GEP, 0, Src->getOperand(0));
2176 replaceOperand(GEP, 1, Sum);
2177 return &GEP;
2178 }
2179 Indices.append(Src->op_begin()+1, Src->op_end()-1);
2180 Indices.push_back(Sum);
2181 Indices.append(GEP.op_begin()+2, GEP.op_end());
2182 } else if (isa<Constant>(*GEP.idx_begin()) &&
2183 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
2184 Src->getNumOperands() != 1) {
2185 // Otherwise we can do the fold if the first index of the GEP is a zero
2186 Indices.append(Src->op_begin()+1, Src->op_end());
2187 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
2188 }
2189
2190 if (!Indices.empty())
2191 return isMergedGEPInBounds(*Src, *cast<GEPOperator>(&GEP))
2192 ? GetElementPtrInst::CreateInBounds(
2193 Src->getSourceElementType(), Src->getOperand(0), Indices,
2194 GEP.getName())
2195 : GetElementPtrInst::Create(Src->getSourceElementType(),
2196 Src->getOperand(0), Indices,
2197 GEP.getName());
2198 }
2199
2200 // Skip if GEP source element type is scalable. The type alloc size is unknown
2201 // at compile-time.
2202 if (GEP.getNumIndices() == 1 && !IsGEPSrcEleScalable) {
2203 unsigned AS = GEP.getPointerAddressSpace();
2204 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
2205 DL.getIndexSizeInBits(AS)) {
2206 uint64_t TyAllocSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2207
2208 bool Matched = false;
2209 uint64_t C;
2210 Value *V = nullptr;
2211 if (TyAllocSize == 1) {
2212 V = GEP.getOperand(1);
2213 Matched = true;
2214 } else if (match(GEP.getOperand(1),
2215 m_AShr(m_Value(V), m_ConstantInt(C)))) {
2216 if (TyAllocSize == 1ULL << C)
2217 Matched = true;
2218 } else if (match(GEP.getOperand(1),
2219 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
2220 if (TyAllocSize == C)
2221 Matched = true;
2222 }
2223
2224 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y), but
2225 // only if both point to the same underlying object (otherwise provenance
2226 // is not necessarily retained).
2227 Value *Y;
2228 Value *X = GEP.getOperand(0);
2229 if (Matched &&
2230 match(V, m_Sub(m_PtrToInt(m_Value(Y)), m_PtrToInt(m_Specific(X)))) &&
2231 getUnderlyingObject(X) == getUnderlyingObject(Y))
2232 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y, GEPType);
2233 }
2234 }
2235
2236 // We do not handle pointer-vector geps here.
2237 if (GEPType->isVectorTy())
2238 return nullptr;
2239
2240 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2241 Value *StrippedPtr = PtrOp->stripPointerCasts();
2242 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
2243
2244 if (StrippedPtr != PtrOp) {
2245 bool HasZeroPointerIndex = false;
2246 Type *StrippedPtrEltTy = StrippedPtrTy->getElementType();
2247
2248 if (auto *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
2249 HasZeroPointerIndex = C->isZero();
2250
2251 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2252 // into : GEP [10 x i8]* X, i32 0, ...
2253 //
2254 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2255 // into : GEP i8* X, ...
2256 //
2257 // This occurs when the program declares an array extern like "int X[];"
2258 if (HasZeroPointerIndex) {
2259 if (auto *CATy = dyn_cast<ArrayType>(GEPEltType)) {
2260 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2261 if (CATy->getElementType() == StrippedPtrEltTy) {
2262 // -> GEP i8* X, ...
2263 SmallVector<Value *, 8> Idx(drop_begin(GEP.indices()));
2264 GetElementPtrInst *Res = GetElementPtrInst::Create(
2265 StrippedPtrEltTy, StrippedPtr, Idx, GEP.getName());
2266 Res->setIsInBounds(GEP.isInBounds());
2267 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
2268 return Res;
2269 // Insert Res, and create an addrspacecast.
2270 // e.g.,
2271 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2272 // ->
2273 // %0 = GEP i8 addrspace(1)* X, ...
2274 // addrspacecast i8 addrspace(1)* %0 to i8*
2275 return new AddrSpaceCastInst(Builder.Insert(Res), GEPType);
2276 }
2277
2278 if (auto *XATy = dyn_cast<ArrayType>(StrippedPtrEltTy)) {
2279 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2280 if (CATy->getElementType() == XATy->getElementType()) {
2281 // -> GEP [10 x i8]* X, i32 0, ...
2282 // At this point, we know that the cast source type is a pointer
2283 // to an array of the same type as the destination pointer
2284 // array. Because the array type is never stepped over (there
2285 // is a leading zero) we can fold the cast into this GEP.
2286 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
2287 GEP.setSourceElementType(XATy);
2288 return replaceOperand(GEP, 0, StrippedPtr);
2289 }
2290 // Cannot replace the base pointer directly because StrippedPtr's
2291 // address space is different. Instead, create a new GEP followed by
2292 // an addrspacecast.
2293 // e.g.,
2294 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2295 // i32 0, ...
2296 // ->
2297 // %0 = GEP [10 x i8] addrspace(1)* X, ...
2298 // addrspacecast i8 addrspace(1)* %0 to i8*
2299 SmallVector<Value *, 8> Idx(GEP.indices());
2300 Value *NewGEP =
2301 GEP.isInBounds()
2302 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2303 Idx, GEP.getName())
2304 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2305 GEP.getName());
2306 return new AddrSpaceCastInst(NewGEP, GEPType);
2307 }
2308 }
2309 }
2310 } else if (GEP.getNumOperands() == 2 && !IsGEPSrcEleScalable) {
2311 // Skip if GEP source element type is scalable. The type alloc size is
2312 // unknown at compile-time.
2313 // Transform things like: %t = getelementptr i32*
2314 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2
2315 // x i32]* %str, i32 0, i32 %V; bitcast
2316 if (StrippedPtrEltTy->isArrayTy() &&
2317 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType()) ==
2318 DL.getTypeAllocSize(GEPEltType)) {
2319 Type *IdxType = DL.getIndexType(GEPType);
2320 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
2321 Value *NewGEP =
2322 GEP.isInBounds()
2323 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2324 GEP.getName())
2325 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Idx,
2326 GEP.getName());
2327
2328 // V and GEP are both pointer types --> BitCast
2329 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP, GEPType);
2330 }
2331
2332 // Transform things like:
2333 // %V = mul i64 %N, 4
2334 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2335 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
2336 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized()) {
2337 // Check that changing the type amounts to dividing the index by a scale
2338 // factor.
2339 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2340 uint64_t SrcSize = DL.getTypeAllocSize(StrippedPtrEltTy).getFixedSize();
2341 if (ResSize && SrcSize % ResSize == 0) {
2342 Value *Idx = GEP.getOperand(1);
2343 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2344 uint64_t Scale = SrcSize / ResSize;
2345
2346 // Earlier transforms ensure that the index has the right type
2347 // according to Data Layout, which considerably simplifies the
2348 // logic by eliminating implicit casts.
2349 assert(Idx->getType() == DL.getIndexType(GEPType) &&(static_cast <bool> (Idx->getType() == DL.getIndexType
(GEPType) && "Index type does not match the Data Layout preferences"
) ? void (0) : __assert_fail ("Idx->getType() == DL.getIndexType(GEPType) && \"Index type does not match the Data Layout preferences\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2350, __extension__ __PRETTY_FUNCTION__))
2350 "Index type does not match the Data Layout preferences")(static_cast <bool> (Idx->getType() == DL.getIndexType
(GEPType) && "Index type does not match the Data Layout preferences"
) ? void (0) : __assert_fail ("Idx->getType() == DL.getIndexType(GEPType) && \"Index type does not match the Data Layout preferences\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2350, __extension__ __PRETTY_FUNCTION__))
;
2351
2352 bool NSW;
2353 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2354 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2355 // If the multiplication NewIdx * Scale may overflow then the new
2356 // GEP may not be "inbounds".
2357 Value *NewGEP =
2358 GEP.isInBounds() && NSW
2359 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2360 NewIdx, GEP.getName())
2361 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, NewIdx,
2362 GEP.getName());
2363
2364 // The NewGEP must be pointer typed, so must the old one -> BitCast
2365 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2366 GEPType);
2367 }
2368 }
2369 }
2370
2371 // Similarly, transform things like:
2372 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2373 // (where tmp = 8*tmp2) into:
2374 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2375 if (GEPEltType->isSized() && StrippedPtrEltTy->isSized() &&
2376 StrippedPtrEltTy->isArrayTy()) {
2377 // Check that changing to the array element type amounts to dividing the
2378 // index by a scale factor.
2379 uint64_t ResSize = DL.getTypeAllocSize(GEPEltType).getFixedSize();
2380 uint64_t ArrayEltSize =
2381 DL.getTypeAllocSize(StrippedPtrEltTy->getArrayElementType())
2382 .getFixedSize();
2383 if (ResSize && ArrayEltSize % ResSize == 0) {
2384 Value *Idx = GEP.getOperand(1);
2385 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
2386 uint64_t Scale = ArrayEltSize / ResSize;
2387
2388 // Earlier transforms ensure that the index has the right type
2389 // according to the Data Layout, which considerably simplifies
2390 // the logic by eliminating implicit casts.
2391 assert(Idx->getType() == DL.getIndexType(GEPType) &&(static_cast <bool> (Idx->getType() == DL.getIndexType
(GEPType) && "Index type does not match the Data Layout preferences"
) ? void (0) : __assert_fail ("Idx->getType() == DL.getIndexType(GEPType) && \"Index type does not match the Data Layout preferences\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2392, __extension__ __PRETTY_FUNCTION__))
2392 "Index type does not match the Data Layout preferences")(static_cast <bool> (Idx->getType() == DL.getIndexType
(GEPType) && "Index type does not match the Data Layout preferences"
) ? void (0) : __assert_fail ("Idx->getType() == DL.getIndexType(GEPType) && \"Index type does not match the Data Layout preferences\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2392, __extension__ __PRETTY_FUNCTION__))
;
2393
2394 bool NSW;
2395 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
2396 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2397 // If the multiplication NewIdx * Scale may overflow then the new
2398 // GEP may not be "inbounds".
2399 Type *IndTy = DL.getIndexType(GEPType);
2400 Value *Off[2] = {Constant::getNullValue(IndTy), NewIdx};
2401
2402 Value *NewGEP =
2403 GEP.isInBounds() && NSW
2404 ? Builder.CreateInBoundsGEP(StrippedPtrEltTy, StrippedPtr,
2405 Off, GEP.getName())
2406 : Builder.CreateGEP(StrippedPtrEltTy, StrippedPtr, Off,
2407 GEP.getName());
2408 // The NewGEP must be pointer typed, so must the old one -> BitCast
2409 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
2410 GEPType);
2411 }
2412 }
2413 }
2414 }
2415 }
2416
2417 // addrspacecast between types is canonicalized as a bitcast, then an
2418 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2419 // through the addrspacecast.
2420 Value *ASCStrippedPtrOp = PtrOp;
2421 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
2422 // X = bitcast A addrspace(1)* to B addrspace(1)*
2423 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2424 // Z = gep Y, <...constant indices...>
2425 // Into an addrspacecasted GEP of the struct.
2426 if (auto *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
2427 ASCStrippedPtrOp = BC;
2428 }
2429
2430 if (auto *BCI = dyn_cast<BitCastInst>(ASCStrippedPtrOp)) {
2431 Value *SrcOp = BCI->getOperand(0);
2432 PointerType *SrcType = cast<PointerType>(BCI->getSrcTy());
2433 Type *SrcEltType = SrcType->getElementType();
2434
2435 // GEP directly using the source operand if this GEP is accessing an element
2436 // of a bitcasted pointer to vector or array of the same dimensions:
2437 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2438 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2439 auto areMatchingArrayAndVecTypes = [](Type *ArrTy, Type *VecTy,
2440 const DataLayout &DL) {
2441 auto *VecVTy = cast<FixedVectorType>(VecTy);
2442 return ArrTy->getArrayElementType() == VecVTy->getElementType() &&
2443 ArrTy->getArrayNumElements() == VecVTy->getNumElements() &&
2444 DL.getTypeAllocSize(ArrTy) == DL.getTypeAllocSize(VecTy);
2445 };
2446 if (GEP.getNumOperands() == 3 &&
2447 ((GEPEltType->isArrayTy() && isa<FixedVectorType>(SrcEltType) &&
2448 areMatchingArrayAndVecTypes(GEPEltType, SrcEltType, DL)) ||
2449 (isa<FixedVectorType>(GEPEltType) && SrcEltType->isArrayTy() &&
2450 areMatchingArrayAndVecTypes(SrcEltType, GEPEltType, DL)))) {
2451
2452 // Create a new GEP here, as using `setOperand()` followed by
2453 // `setSourceElementType()` won't actually update the type of the
2454 // existing GEP Value. Causing issues if this Value is accessed when
2455 // constructing an AddrSpaceCastInst
2456 Value *NGEP =
2457 GEP.isInBounds()
2458 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]})
2459 : Builder.CreateGEP(SrcEltType, SrcOp, {Ops[1], Ops[2]});
2460 NGEP->takeName(&GEP);
2461
2462 // Preserve GEP address space to satisfy users
2463 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2464 return new AddrSpaceCastInst(NGEP, GEPType);
2465
2466 return replaceInstUsesWith(GEP, NGEP);
2467 }
2468
2469 // See if we can simplify:
2470 // X = bitcast A* to B*
2471 // Y = gep X, <...constant indices...>
2472 // into a gep of the original struct. This is important for SROA and alias
2473 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2474 unsigned OffsetBits = DL.getIndexTypeSizeInBits(GEPType);
2475 APInt Offset(OffsetBits, 0);
2476
2477 // If the bitcast argument is an allocation, The bitcast is for convertion
2478 // to actual type of allocation. Removing such bitcasts, results in having
2479 // GEPs with i8* base and pure byte offsets. That means GEP is not aware of
2480 // struct or array hierarchy.
2481 // By avoiding such GEPs, phi translation and MemoryDependencyAnalysis have
2482 // a better chance to succeed.
2483 if (!isa<BitCastInst>(SrcOp) && GEP.accumulateConstantOffset(DL, Offset) &&
2484 !isAllocationFn(SrcOp, &TLI)) {
2485 // If this GEP instruction doesn't move the pointer, just replace the GEP
2486 // with a bitcast of the real input to the dest type.
2487 if (!Offset) {
2488 // If the bitcast is of an allocation, and the allocation will be
2489 // converted to match the type of the cast, don't touch this.
2490 if (isa<AllocaInst>(SrcOp)) {
2491 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2492 if (Instruction *I = visitBitCast(*BCI)) {
2493 if (I != BCI) {
2494 I->takeName(BCI);
2495 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
2496 replaceInstUsesWith(*BCI, I);
2497 }
2498 return &GEP;
2499 }
2500 }
2501
2502 if (SrcType->getPointerAddressSpace() != GEP.getAddressSpace())
2503 return new AddrSpaceCastInst(SrcOp, GEPType);
2504 return new BitCastInst(SrcOp, GEPType);
2505 }
2506
2507 // Otherwise, if the offset is non-zero, we need to find out if there is a
2508 // field at Offset in 'A's type. If so, we can pull the cast through the
2509 // GEP.
2510 SmallVector<Value*, 8> NewIndices;
2511 if (FindElementAtOffset(SrcType, Offset.getSExtValue(), NewIndices)) {
2512 Value *NGEP =
2513 GEP.isInBounds()
2514 ? Builder.CreateInBoundsGEP(SrcEltType, SrcOp, NewIndices)
2515 : Builder.CreateGEP(SrcEltType, SrcOp, NewIndices);
2516
2517 if (NGEP->getType() == GEPType)
2518 return replaceInstUsesWith(GEP, NGEP);
2519 NGEP->takeName(&GEP);
2520
2521 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
2522 return new AddrSpaceCastInst(NGEP, GEPType);
2523 return new BitCastInst(NGEP, GEPType);
2524 }
2525 }
2526 }
2527
2528 if (!GEP.isInBounds()) {
2529 unsigned IdxWidth =
2530 DL.getIndexSizeInBits(PtrOp->getType()->getPointerAddressSpace());
2531 APInt BasePtrOffset(IdxWidth, 0);
2532 Value *UnderlyingPtrOp =
2533 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
2534 BasePtrOffset);
2535 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
2536 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
2537 BasePtrOffset.isNonNegative()) {
2538 APInt AllocSize(
2539 IdxWidth,
2540 DL.getTypeAllocSize(AI->getAllocatedType()).getKnownMinSize());
2541 if (BasePtrOffset.ule(AllocSize)) {
2542 return GetElementPtrInst::CreateInBounds(
2543 GEP.getSourceElementType(), PtrOp, makeArrayRef(Ops).slice(1),
2544 GEP.getName());
2545 }
2546 }
2547 }
2548 }
2549
2550 if (Instruction *R = foldSelectGEP(GEP, Builder))
2551 return R;
2552
2553 return nullptr;
2554}
2555
2556static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
2557 Instruction *AI) {
2558 if (isa<ConstantPointerNull>(V))
2559 return true;
2560 if (auto *LI = dyn_cast<LoadInst>(V))
2561 return isa<GlobalVariable>(LI->getPointerOperand());
2562 // Two distinct allocations will never be equal.
2563 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2564 // through bitcasts of V can cause
2565 // the result statement below to be true, even when AI and V (ex:
2566 // i8* ->i32* ->i8* of AI) are the same allocations.
2567 return isAllocLikeFn(V, TLI) && V != AI;
2568}
2569
2570static bool isAllocSiteRemovable(Instruction *AI,
2571 SmallVectorImpl<WeakTrackingVH> &Users,
2572 const TargetLibraryInfo *TLI) {
2573 SmallVector<Instruction*, 4> Worklist;
2574 Worklist.push_back(AI);
2575
2576 do {
2577 Instruction *PI = Worklist.pop_back_val();
2578 for (User *U : PI->users()) {
2579 Instruction *I = cast<Instruction>(U);
2580 switch (I->getOpcode()) {
2581 default:
2582 // Give up the moment we see something we can't handle.
2583 return false;
2584
2585 case Instruction::AddrSpaceCast:
2586 case Instruction::BitCast:
2587 case Instruction::GetElementPtr:
2588 Users.emplace_back(I);
2589 Worklist.push_back(I);
2590 continue;
2591
2592 case Instruction::ICmp: {
2593 ICmpInst *ICI = cast<ICmpInst>(I);
2594 // We can fold eq/ne comparisons with null to false/true, respectively.
2595 // We also fold comparisons in some conditions provided the alloc has
2596 // not escaped (see isNeverEqualToUnescapedAlloc).
2597 if (!ICI->isEquality())
2598 return false;
2599 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
2600 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
2601 return false;
2602 Users.emplace_back(I);
2603 continue;
2604 }
2605
2606 case Instruction::Call:
2607 // Ignore no-op and store intrinsics.
2608 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2609 switch (II->getIntrinsicID()) {
2610 default:
2611 return false;
2612
2613 case Intrinsic::memmove:
2614 case Intrinsic::memcpy:
2615 case Intrinsic::memset: {
2616 MemIntrinsic *MI = cast<MemIntrinsic>(II);
2617 if (MI->isVolatile() || MI->getRawDest() != PI)
2618 return false;
2619 LLVM_FALLTHROUGH[[gnu::fallthrough]];
2620 }
2621 case Intrinsic::assume:
2622 case Intrinsic::invariant_start:
2623 case Intrinsic::invariant_end:
2624 case Intrinsic::lifetime_start:
2625 case Intrinsic::lifetime_end:
2626 case Intrinsic::objectsize:
2627 Users.emplace_back(I);
2628 continue;
2629 case Intrinsic::launder_invariant_group:
2630 case Intrinsic::strip_invariant_group:
2631 Users.emplace_back(I);
2632 Worklist.push_back(I);
2633 continue;
2634 }
2635 }
2636
2637 if (isFreeCall(I, TLI)) {
2638 Users.emplace_back(I);
2639 continue;
2640 }
2641 return false;
2642
2643 case Instruction::Store: {
2644 StoreInst *SI = cast<StoreInst>(I);
2645 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2646 return false;
2647 Users.emplace_back(I);
2648 continue;
2649 }
2650 }
2651 llvm_unreachable("missing a return?")::llvm::llvm_unreachable_internal("missing a return?", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2651)
;
2652 }
2653 } while (!Worklist.empty());
2654 return true;
2655}
2656
2657Instruction *InstCombinerImpl::visitAllocSite(Instruction &MI) {
2658 // If we have a malloc call which is only used in any amount of comparisons to
2659 // null and free calls, delete the calls and replace the comparisons with true
2660 // or false as appropriate.
2661
2662 // This is based on the principle that we can substitute our own allocation
2663 // function (which will never return null) rather than knowledge of the
2664 // specific function being called. In some sense this can change the permitted
2665 // outputs of a program (when we convert a malloc to an alloca, the fact that
2666 // the allocation is now on the stack is potentially visible, for example),
2667 // but we believe in a permissible manner.
2668 SmallVector<WeakTrackingVH, 64> Users;
2669
2670 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2671 // before each store.
2672 SmallVector<DbgVariableIntrinsic *, 8> DVIs;
2673 std::unique_ptr<DIBuilder> DIB;
2674 if (isa<AllocaInst>(MI)) {
2675 findDbgUsers(DVIs, &MI);
2676 DIB.reset(new DIBuilder(*MI.getModule(), /*AllowUnresolved=*/false));
2677 }
2678
2679 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2680 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2681 // Lowering all @llvm.objectsize calls first because they may
2682 // use a bitcast/GEP of the alloca we are removing.
2683 if (!Users[i])
2684 continue;
2685
2686 Instruction *I = cast<Instruction>(&*Users[i]);
2687
2688 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2689 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2690 Value *Result =
2691 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/true);
2692 replaceInstUsesWith(*I, Result);
2693 eraseInstFromFunction(*I);
2694 Users[i] = nullptr; // Skip examining in the next loop.
2695 }
2696 }
2697 }
2698 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2699 if (!Users[i])
2700 continue;
2701
2702 Instruction *I = cast<Instruction>(&*Users[i]);
2703
2704 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2705 replaceInstUsesWith(*C,
2706 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2707 C->isFalseWhenEqual()));
2708 } else if (auto *SI = dyn_cast<StoreInst>(I)) {
2709 for (auto *DVI : DVIs)
2710 if (DVI->isAddressOfVariable())
2711 ConvertDebugDeclareToDebugValue(DVI, SI, *DIB);
2712 } else {
2713 // Casts, GEP, or anything else: we're about to delete this instruction,
2714 // so it can not have any valid uses.
2715 replaceInstUsesWith(*I, PoisonValue::get(I->getType()));
2716 }
2717 eraseInstFromFunction(*I);
2718 }
2719
2720 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2721 // Replace invoke with a NOP intrinsic to maintain the original CFG
2722 Module *M = II->getModule();
2723 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2724 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2725 None, "", II->getParent());
2726 }
2727
2728 // Remove debug intrinsics which describe the value contained within the
2729 // alloca. In addition to removing dbg.{declare,addr} which simply point to
2730 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
2731 //
2732 // ```
2733 // define void @foo(i32 %0) {
2734 // %a = alloca i32 ; Deleted.
2735 // store i32 %0, i32* %a
2736 // dbg.value(i32 %0, "arg0") ; Not deleted.
2737 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
2738 // call void @trivially_inlinable_no_op(i32* %a)
2739 // ret void
2740 // }
2741 // ```
2742 //
2743 // This may not be required if we stop describing the contents of allocas
2744 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
2745 // the LowerDbgDeclare utility.
2746 //
2747 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
2748 // "arg0" dbg.value may be stale after the call. However, failing to remove
2749 // the DW_OP_deref dbg.value causes large gaps in location coverage.
2750 for (auto *DVI : DVIs)
2751 if (DVI->isAddressOfVariable() || DVI->getExpression()->startsWithDeref())
2752 DVI->eraseFromParent();
2753
2754 return eraseInstFromFunction(MI);
2755 }
2756 return nullptr;
2757}
2758
2759/// Move the call to free before a NULL test.
2760///
2761/// Check if this free is accessed after its argument has been test
2762/// against NULL (property 0).
2763/// If yes, it is legal to move this call in its predecessor block.
2764///
2765/// The move is performed only if the block containing the call to free
2766/// will be removed, i.e.:
2767/// 1. it has only one predecessor P, and P has two successors
2768/// 2. it contains the call, noops, and an unconditional branch
2769/// 3. its successor is the same as its predecessor's successor
2770///
2771/// The profitability is out-of concern here and this function should
2772/// be called only if the caller knows this transformation would be
2773/// profitable (e.g., for code size).
2774static Instruction *tryToMoveFreeBeforeNullTest(CallInst &FI,
2775 const DataLayout &DL) {
2776 Value *Op = FI.getArgOperand(0);
2777 BasicBlock *FreeInstrBB = FI.getParent();
2778 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2779
2780 // Validate part of constraint #1: Only one predecessor
2781 // FIXME: We can extend the number of predecessor, but in that case, we
2782 // would duplicate the call to free in each predecessor and it may
2783 // not be profitable even for code size.
2784 if (!PredBB)
2785 return nullptr;
2786
2787 // Validate constraint #2: Does this block contains only the call to
2788 // free, noops, and an unconditional branch?
2789 BasicBlock *SuccBB;
2790 Instruction *FreeInstrBBTerminator = FreeInstrBB->getTerminator();
2791 if (!match(FreeInstrBBTerminator, m_UnconditionalBr(SuccBB)))
2792 return nullptr;
2793
2794 // If there are only 2 instructions in the block, at this point,
2795 // this is the call to free and unconditional.
2796 // If there are more than 2 instructions, check that they are noops
2797 // i.e., they won't hurt the performance of the generated code.
2798 if (FreeInstrBB->size() != 2) {
2799 for (const Instruction &Inst : FreeInstrBB->instructionsWithoutDebug()) {
2800 if (&Inst == &FI || &Inst == FreeInstrBBTerminator)
2801 continue;
2802 auto *Cast = dyn_cast<CastInst>(&Inst);
2803 if (!Cast || !Cast->isNoopCast(DL))
2804 return nullptr;
2805 }
2806 }
2807 // Validate the rest of constraint #1 by matching on the pred branch.
2808 Instruction *TI = PredBB->getTerminator();
2809 BasicBlock *TrueBB, *FalseBB;
2810 ICmpInst::Predicate Pred;
2811 if (!match(TI, m_Br(m_ICmp(Pred,
2812 m_CombineOr(m_Specific(Op),
2813 m_Specific(Op->stripPointerCasts())),
2814 m_Zero()),
2815 TrueBB, FalseBB)))
2816 return nullptr;
2817 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2818 return nullptr;
2819
2820 // Validate constraint #3: Ensure the null case just falls through.
2821 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2822 return nullptr;
2823 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&(static_cast <bool> (FreeInstrBB == (Pred == ICmpInst::
ICMP_EQ ? FalseBB : TrueBB) && "Broken CFG: missing edge from predecessor to successor"
) ? void (0) : __assert_fail ("FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && \"Broken CFG: missing edge from predecessor to successor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2824, __extension__ __PRETTY_FUNCTION__))
2824 "Broken CFG: missing edge from predecessor to successor")(static_cast <bool> (FreeInstrBB == (Pred == ICmpInst::
ICMP_EQ ? FalseBB : TrueBB) && "Broken CFG: missing edge from predecessor to successor"
) ? void (0) : __assert_fail ("FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) && \"Broken CFG: missing edge from predecessor to successor\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2824, __extension__ __PRETTY_FUNCTION__))
;
2825
2826 // At this point, we know that everything in FreeInstrBB can be moved
2827 // before TI.
2828 for (BasicBlock::iterator It = FreeInstrBB->begin(), End = FreeInstrBB->end();
2829 It != End;) {
2830 Instruction &Instr = *It++;
2831 if (&Instr == FreeInstrBBTerminator)
2832 break;
2833 Instr.moveBefore(TI);
2834 }
2835 assert(FreeInstrBB->size() == 1 &&(static_cast <bool> (FreeInstrBB->size() == 1 &&
"Only the branch instruction should remain") ? void (0) : __assert_fail
("FreeInstrBB->size() == 1 && \"Only the branch instruction should remain\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2836, __extension__ __PRETTY_FUNCTION__))
2836 "Only the branch instruction should remain")(static_cast <bool> (FreeInstrBB->size() == 1 &&
"Only the branch instruction should remain") ? void (0) : __assert_fail
("FreeInstrBB->size() == 1 && \"Only the branch instruction should remain\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2836, __extension__ __PRETTY_FUNCTION__))
;
2837 return &FI;
2838}
2839
2840Instruction *InstCombinerImpl::visitFree(CallInst &FI) {
2841 Value *Op = FI.getArgOperand(0);
2842
2843 // free undef -> unreachable.
2844 if (isa<UndefValue>(Op)) {
2845 // Leave a marker since we can't modify the CFG here.
2846 CreateNonTerminatorUnreachable(&FI);
2847 return eraseInstFromFunction(FI);
2848 }
2849
2850 // If we have 'free null' delete the instruction. This can happen in stl code
2851 // when lots of inlining happens.
2852 if (isa<ConstantPointerNull>(Op))
2853 return eraseInstFromFunction(FI);
2854
2855 // If we optimize for code size, try to move the call to free before the null
2856 // test so that simplify cfg can remove the empty block and dead code
2857 // elimination the branch. I.e., helps to turn something like:
2858 // if (foo) free(foo);
2859 // into
2860 // free(foo);
2861 //
2862 // Note that we can only do this for 'free' and not for any flavor of
2863 // 'operator delete'; there is no 'operator delete' symbol for which we are
2864 // permitted to invent a call, even if we're passing in a null pointer.
2865 if (MinimizeSize) {
2866 LibFunc Func;
2867 if (TLI.getLibFunc(FI, Func) && TLI.has(Func) && Func == LibFunc_free)
2868 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI, DL))
2869 return I;
2870 }
2871
2872 return nullptr;
2873}
2874
2875static bool isMustTailCall(Value *V) {
2876 if (auto *CI = dyn_cast<CallInst>(V))
2877 return CI->isMustTailCall();
2878 return false;
2879}
2880
2881Instruction *InstCombinerImpl::visitReturnInst(ReturnInst &RI) {
2882 if (RI.getNumOperands() == 0) // ret void
2883 return nullptr;
2884
2885 Value *ResultOp = RI.getOperand(0);
2886 Type *VTy = ResultOp->getType();
2887 if (!VTy->isIntegerTy() || isa<Constant>(ResultOp))
2888 return nullptr;
2889
2890 // Don't replace result of musttail calls.
2891 if (isMustTailCall(ResultOp))
2892 return nullptr;
2893
2894 // There might be assume intrinsics dominating this return that completely
2895 // determine the value. If so, constant fold it.
2896 KnownBits Known = computeKnownBits(ResultOp, 0, &RI);
2897 if (Known.isConstant())
2898 return replaceOperand(RI, 0,
2899 Constant::getIntegerValue(VTy, Known.getConstant()));
2900
2901 return nullptr;
2902}
2903
2904// WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
2905Instruction *InstCombinerImpl::visitUnreachableInst(UnreachableInst &I) {
2906 // Try to remove the previous instruction if it must lead to unreachable.
2907 // This includes instructions like stores and "llvm.assume" that may not get
2908 // removed by simple dead code elimination.
2909 while (Instruction *Prev = I.getPrevNonDebugInstruction()) {
2910 // While we theoretically can erase EH, that would result in a block that
2911 // used to start with an EH no longer starting with EH, which is invalid.
2912 // To make it valid, we'd need to fixup predecessors to no longer refer to
2913 // this block, but that changes CFG, which is not allowed in InstCombine.
2914 if (Prev->isEHPad())
2915 return nullptr; // Can not drop any more instructions. We're done here.
2916
2917 if (!isGuaranteedToTransferExecutionToSuccessor(Prev))
2918 return nullptr; // Can not drop any more instructions. We're done here.
2919 // Otherwise, this instruction can be freely erased,
2920 // even if it is not side-effect free.
2921
2922 // A value may still have uses before we process it here (for example, in
2923 // another unreachable block), so convert those to poison.
2924 replaceInstUsesWith(*Prev, PoisonValue::get(Prev->getType()));
2925 eraseInstFromFunction(*Prev);
2926 }
2927 assert(I.getParent()->sizeWithoutDebug() == 1 && "The block is now empty.")(static_cast <bool> (I.getParent()->sizeWithoutDebug
() == 1 && "The block is now empty.") ? void (0) : __assert_fail
("I.getParent()->sizeWithoutDebug() == 1 && \"The block is now empty.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2927, __extension__ __PRETTY_FUNCTION__))
;
2928 // FIXME: recurse into unconditional predecessors?
2929 return nullptr;
2930}
2931
2932Instruction *InstCombinerImpl::visitUnconditionalBranchInst(BranchInst &BI) {
2933 assert(BI.isUnconditional() && "Only for unconditional branches.")(static_cast <bool> (BI.isUnconditional() && "Only for unconditional branches."
) ? void (0) : __assert_fail ("BI.isUnconditional() && \"Only for unconditional branches.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 2933, __extension__ __PRETTY_FUNCTION__))
;
2934
2935 // If this store is the second-to-last instruction in the basic block
2936 // (excluding debug info and bitcasts of pointers) and if the block ends with
2937 // an unconditional branch, try to move the store to the successor block.
2938
2939 auto GetLastSinkableStore = [](BasicBlock::iterator BBI) {
2940 auto IsNoopInstrForStoreMerging = [](BasicBlock::iterator BBI) {
2941 return isa<DbgInfoIntrinsic>(BBI) ||
2942 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy());
2943 };
2944
2945 BasicBlock::iterator FirstInstr = BBI->getParent()->begin();
2946 do {
2947 if (BBI != FirstInstr)
2948 --BBI;
2949 } while (BBI != FirstInstr && IsNoopInstrForStoreMerging(BBI));
2950
2951 return dyn_cast<StoreInst>(BBI);
2952 };
2953
2954 if (StoreInst *SI = GetLastSinkableStore(BasicBlock::iterator(BI)))
2955 if (mergeStoreIntoSuccessor(*SI))
2956 return &BI;
2957
2958 return nullptr;
2959}
2960
2961Instruction *InstCombinerImpl::visitBranchInst(BranchInst &BI) {
2962 if (BI.isUnconditional())
2963 return visitUnconditionalBranchInst(BI);
2964
2965 // Change br (not X), label True, label False to: br X, label False, True
2966 Value *X = nullptr;
2967 if (match(&BI, m_Br(m_Not(m_Value(X)), m_BasicBlock(), m_BasicBlock())) &&
2968 !isa<Constant>(X)) {
2969 // Swap Destinations and condition...
2970 BI.swapSuccessors();
2971 return replaceOperand(BI, 0, X);
2972 }
2973
2974 // If the condition is irrelevant, remove the use so that other
2975 // transforms on the condition become more effective.
2976 if (!isa<ConstantInt>(BI.getCondition()) &&
2977 BI.getSuccessor(0) == BI.getSuccessor(1))
2978 return replaceOperand(
2979 BI, 0, ConstantInt::getFalse(BI.getCondition()->getType()));
2980
2981 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
2982 CmpInst::Predicate Pred;
2983 if (match(&BI, m_Br(m_OneUse(m_FCmp(Pred, m_Value(), m_Value())),
2984 m_BasicBlock(), m_BasicBlock())) &&
2985 !isCanonicalPredicate(Pred)) {
2986 // Swap destinations and condition.
2987 CmpInst *Cond = cast<CmpInst>(BI.getCondition());
2988 Cond->setPredicate(CmpInst::getInversePredicate(Pred));
2989 BI.swapSuccessors();
2990 Worklist.push(Cond);
2991 return &BI;
2992 }
2993
2994 return nullptr;
2995}
2996
2997Instruction *InstCombinerImpl::visitSwitchInst(SwitchInst &SI) {
2998 Value *Cond = SI.getCondition();
2999 Value *Op0;
3000 ConstantInt *AddRHS;
3001 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
3002 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
3003 for (auto Case : SI.cases()) {
3004 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
3005 assert(isa<ConstantInt>(NewCase) &&(static_cast <bool> (isa<ConstantInt>(NewCase) &&
"Result of expression should be constant") ? void (0) : __assert_fail
("isa<ConstantInt>(NewCase) && \"Result of expression should be constant\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3006, __extension__ __PRETTY_FUNCTION__))
3006 "Result of expression should be constant")(static_cast <bool> (isa<ConstantInt>(NewCase) &&
"Result of expression should be constant") ? void (0) : __assert_fail
("isa<ConstantInt>(NewCase) && \"Result of expression should be constant\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3006, __extension__ __PRETTY_FUNCTION__))
;
3007 Case.setValue(cast<ConstantInt>(NewCase));
3008 }
3009 return replaceOperand(SI, 0, Op0);
3010 }
3011
3012 KnownBits Known = computeKnownBits(Cond, 0, &SI);
3013 unsigned LeadingKnownZeros = Known.countMinLeadingZeros();
3014 unsigned LeadingKnownOnes = Known.countMinLeadingOnes();
3015
3016 // Compute the number of leading bits we can ignore.
3017 // TODO: A better way to determine this would use ComputeNumSignBits().
3018 for (auto &C : SI.cases()) {
3019 LeadingKnownZeros = std::min(
3020 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
3021 LeadingKnownOnes = std::min(
3022 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
3023 }
3024
3025 unsigned NewWidth = Known.getBitWidth() - std::max(LeadingKnownZeros, LeadingKnownOnes);
3026
3027 // Shrink the condition operand if the new type is smaller than the old type.
3028 // But do not shrink to a non-standard type, because backend can't generate
3029 // good code for that yet.
3030 // TODO: We can make it aggressive again after fixing PR39569.
3031 if (NewWidth > 0 && NewWidth < Known.getBitWidth() &&
3032 shouldChangeType(Known.getBitWidth(), NewWidth)) {
3033 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
3034 Builder.SetInsertPoint(&SI);
3035 Value *NewCond = Builder.CreateTrunc(Cond, Ty, "trunc");
3036
3037 for (auto Case : SI.cases()) {
3038 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
3039 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
3040 }
3041 return replaceOperand(SI, 0, NewCond);
3042 }
3043
3044 return nullptr;
3045}
3046
3047Instruction *InstCombinerImpl::visitExtractValueInst(ExtractValueInst &EV) {
3048 Value *Agg = EV.getAggregateOperand();
3049
3050 if (!EV.hasIndices())
3051 return replaceInstUsesWith(EV, Agg);
3052
3053 if (Value *V = SimplifyExtractValueInst(Agg, EV.getIndices(),
3054 SQ.getWithInstruction(&EV)))
3055 return replaceInstUsesWith(EV, V);
3056
3057 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
3058 // We're extracting from an insertvalue instruction, compare the indices
3059 const unsigned *exti, *exte, *insi, *inse;
3060 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
3061 exte = EV.idx_end(), inse = IV->idx_end();
3062 exti != exte && insi != inse;
3063 ++exti, ++insi) {
3064 if (*insi != *exti)
3065 // The insert and extract both reference distinctly different elements.
3066 // This means the extract is not influenced by the insert, and we can
3067 // replace the aggregate operand of the extract with the aggregate
3068 // operand of the insert. i.e., replace
3069 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3070 // %E = extractvalue { i32, { i32 } } %I, 0
3071 // with
3072 // %E = extractvalue { i32, { i32 } } %A, 0
3073 return ExtractValueInst::Create(IV->getAggregateOperand(),
3074 EV.getIndices());
3075 }
3076 if (exti == exte && insi == inse)
3077 // Both iterators are at the end: Index lists are identical. Replace
3078 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3079 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3080 // with "i32 42"
3081 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
3082 if (exti == exte) {
3083 // The extract list is a prefix of the insert list. i.e. replace
3084 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3085 // %E = extractvalue { i32, { i32 } } %I, 1
3086 // with
3087 // %X = extractvalue { i32, { i32 } } %A, 1
3088 // %E = insertvalue { i32 } %X, i32 42, 0
3089 // by switching the order of the insert and extract (though the
3090 // insertvalue should be left in, since it may have other uses).
3091 Value *NewEV = Builder.CreateExtractValue(IV->getAggregateOperand(),
3092 EV.getIndices());
3093 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
3094 makeArrayRef(insi, inse));
3095 }
3096 if (insi == inse)
3097 // The insert list is a prefix of the extract list
3098 // We can simply remove the common indices from the extract and make it
3099 // operate on the inserted value instead of the insertvalue result.
3100 // i.e., replace
3101 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3102 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3103 // with
3104 // %E extractvalue { i32 } { i32 42 }, 0
3105 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
3106 makeArrayRef(exti, exte));
3107 }
3108 if (WithOverflowInst *WO = dyn_cast<WithOverflowInst>(Agg)) {
3109 // We're extracting from an overflow intrinsic, see if we're the only user,
3110 // which allows us to simplify multiple result intrinsics to simpler
3111 // things that just get one value.
3112 if (WO->hasOneUse()) {
3113 // Check if we're grabbing only the result of a 'with overflow' intrinsic
3114 // and replace it with a traditional binary instruction.
3115 if (*EV.idx_begin() == 0) {
3116 Instruction::BinaryOps BinOp = WO->getBinaryOp();
3117 Value *LHS = WO->getLHS(), *RHS = WO->getRHS();
3118 // Replace the old instruction's uses with poison.
3119 replaceInstUsesWith(*WO, PoisonValue::get(WO->getType()));
3120 eraseInstFromFunction(*WO);
3121 return BinaryOperator::Create(BinOp, LHS, RHS);
3122 }
3123
3124 assert(*EV.idx_begin() == 1 &&(static_cast <bool> (*EV.idx_begin() == 1 && "unexpected extract index for overflow inst"
) ? void (0) : __assert_fail ("*EV.idx_begin() == 1 && \"unexpected extract index for overflow inst\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3125, __extension__ __PRETTY_FUNCTION__))
3125 "unexpected extract index for overflow inst")(static_cast <bool> (*EV.idx_begin() == 1 && "unexpected extract index for overflow inst"
) ? void (0) : __assert_fail ("*EV.idx_begin() == 1 && \"unexpected extract index for overflow inst\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3125, __extension__ __PRETTY_FUNCTION__))
;
3126
3127 // If only the overflow result is used, and the right hand side is a
3128 // constant (or constant splat), we can remove the intrinsic by directly
3129 // checking for overflow.
3130 const APInt *C;
3131 if (match(WO->getRHS(), m_APInt(C))) {
3132 // Compute the no-wrap range [X,Y) for LHS given RHS=C, then
3133 // check for the inverted range using range offset trick (i.e.
3134 // use a subtract to shift the range to bottom of either the
3135 // signed or unsigned domain and then use a single compare to
3136 // check range membership).
3137 ConstantRange NWR =
3138 ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
3139 WO->getNoWrapKind());
3140 APInt Min = WO->isSigned() ? NWR.getSignedMin() : NWR.getUnsignedMin();
3141 NWR = NWR.subtract(Min);
3142
3143 CmpInst::Predicate Pred;
3144 APInt NewRHSC;
3145 if (NWR.getEquivalentICmp(Pred, NewRHSC)) {
3146 auto *OpTy = WO->getRHS()->getType();
3147 auto *NewLHS = Builder.CreateSub(WO->getLHS(),
3148 ConstantInt::get(OpTy, Min));
3149 return new ICmpInst(ICmpInst::getInversePredicate(Pred), NewLHS,
3150 ConstantInt::get(OpTy, NewRHSC));
3151 }
3152 }
3153 }
3154 }
3155 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
3156 // If the (non-volatile) load only has one use, we can rewrite this to a
3157 // load from a GEP. This reduces the size of the load. If a load is used
3158 // only by extractvalue instructions then this either must have been
3159 // optimized before, or it is a struct with padding, in which case we
3160 // don't want to do the transformation as it loses padding knowledge.
3161 if (L->isSimple() && L->hasOneUse()) {
3162 // extractvalue has integer indices, getelementptr has Value*s. Convert.
3163 SmallVector<Value*, 4> Indices;
3164 // Prefix an i32 0 since we need the first element.
3165 Indices.push_back(Builder.getInt32(0));
3166 for (unsigned Idx : EV.indices())
3167 Indices.push_back(Builder.getInt32(Idx));
3168
3169 // We need to insert these at the location of the old load, not at that of
3170 // the extractvalue.
3171 Builder.SetInsertPoint(L);
3172 Value *GEP = Builder.CreateInBoundsGEP(L->getType(),
3173 L->getPointerOperand(), Indices);
3174 Instruction *NL = Builder.CreateLoad(EV.getType(), GEP);
3175 // Whatever aliasing information we had for the orignal load must also
3176 // hold for the smaller load, so propagate the annotations.
3177 AAMDNodes Nodes;
3178 L->getAAMetadata(Nodes);
3179 NL->setAAMetadata(Nodes);
3180 // Returning the load directly will cause the main loop to insert it in
3181 // the wrong spot, so use replaceInstUsesWith().
3182 return replaceInstUsesWith(EV, NL);
3183 }
3184 // We could simplify extracts from other values. Note that nested extracts may
3185 // already be simplified implicitly by the above: extract (extract (insert) )
3186 // will be translated into extract ( insert ( extract ) ) first and then just
3187 // the value inserted, if appropriate. Similarly for extracts from single-use
3188 // loads: extract (extract (load)) will be translated to extract (load (gep))
3189 // and if again single-use then via load (gep (gep)) to load (gep).
3190 // However, double extracts from e.g. function arguments or return values
3191 // aren't handled yet.
3192 return nullptr;
3193}
3194
3195/// Return 'true' if the given typeinfo will match anything.
3196static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
3197 switch (Personality) {
3198 case EHPersonality::GNU_C:
3199 case EHPersonality::GNU_C_SjLj:
3200 case EHPersonality::Rust:
3201 // The GCC C EH and Rust personality only exists to support cleanups, so
3202 // it's not clear what the semantics of catch clauses are.
3203 return false;
3204 case EHPersonality::Unknown:
3205 return false;
3206 case EHPersonality::GNU_Ada:
3207 // While __gnat_all_others_value will match any Ada exception, it doesn't
3208 // match foreign exceptions (or didn't, before gcc-4.7).
3209 return false;
3210 case EHPersonality::GNU_CXX:
3211 case EHPersonality::GNU_CXX_SjLj:
3212 case EHPersonality::GNU_ObjC:
3213 case EHPersonality::MSVC_X86SEH:
3214 case EHPersonality::MSVC_TableSEH:
3215 case EHPersonality::MSVC_CXX:
3216 case EHPersonality::CoreCLR:
3217 case EHPersonality::Wasm_CXX:
3218 case EHPersonality::XL_CXX:
3219 return TypeInfo->isNullValue();
3220 }
3221 llvm_unreachable("invalid enum")::llvm::llvm_unreachable_internal("invalid enum", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3221)
;
3222}
3223
3224static bool shorter_filter(const Value *LHS, const Value *RHS) {
3225 return
3226 cast<ArrayType>(LHS->getType())->getNumElements()
3227 <
3228 cast<ArrayType>(RHS->getType())->getNumElements();
3229}
3230
3231Instruction *InstCombinerImpl::visitLandingPadInst(LandingPadInst &LI) {
3232 // The logic here should be correct for any real-world personality function.
3233 // However if that turns out not to be true, the offending logic can always
3234 // be conditioned on the personality function, like the catch-all logic is.
3235 EHPersonality Personality =
3236 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
3237
3238 // Simplify the list of clauses, eg by removing repeated catch clauses
3239 // (these are often created by inlining).
3240 bool MakeNewInstruction = false; // If true, recreate using the following:
3241 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
3242 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
3243
3244 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
3245 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
3246 bool isLastClause = i + 1 == e;
3247 if (LI.isCatch(i)) {
3248 // A catch clause.
3249 Constant *CatchClause = LI.getClause(i);
3250 Constant *TypeInfo = CatchClause->stripPointerCasts();
3251
3252 // If we already saw this clause, there is no point in having a second
3253 // copy of it.
3254 if (AlreadyCaught.insert(TypeInfo).second) {
3255 // This catch clause was not already seen.
3256 NewClauses.push_back(CatchClause);
3257 } else {
3258 // Repeated catch clause - drop the redundant copy.
3259 MakeNewInstruction = true;
3260 }
3261
3262 // If this is a catch-all then there is no point in keeping any following
3263 // clauses or marking the landingpad as having a cleanup.
3264 if (isCatchAll(Personality, TypeInfo)) {
3265 if (!isLastClause)
3266 MakeNewInstruction = true;
3267 CleanupFlag = false;
3268 break;
3269 }
3270 } else {
3271 // A filter clause. If any of the filter elements were already caught
3272 // then they can be dropped from the filter. It is tempting to try to
3273 // exploit the filter further by saying that any typeinfo that does not
3274 // occur in the filter can't be caught later (and thus can be dropped).
3275 // However this would be wrong, since typeinfos can match without being
3276 // equal (for example if one represents a C++ class, and the other some
3277 // class derived from it).
3278 assert(LI.isFilter(i) && "Unsupported landingpad clause!")(static_cast <bool> (LI.isFilter(i) && "Unsupported landingpad clause!"
) ? void (0) : __assert_fail ("LI.isFilter(i) && \"Unsupported landingpad clause!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3278, __extension__ __PRETTY_FUNCTION__))
;
3279 Constant *FilterClause = LI.getClause(i);
3280 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
3281 unsigned NumTypeInfos = FilterType->getNumElements();
3282
3283 // An empty filter catches everything, so there is no point in keeping any
3284 // following clauses or marking the landingpad as having a cleanup. By
3285 // dealing with this case here the following code is made a bit simpler.
3286 if (!NumTypeInfos) {
3287 NewClauses.push_back(FilterClause);
3288 if (!isLastClause)
3289 MakeNewInstruction = true;
3290 CleanupFlag = false;
3291 break;
3292 }
3293
3294 bool MakeNewFilter = false; // If true, make a new filter.
3295 SmallVector<Constant *, 16> NewFilterElts; // New elements.
3296 if (isa<ConstantAggregateZero>(FilterClause)) {
3297 // Not an empty filter - it contains at least one null typeinfo.
3298 assert(NumTypeInfos > 0 && "Should have handled empty filter already!")(static_cast <bool> (NumTypeInfos > 0 && "Should have handled empty filter already!"
) ? void (0) : __assert_fail ("NumTypeInfos > 0 && \"Should have handled empty filter already!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3298, __extension__ __PRETTY_FUNCTION__))
;
3299 Constant *TypeInfo =
3300 Constant::getNullValue(FilterType->getElementType());
3301 // If this typeinfo is a catch-all then the filter can never match.
3302 if (isCatchAll(Personality, TypeInfo)) {
3303 // Throw the filter away.
3304 MakeNewInstruction = true;
3305 continue;
3306 }
3307
3308 // There is no point in having multiple copies of this typeinfo, so
3309 // discard all but the first copy if there is more than one.
3310 NewFilterElts.push_back(TypeInfo);
3311 if (NumTypeInfos > 1)
3312 MakeNewFilter = true;
3313 } else {
3314 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
3315 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
3316 NewFilterElts.reserve(NumTypeInfos);
3317
3318 // Remove any filter elements that were already caught or that already
3319 // occurred in the filter. While there, see if any of the elements are
3320 // catch-alls. If so, the filter can be discarded.
3321 bool SawCatchAll = false;
3322 for (unsigned j = 0; j != NumTypeInfos; ++j) {
3323 Constant *Elt = Filter->getOperand(j);
3324 Constant *TypeInfo = Elt->stripPointerCasts();
3325 if (isCatchAll(Personality, TypeInfo)) {
3326 // This element is a catch-all. Bail out, noting this fact.
3327 SawCatchAll = true;
3328 break;
3329 }
3330
3331 // Even if we've seen a type in a catch clause, we don't want to
3332 // remove it from the filter. An unexpected type handler may be
3333 // set up for a call site which throws an exception of the same
3334 // type caught. In order for the exception thrown by the unexpected
3335 // handler to propagate correctly, the filter must be correctly
3336 // described for the call site.
3337 //
3338 // Example:
3339 //
3340 // void unexpected() { throw 1;}
3341 // void foo() throw (int) {
3342 // std::set_unexpected(unexpected);
3343 // try {
3344 // throw 2.0;
3345 // } catch (int i) {}
3346 // }
3347
3348 // There is no point in having multiple copies of the same typeinfo in
3349 // a filter, so only add it if we didn't already.
3350 if (SeenInFilter.insert(TypeInfo).second)
3351 NewFilterElts.push_back(cast<Constant>(Elt));
3352 }
3353 // A filter containing a catch-all cannot match anything by definition.
3354 if (SawCatchAll) {
3355 // Throw the filter away.
3356 MakeNewInstruction = true;
3357 continue;
3358 }
3359
3360 // If we dropped something from the filter, make a new one.
3361 if (NewFilterElts.size() < NumTypeInfos)
3362 MakeNewFilter = true;
3363 }
3364 if (MakeNewFilter) {
3365 FilterType = ArrayType::get(FilterType->getElementType(),
3366 NewFilterElts.size());
3367 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
3368 MakeNewInstruction = true;
3369 }
3370
3371 NewClauses.push_back(FilterClause);
3372
3373 // If the new filter is empty then it will catch everything so there is
3374 // no point in keeping any following clauses or marking the landingpad
3375 // as having a cleanup. The case of the original filter being empty was
3376 // already handled above.
3377 if (MakeNewFilter && !NewFilterElts.size()) {
3378 assert(MakeNewInstruction && "New filter but not a new instruction!")(static_cast <bool> (MakeNewInstruction && "New filter but not a new instruction!"
) ? void (0) : __assert_fail ("MakeNewInstruction && \"New filter but not a new instruction!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3378, __extension__ __PRETTY_FUNCTION__))
;
3379 CleanupFlag = false;
3380 break;
3381 }
3382 }
3383 }
3384
3385 // If several filters occur in a row then reorder them so that the shortest
3386 // filters come first (those with the smallest number of elements). This is
3387 // advantageous because shorter filters are more likely to match, speeding up
3388 // unwinding, but mostly because it increases the effectiveness of the other
3389 // filter optimizations below.
3390 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
3391 unsigned j;
3392 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3393 for (j = i; j != e; ++j)
3394 if (!isa<ArrayType>(NewClauses[j]->getType()))
3395 break;
3396
3397 // Check whether the filters are already sorted by length. We need to know
3398 // if sorting them is actually going to do anything so that we only make a
3399 // new landingpad instruction if it does.
3400 for (unsigned k = i; k + 1 < j; ++k)
3401 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
3402 // Not sorted, so sort the filters now. Doing an unstable sort would be
3403 // correct too but reordering filters pointlessly might confuse users.
3404 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
3405 shorter_filter);
3406 MakeNewInstruction = true;
3407 break;
3408 }
3409
3410 // Look for the next batch of filters.
3411 i = j + 1;
3412 }
3413
3414 // If typeinfos matched if and only if equal, then the elements of a filter L
3415 // that occurs later than a filter F could be replaced by the intersection of
3416 // the elements of F and L. In reality two typeinfos can match without being
3417 // equal (for example if one represents a C++ class, and the other some class
3418 // derived from it) so it would be wrong to perform this transform in general.
3419 // However the transform is correct and useful if F is a subset of L. In that
3420 // case L can be replaced by F, and thus removed altogether since repeating a
3421 // filter is pointless. So here we look at all pairs of filters F and L where
3422 // L follows F in the list of clauses, and remove L if every element of F is
3423 // an element of L. This can occur when inlining C++ functions with exception
3424 // specifications.
3425 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
3426 // Examine each filter in turn.
3427 Value *Filter = NewClauses[i];
3428 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
3429 if (!FTy)
3430 // Not a filter - skip it.
3431 continue;
3432 unsigned FElts = FTy->getNumElements();
3433 // Examine each filter following this one. Doing this backwards means that
3434 // we don't have to worry about filters disappearing under us when removed.
3435 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
3436 Value *LFilter = NewClauses[j];
3437 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
3438 if (!LTy)
3439 // Not a filter - skip it.
3440 continue;
3441 // If Filter is a subset of LFilter, i.e. every element of Filter is also
3442 // an element of LFilter, then discard LFilter.
3443 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
3444 // If Filter is empty then it is a subset of LFilter.
3445 if (!FElts) {
3446 // Discard LFilter.
3447 NewClauses.erase(J);
3448 MakeNewInstruction = true;
3449 // Move on to the next filter.
3450 continue;
3451 }
3452 unsigned LElts = LTy->getNumElements();
3453 // If Filter is longer than LFilter then it cannot be a subset of it.
3454 if (FElts > LElts)
3455 // Move on to the next filter.
3456 continue;
3457 // At this point we know that LFilter has at least one element.
3458 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
3459 // Filter is a subset of LFilter iff Filter contains only zeros (as we
3460 // already know that Filter is not longer than LFilter).
3461 if (isa<ConstantAggregateZero>(Filter)) {
3462 assert(FElts <= LElts && "Should have handled this case earlier!")(static_cast <bool> (FElts <= LElts && "Should have handled this case earlier!"
) ? void (0) : __assert_fail ("FElts <= LElts && \"Should have handled this case earlier!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3462, __extension__ __PRETTY_FUNCTION__))
;
3463 // Discard LFilter.
3464 NewClauses.erase(J);
3465 MakeNewInstruction = true;
3466 }
3467 // Move on to the next filter.
3468 continue;
3469 }
3470 ConstantArray *LArray = cast<ConstantArray>(LFilter);
3471 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
3472 // Since Filter is non-empty and contains only zeros, it is a subset of
3473 // LFilter iff LFilter contains a zero.
3474 assert(FElts > 0 && "Should have eliminated the empty filter earlier!")(static_cast <bool> (FElts > 0 && "Should have eliminated the empty filter earlier!"
) ? void (0) : __assert_fail ("FElts > 0 && \"Should have eliminated the empty filter earlier!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3474, __extension__ __PRETTY_FUNCTION__))
;
3475 for (unsigned l = 0; l != LElts; ++l)
3476 if (LArray->getOperand(l)->isNullValue()) {
3477 // LFilter contains a zero - discard it.
3478 NewClauses.erase(J);
3479 MakeNewInstruction = true;
3480 break;
3481 }
3482 // Move on to the next filter.
3483 continue;
3484 }
3485 // At this point we know that both filters are ConstantArrays. Loop over
3486 // operands to see whether every element of Filter is also an element of
3487 // LFilter. Since filters tend to be short this is probably faster than
3488 // using a method that scales nicely.
3489 ConstantArray *FArray = cast<ConstantArray>(Filter);
3490 bool AllFound = true;
3491 for (unsigned f = 0; f != FElts; ++f) {
3492 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
3493 AllFound = false;
3494 for (unsigned l = 0; l != LElts; ++l) {
3495 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
3496 if (LTypeInfo == FTypeInfo) {
3497 AllFound = true;
3498 break;
3499 }
3500 }
3501 if (!AllFound)
3502 break;
3503 }
3504 if (AllFound) {
3505 // Discard LFilter.
3506 NewClauses.erase(J);
3507 MakeNewInstruction = true;
3508 }
3509 // Move on to the next filter.
3510 }
3511 }
3512
3513 // If we changed any of the clauses, replace the old landingpad instruction
3514 // with a new one.
3515 if (MakeNewInstruction) {
3516 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
3517 NewClauses.size());
3518 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
3519 NLI->addClause(NewClauses[i]);
3520 // A landing pad with no clauses must have the cleanup flag set. It is
3521 // theoretically possible, though highly unlikely, that we eliminated all
3522 // clauses. If so, force the cleanup flag to true.
3523 if (NewClauses.empty())
3524 CleanupFlag = true;
3525 NLI->setCleanup(CleanupFlag);
3526 return NLI;
3527 }
3528
3529 // Even if none of the clauses changed, we may nonetheless have understood
3530 // that the cleanup flag is pointless. Clear it if so.
3531 if (LI.isCleanup() != CleanupFlag) {
3532 assert(!CleanupFlag && "Adding a cleanup, not removing one?!")(static_cast <bool> (!CleanupFlag && "Adding a cleanup, not removing one?!"
) ? void (0) : __assert_fail ("!CleanupFlag && \"Adding a cleanup, not removing one?!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3532, __extension__ __PRETTY_FUNCTION__))
;
3533 LI.setCleanup(CleanupFlag);
3534 return &LI;
3535 }
3536
3537 return nullptr;
3538}
3539
3540Value *
3541InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst &OrigFI) {
3542 // Try to push freeze through instructions that propagate but don't produce
3543 // poison as far as possible. If an operand of freeze follows three
3544 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
3545 // guaranteed-non-poison operands then push the freeze through to the one
3546 // operand that is not guaranteed non-poison. The actual transform is as
3547 // follows.
3548 // Op1 = ... ; Op1 can be posion
3549 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
3550 // ; single guaranteed-non-poison operands
3551 // ... = Freeze(Op0)
3552 // =>
3553 // Op1 = ...
3554 // Op1.fr = Freeze(Op1)
3555 // ... = Inst(Op1.fr, NonPoisonOps...)
3556 auto *OrigOp = OrigFI.getOperand(0);
3557 auto *OrigOpInst = dyn_cast<Instruction>(OrigOp);
3558
3559 // While we could change the other users of OrigOp to use freeze(OrigOp), that
3560 // potentially reduces their optimization potential, so let's only do this iff
3561 // the OrigOp is only used by the freeze.
3562 if (!OrigOpInst || !OrigOpInst->hasOneUse() || isa<PHINode>(OrigOp) ||
6
Assuming 'OrigOpInst' is null
3563 canCreateUndefOrPoison(dyn_cast<Operator>(OrigOp)))
3564 return nullptr;
7
Returning null pointer, which participates in a condition later
3565
3566 // If operand is guaranteed not to be poison, there is no need to add freeze
3567 // to the operand. So we first find the operand that is not guaranteed to be
3568 // poison.
3569 Use *MaybePoisonOperand = nullptr;
3570 for (Use &U : OrigOpInst->operands()) {
3571 if (isGuaranteedNotToBeUndefOrPoison(U.get()))
3572 continue;
3573 if (!MaybePoisonOperand)
3574 MaybePoisonOperand = &U;
3575 else
3576 return nullptr;
3577 }
3578
3579 // If all operands are guaranteed to be non-poison, we can drop freeze.
3580 if (!MaybePoisonOperand)
3581 return OrigOp;
3582
3583 auto *FrozenMaybePoisonOperand = new FreezeInst(
3584 MaybePoisonOperand->get(), MaybePoisonOperand->get()->getName() + ".fr");
3585
3586 replaceUse(*MaybePoisonOperand, FrozenMaybePoisonOperand);
3587 FrozenMaybePoisonOperand->insertBefore(OrigOpInst);
3588 return OrigOp;
3589}
3590
3591bool InstCombinerImpl::freezeDominatedUses(FreezeInst &FI) {
3592 Value *Op = FI.getOperand(0);
3593
3594 if (isa<Constant>(Op))
3595 return false;
3596
3597 bool Changed = false;
3598 Op->replaceUsesWithIf(&FI, [&](Use &U) -> bool {
3599 bool Dominates = DT.dominates(&FI, U);
3600 Changed |= Dominates;
3601 return Dominates;
3602 });
3603
3604 return Changed;
3605}
3606
3607Instruction *InstCombinerImpl::visitFreeze(FreezeInst &I) {
3608 Value *Op0 = I.getOperand(0);
3609
3610 if (Value *V = SimplifyFreezeInst(Op0, SQ.getWithInstruction(&I)))
1
Assuming 'V' is null
2
Taking false branch
3611 return replaceInstUsesWith(I, V);
3612
3613 // freeze (phi const, x) --> phi const, (freeze x)
3614 if (auto *PN = dyn_cast<PHINode>(Op0)) {
3
Assuming 'PN' is null
4
Taking false branch
3615 if (Instruction *NV = foldOpIntoPhi(I, PN))
3616 return NV;
3617 }
3618
3619 if (Value *NI
8.1
'NI' is null
8.1
'NI' is null
8.1
'NI' is null
= pushFreezeToPreventPoisonFromPropagating(I))
5
Calling 'InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating'
8
Returning from 'InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating'
9
Taking false branch
3620 return replaceInstUsesWith(I, NI);
3621
3622 if (match(Op0, m_Undef())) {
10
Assuming the condition is true
11
Taking true branch
3623 // If I is freeze(undef), see its uses and fold it to the best constant.
3624 // - or: pick -1
3625 // - select's condition: pick the value that leads to choosing a constant
3626 // - other ops: pick 0
3627 Constant *BestValue = nullptr;
12
'BestValue' initialized to a null pointer value
3628 Constant *NullValue = Constant::getNullValue(I.getType());
3629 for (const auto *U : I.users()) {
3630 Constant *C = NullValue;
3631
3632 if (match(U, m_Or(m_Value(), m_Value())))
3633 C = Constant::getAllOnesValue(I.getType());
3634 else if (const auto *SI = dyn_cast<SelectInst>(U)) {
3635 if (SI->getCondition() == &I) {
3636 APInt CondVal(1, isa<Constant>(SI->getFalseValue()) ? 0 : 1);
3637 C = Constant::getIntegerValue(I.getType(), CondVal);
3638 }
3639 }
3640
3641 if (!BestValue)
3642 BestValue = C;
3643 else if (BestValue != C)
3644 BestValue = NullValue;
3645 }
3646
3647 return replaceInstUsesWith(I, BestValue);
13
Passing null pointer value via 2nd parameter 'V'
14
Calling 'InstCombinerImpl::replaceInstUsesWith'
3648 }
3649
3650 // Replace all dominated uses of Op to freeze(Op).
3651 if (freezeDominatedUses(I))
3652 return &I;
3653
3654 return nullptr;
3655}
3656
3657/// Try to move the specified instruction from its current block into the
3658/// beginning of DestBlock, which can only happen if it's safe to move the
3659/// instruction past all of the instructions between it and the end of its
3660/// block.
3661static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
3662 assert(I->getSingleUndroppableUse() && "Invariants didn't hold!")(static_cast <bool> (I->getSingleUndroppableUse() &&
"Invariants didn't hold!") ? void (0) : __assert_fail ("I->getSingleUndroppableUse() && \"Invariants didn't hold!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3662, __extension__ __PRETTY_FUNCTION__))
;
3663 BasicBlock *SrcBlock = I->getParent();
3664
3665 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3666 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
3667 I->isTerminator())
3668 return false;
3669
3670 // Do not sink static or dynamic alloca instructions. Static allocas must
3671 // remain in the entry block, and dynamic allocas must not be sunk in between
3672 // a stacksave / stackrestore pair, which would incorrectly shorten its
3673 // lifetime.
3674 if (isa<AllocaInst>(I))
3675 return false;
3676
3677 // Do not sink into catchswitch blocks.
3678 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
3679 return false;
3680
3681 // Do not sink convergent call instructions.
3682 if (auto *CI = dyn_cast<CallInst>(I)) {
3683 if (CI->isConvergent())
3684 return false;
3685 }
3686 // We can only sink load instructions if there is nothing between the load and
3687 // the end of block that could change the value.
3688 if (I->mayReadFromMemory()) {
3689 // We don't want to do any sophisticated alias analysis, so we only check
3690 // the instructions after I in I's parent block if we try to sink to its
3691 // successor block.
3692 if (DestBlock->getUniquePredecessor() != I->getParent())
3693 return false;
3694 for (BasicBlock::iterator Scan = I->getIterator(),
3695 E = I->getParent()->end();
3696 Scan != E; ++Scan)
3697 if (Scan->mayWriteToMemory())
3698 return false;
3699 }
3700
3701 I->dropDroppableUses([DestBlock](const Use *U) {
3702 if (auto *I = dyn_cast<Instruction>(U->getUser()))
3703 return I->getParent() != DestBlock;
3704 return true;
3705 });
3706 /// FIXME: We could remove droppable uses that are not dominated by
3707 /// the new position.
3708
3709 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
3710 I->moveBefore(&*InsertPos);
3711 ++NumSunkInst;
3712
3713 // Also sink all related debug uses from the source basic block. Otherwise we
3714 // get debug use before the def. Attempt to salvage debug uses first, to
3715 // maximise the range variables have location for. If we cannot salvage, then
3716 // mark the location undef: we know it was supposed to receive a new location
3717 // here, but that computation has been sunk.
3718 SmallVector<DbgVariableIntrinsic *, 2> DbgUsers;
3719 findDbgUsers(DbgUsers, I);
3720 // Process the sinking DbgUsers in reverse order, as we only want to clone the
3721 // last appearing debug intrinsic for each given variable.
3722 SmallVector<DbgVariableIntrinsic *, 2> DbgUsersToSink;
3723 for (DbgVariableIntrinsic *DVI : DbgUsers)
3724 if (DVI->getParent() == SrcBlock)
3725 DbgUsersToSink.push_back(DVI);
3726 llvm::sort(DbgUsersToSink,
3727 [](auto *A, auto *B) { return B->comesBefore(A); });
3728
3729 SmallVector<DbgVariableIntrinsic *, 2> DIIClones;
3730 SmallSet<DebugVariable, 4> SunkVariables;
3731 for (auto User : DbgUsersToSink) {
3732 // A dbg.declare instruction should not be cloned, since there can only be
3733 // one per variable fragment. It should be left in the original place
3734 // because the sunk instruction is not an alloca (otherwise we could not be
3735 // here).
3736 if (isa<DbgDeclareInst>(User))
3737 continue;
3738
3739 DebugVariable DbgUserVariable =
3740 DebugVariable(User->getVariable(), User->getExpression(),
3741 User->getDebugLoc()->getInlinedAt());
3742
3743 if (!SunkVariables.insert(DbgUserVariable).second)
3744 continue;
3745
3746 DIIClones.emplace_back(cast<DbgVariableIntrinsic>(User->clone()));
3747 if (isa<DbgDeclareInst>(User) && isa<CastInst>(I))
3748 DIIClones.back()->replaceVariableLocationOp(I, I->getOperand(0));
3749 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones.back() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "CLONE: " << *DIIClones
.back() << '\n'; } } while (false)
;
3750 }
3751
3752 // Perform salvaging without the clones, then sink the clones.
3753 if (!DIIClones.empty()) {
3754 salvageDebugInfoForDbgValues(*I, DbgUsers);
3755 // The clones are in reverse order of original appearance, reverse again to
3756 // maintain the original order.
3757 for (auto &DIIClone : llvm::reverse(DIIClones)) {
3758 DIIClone->insertBefore(&*InsertPos);
3759 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "SINK: " << *DIIClone
<< '\n'; } } while (false)
;
3760 }
3761 }
3762
3763 return true;
3764}
3765
3766bool InstCombinerImpl::run() {
3767 while (!Worklist.isEmpty()) {
3768 // Walk deferred instructions in reverse order, and push them to the
3769 // worklist, which means they'll end up popped from the worklist in-order.
3770 while (Instruction *I = Worklist.popDeferred()) {
3771 // Check to see if we can DCE the instruction. We do this already here to
3772 // reduce the number of uses and thus allow other folds to trigger.
3773 // Note that eraseInstFromFunction() may push additional instructions on
3774 // the deferred worklist, so this will DCE whole instruction chains.
3775 if (isInstructionTriviallyDead(I, &TLI)) {
3776 eraseInstFromFunction(*I);
3777 ++NumDeadInst;
3778 continue;
3779 }
3780
3781 Worklist.push(I);
3782 }
3783
3784 Instruction *I = Worklist.removeOne();
3785 if (I == nullptr) continue; // skip null values.
3786
3787 // Check to see if we can DCE the instruction.
3788 if (isInstructionTriviallyDead(I, &TLI)) {
3789 eraseInstFromFunction(*I);
3790 ++NumDeadInst;
3791 continue;
3792 }
3793
3794 if (!DebugCounter::shouldExecute(VisitCounter))
3795 continue;
3796
3797 // Instruction isn't dead, see if we can constant propagate it.
3798 if (!I->use_empty() &&
3799 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
3800 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
3801 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Ido { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold to: " <<
*C << " from: " << *I << '\n'; } } while (
false)
3802 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold to: " <<
*C << " from: " << *I << '\n'; } } while (
false)
;
3803
3804 // Add operands to the worklist.
3805 replaceInstUsesWith(*I, C);
3806 ++NumConstProp;
3807 if (isInstructionTriviallyDead(I, &TLI))
3808 eraseInstFromFunction(*I);
3809 MadeIRChange = true;
3810 continue;
3811 }
3812 }
3813
3814 // See if we can trivially sink this instruction to its user if we can
3815 // prove that the successor is not executed more frequently than our block.
3816 if (EnableCodeSinking)
3817 if (Use *SingleUse = I->getSingleUndroppableUse()) {
3818 BasicBlock *BB = I->getParent();
3819 Instruction *UserInst = cast<Instruction>(SingleUse->getUser());
3820 BasicBlock *UserParent;
3821
3822 // Get the block the use occurs in.
3823 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
3824 UserParent = PN->getIncomingBlock(*SingleUse);
3825 else
3826 UserParent = UserInst->getParent();
3827
3828 // Try sinking to another block. If that block is unreachable, then do
3829 // not bother. SimplifyCFG should handle it.
3830 if (UserParent != BB && DT.isReachableFromEntry(UserParent)) {
3831 // See if the user is one of our successors that has only one
3832 // predecessor, so that we don't have to split the critical edge.
3833 bool ShouldSink = UserParent->getUniquePredecessor() == BB;
3834 // Another option where we can sink is a block that ends with a
3835 // terminator that does not pass control to other block (such as
3836 // return or unreachable). In this case:
3837 // - I dominates the User (by SSA form);
3838 // - the User will be executed at most once.
3839 // So sinking I down to User is always profitable or neutral.
3840 if (!ShouldSink) {
3841 auto *Term = UserParent->getTerminator();
3842 ShouldSink = isa<ReturnInst>(Term) || isa<UnreachableInst>(Term);
3843 }
3844 if (ShouldSink) {
3845 assert(DT.dominates(BB, UserParent) &&(static_cast <bool> (DT.dominates(BB, UserParent) &&
"Dominance relation broken?") ? void (0) : __assert_fail ("DT.dominates(BB, UserParent) && \"Dominance relation broken?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3846, __extension__ __PRETTY_FUNCTION__))
3846 "Dominance relation broken?")(static_cast <bool> (DT.dominates(BB, UserParent) &&
"Dominance relation broken?") ? void (0) : __assert_fail ("DT.dominates(BB, UserParent) && \"Dominance relation broken?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3846, __extension__ __PRETTY_FUNCTION__))
;
3847 // Okay, the CFG is simple enough, try to sink this instruction.
3848 if (TryToSinkInstruction(I, UserParent)) {
3849 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Sink: " << *I <<
'\n'; } } while (false)
;
3850 MadeIRChange = true;
3851 // We'll add uses of the sunk instruction below, but since sinking
3852 // can expose opportunities for it's *operands* add them to the
3853 // worklist
3854 for (Use &U : I->operands())
3855 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
3856 Worklist.push(OpI);
3857 }
3858 }
3859 }
3860 }
3861
3862 // Now that we have an instruction, try combining it to simplify it.
3863 Builder.SetInsertPoint(I);
3864 Builder.CollectMetadataToCopy(
3865 I, {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
3866
3867#ifndef NDEBUG
3868 std::string OrigI;
3869#endif
3870 LLVM_DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str();)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { raw_string_ostream SS(OrigI); I->print(
SS); OrigI = SS.str();; } } while (false)
;
3871 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Visiting: " << OrigI
<< '\n'; } } while (false)
;
3872
3873 if (Instruction *Result = visit(*I)) {
3874 ++NumCombined;
3875 // Should we replace the old instruction with a new one?
3876 if (Result != I) {
3877 LLVM_DEBUG(dbgs() << "IC: Old = " << *I << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Old = " << *I <<
'\n' << " New = " << *Result << '\n'; }
} while (false)
3878 << " New = " << *Result << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Old = " << *I <<
'\n' << " New = " << *Result << '\n'; }
} while (false)
;
3879
3880 Result->copyMetadata(*I,
3881 {LLVMContext::MD_dbg, LLVMContext::MD_annotation});
3882 // Everything uses the new instruction now.
3883 I->replaceAllUsesWith(Result);
3884
3885 // Move the name to the new instruction first.
3886 Result->takeName(I);
3887
3888 // Insert the new instruction into the basic block...
3889 BasicBlock *InstParent = I->getParent();
3890 BasicBlock::iterator InsertPos = I->getIterator();
3891
3892 // Are we replace a PHI with something that isn't a PHI, or vice versa?
3893 if (isa<PHINode>(Result) != isa<PHINode>(I)) {
3894 // We need to fix up the insertion point.
3895 if (isa<PHINode>(I)) // PHI -> Non-PHI
3896 InsertPos = InstParent->getFirstInsertionPt();
3897 else // Non-PHI -> PHI
3898 InsertPos = InstParent->getFirstNonPHI()->getIterator();
3899 }
3900
3901 InstParent->getInstList().insert(InsertPos, Result);
3902
3903 // Push the new instruction and any users onto the worklist.
3904 Worklist.pushUsersToWorkList(*Result);
3905 Worklist.push(Result);
3906
3907 eraseInstFromFunction(*I);
3908 } else {
3909 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Mod = " << OrigI
<< '\n' << " New = " << *I << '\n'
; } } while (false)
3910 << " New = " << *I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Mod = " << OrigI
<< '\n' << " New = " << *I << '\n'
; } } while (false)
;
3911
3912 // If the instruction was modified, it's possible that it is now dead.
3913 // if so, remove it.
3914 if (isInstructionTriviallyDead(I, &TLI)) {
3915 eraseInstFromFunction(*I);
3916 } else {
3917 Worklist.pushUsersToWorkList(*I);
3918 Worklist.push(I);
3919 }
3920 }
3921 MadeIRChange = true;
3922 }
3923 }
3924
3925 Worklist.zap();
3926 return MadeIRChange;
3927}
3928
3929// Track the scopes used by !alias.scope and !noalias. In a function, a
3930// @llvm.experimental.noalias.scope.decl is only useful if that scope is used
3931// by both sets. If not, the declaration of the scope can be safely omitted.
3932// The MDNode of the scope can be omitted as well for the instructions that are
3933// part of this function. We do not do that at this point, as this might become
3934// too time consuming to do.
3935class AliasScopeTracker {
3936 SmallPtrSet<const MDNode *, 8> UsedAliasScopesAndLists;
3937 SmallPtrSet<const MDNode *, 8> UsedNoAliasScopesAndLists;
3938
3939public:
3940 void analyse(Instruction *I) {
3941 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
3942 if (!I->hasMetadataOtherThanDebugLoc())
3943 return;
3944
3945 auto Track = [](Metadata *ScopeList, auto &Container) {
3946 const auto *MDScopeList = dyn_cast_or_null<MDNode>(ScopeList);
3947 if (!MDScopeList || !Container.insert(MDScopeList).second)
3948 return;
3949 for (auto &MDOperand : MDScopeList->operands())
3950 if (auto *MDScope = dyn_cast<MDNode>(MDOperand))
3951 Container.insert(MDScope);
3952 };
3953
3954 Track(I->getMetadata(LLVMContext::MD_alias_scope), UsedAliasScopesAndLists);
3955 Track(I->getMetadata(LLVMContext::MD_noalias), UsedNoAliasScopesAndLists);
3956 }
3957
3958 bool isNoAliasScopeDeclDead(Instruction *Inst) {
3959 NoAliasScopeDeclInst *Decl = dyn_cast<NoAliasScopeDeclInst>(Inst);
3960 if (!Decl)
3961 return false;
3962
3963 assert(Decl->use_empty() &&(static_cast <bool> (Decl->use_empty() && "llvm.experimental.noalias.scope.decl in use ?"
) ? void (0) : __assert_fail ("Decl->use_empty() && \"llvm.experimental.noalias.scope.decl in use ?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3964, __extension__ __PRETTY_FUNCTION__))
3964 "llvm.experimental.noalias.scope.decl in use ?")(static_cast <bool> (Decl->use_empty() && "llvm.experimental.noalias.scope.decl in use ?"
) ? void (0) : __assert_fail ("Decl->use_empty() && \"llvm.experimental.noalias.scope.decl in use ?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3964, __extension__ __PRETTY_FUNCTION__))
;
3965 const MDNode *MDSL = Decl->getScopeList();
3966 assert(MDSL->getNumOperands() == 1 &&(static_cast <bool> (MDSL->getNumOperands() == 1 &&
"llvm.experimental.noalias.scope should refer to a single scope"
) ? void (0) : __assert_fail ("MDSL->getNumOperands() == 1 && \"llvm.experimental.noalias.scope should refer to a single scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3967, __extension__ __PRETTY_FUNCTION__))
3967 "llvm.experimental.noalias.scope should refer to a single scope")(static_cast <bool> (MDSL->getNumOperands() == 1 &&
"llvm.experimental.noalias.scope should refer to a single scope"
) ? void (0) : __assert_fail ("MDSL->getNumOperands() == 1 && \"llvm.experimental.noalias.scope should refer to a single scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp"
, 3967, __extension__ __PRETTY_FUNCTION__))
;
3968 auto &MDOperand = MDSL->getOperand(0);
3969 if (auto *MD = dyn_cast<MDNode>(MDOperand))
3970 return !UsedAliasScopesAndLists.contains(MD) ||
3971 !UsedNoAliasScopesAndLists.contains(MD);
3972
3973 // Not an MDNode ? throw away.
3974 return true;
3975 }
3976};
3977
3978/// Populate the IC worklist from a function, by walking it in depth-first
3979/// order and adding all reachable code to the worklist.
3980///
3981/// This has a couple of tricks to make the code faster and more powerful. In
3982/// particular, we constant fold and DCE instructions as we go, to avoid adding
3983/// them to the worklist (this significantly speeds up instcombine on code where
3984/// many instructions are dead or constant). Additionally, if we find a branch
3985/// whose condition is a known constant, we only visit the reachable successors.
3986static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3987 const TargetLibraryInfo *TLI,
3988 InstCombineWorklist &ICWorklist) {
3989 bool MadeIRChange = false;
3990 SmallPtrSet<BasicBlock *, 32> Visited;
3991 SmallVector<BasicBlock*, 256> Worklist;
3992 Worklist.push_back(&F.front());
3993
3994 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3995 DenseMap<Constant *, Constant *> FoldedConstants;
3996 AliasScopeTracker SeenAliasScopes;
3997
3998 do {
3999 BasicBlock *BB = Worklist.pop_back_val();
4000
4001 // We have now visited this block! If we've already been here, ignore it.
4002 if (!Visited.insert(BB).second)
4003 continue;
4004
4005 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
4006 Instruction *Inst = &*BBI++;
4007
4008 // ConstantProp instruction if trivially constant.
4009 if (!Inst->use_empty() &&
4010 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
4011 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
4012 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *Instdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold to: " <<
*C << " from: " << *Inst << '\n'; } } while
(false)
4013 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold to: " <<
*C << " from: " << *Inst << '\n'; } } while
(false)
;
4014 Inst->replaceAllUsesWith(C);
4015 ++NumConstProp;
4016 if (isInstructionTriviallyDead(Inst, TLI))
4017 Inst->eraseFromParent();
4018 MadeIRChange = true;
4019 continue;
4020 }
4021
4022 // See if we can constant fold its operands.
4023 for (Use &U : Inst->operands()) {
4024 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
4025 continue;
4026
4027 auto *C = cast<Constant>(U);
4028 Constant *&FoldRes = FoldedConstants[C];
4029 if (!FoldRes)
4030 FoldRes = ConstantFoldConstant(C, DL, TLI);
4031
4032 if (FoldRes != C) {
4033 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Instdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold operand of: "
<< *Inst << "\n Old = " << *C << "\n New = "
<< *FoldRes << '\n'; } } while (false)
4034 << "\n Old = " << *Cdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold operand of: "
<< *Inst << "\n Old = " << *C << "\n New = "
<< *FoldRes << '\n'; } } while (false)
4035 << "\n New = " << *FoldRes << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ConstFold operand of: "
<< *Inst << "\n Old = " << *C << "\n New = "
<< *FoldRes << '\n'; } } while (false)
;
4036 U = FoldRes;
4037 MadeIRChange = true;
4038 }
4039 }
4040
4041 // Skip processing debug and pseudo intrinsics in InstCombine. Processing
4042 // these call instructions consumes non-trivial amount of time and
4043 // provides no value for the optimization.
4044 if (!Inst->isDebugOrPseudoInst()) {
4045 InstrsForInstCombineWorklist.push_back(Inst);
4046 SeenAliasScopes.analyse(Inst);
4047 }
4048 }
4049
4050 // Recursively visit successors. If this is a branch or switch on a
4051 // constant, only visit the reachable successor.
4052 Instruction *TI = BB->getTerminator();
4053 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
4054 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
4055 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
4056 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
4057 Worklist.push_back(ReachableBB);
4058 continue;
4059 }
4060 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
4061 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
4062 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
4063 continue;
4064 }
4065 }
4066
4067 append_range(Worklist, successors(TI));
4068 } while (!Worklist.empty());
4069
4070 // Remove instructions inside unreachable blocks. This prevents the
4071 // instcombine code from having to deal with some bad special cases, and
4072 // reduces use counts of instructions.
4073 for (BasicBlock &BB : F) {
4074 if (Visited.count(&BB))
4075 continue;
4076
4077 unsigned NumDeadInstInBB;
4078 unsigned NumDeadDbgInstInBB;
4079 std::tie(NumDeadInstInBB, NumDeadDbgInstInBB) =
4080 removeAllNonTerminatorAndEHPadInstructions(&BB);
4081
4082 MadeIRChange |= NumDeadInstInBB + NumDeadDbgInstInBB > 0;
4083 NumDeadInst += NumDeadInstInBB;
4084 }
4085
4086 // Once we've found all of the instructions to add to instcombine's worklist,
4087 // add them in reverse order. This way instcombine will visit from the top
4088 // of the function down. This jives well with the way that it adds all uses
4089 // of instructions to the worklist after doing a transformation, thus avoiding
4090 // some N^2 behavior in pathological cases.
4091 ICWorklist.reserve(InstrsForInstCombineWorklist.size());
4092 for (Instruction *Inst : reverse(InstrsForInstCombineWorklist)) {
4093 // DCE instruction if trivially dead. As we iterate in reverse program
4094 // order here, we will clean up whole chains of dead instructions.
4095 if (isInstructionTriviallyDead(Inst, TLI) ||
4096 SeenAliasScopes.isNoAliasScopeDeclDead(Inst)) {
4097 ++NumDeadInst;
4098 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: DCE: " << *Inst
<< '\n'; } } while (false)
;
4099 salvageDebugInfo(*Inst);
4100 Inst->eraseFromParent();
4101 MadeIRChange = true;
4102 continue;
4103 }
4104
4105 ICWorklist.push(Inst);
4106 }
4107
4108 return MadeIRChange;
4109}
4110
4111static bool combineInstructionsOverFunction(
4112 Function &F, InstCombineWorklist &Worklist, AliasAnalysis *AA,
4113 AssumptionCache &AC, TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
4114 DominatorTree &DT, OptimizationRemarkEmitter &ORE, BlockFrequencyInfo *BFI,
4115 ProfileSummaryInfo *PSI, unsigned MaxIterations, LoopInfo *LI) {
4116 auto &DL = F.getParent()->getDataLayout();
4117 MaxIterations = std::min(MaxIterations, LimitMaxIterations.getValue());
4118
4119 /// Builder - This is an IRBuilder that automatically inserts new
4120 /// instructions into the worklist when they are created.
4121 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
4122 F.getContext(), TargetFolder(DL),
4123 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
4124 Worklist.add(I);
4125 if (auto *Assume = dyn_cast<AssumeInst>(I))
4126 AC.registerAssumption(Assume);
4127 }));
4128
4129 // Lower dbg.declare intrinsics otherwise their value may be clobbered
4130 // by instcombiner.
4131 bool MadeIRChange = false;
4132 if (ShouldLowerDbgDeclare)
4133 MadeIRChange = LowerDbgDeclare(F);
4134
4135 // Iterate while there is work to do.
4136 unsigned Iteration = 0;
4137 while (true) {
4138 ++NumWorklistIterations;
4139 ++Iteration;
4140
4141 if (Iteration > InfiniteLoopDetectionThreshold) {
4142 report_fatal_error(
4143 "Instruction Combining seems stuck in an infinite loop after " +
4144 Twine(InfiniteLoopDetectionThreshold) + " iterations.");
4145 }
4146
4147 if (Iteration > MaxIterations) {
4148 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterationsdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "\n\n[IC] Iteration limit #"
<< MaxIterations << " on " << F.getName() <<
" reached; stopping before reaching a fixpoint\n"; } } while
(false)
4149 << " on " << F.getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "\n\n[IC] Iteration limit #"
<< MaxIterations << " on " << F.getName() <<
" reached; stopping before reaching a fixpoint\n"; } } while
(false)
4150 << " reached; stopping before reaching a fixpoint\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "\n\n[IC] Iteration limit #"
<< MaxIterations << " on " << F.getName() <<
" reached; stopping before reaching a fixpoint\n"; } } while
(false)
;
4151 break;
4152 }
4153
4154 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "\n\nINSTCOMBINE ITERATION #"
<< Iteration << " on " << F.getName() <<
"\n"; } } while (false)
4155 << F.getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "\n\nINSTCOMBINE ITERATION #"
<< Iteration << " on " << F.getName() <<
"\n"; } } while (false)
;
4156
4157 MadeIRChange |= prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
4158
4159 InstCombinerImpl IC(Worklist, Builder, F.hasMinSize(), AA, AC, TLI, TTI, DT,
4160 ORE, BFI, PSI, DL, LI);
4161 IC.MaxArraySizeForCombine = MaxArraySize;
4162
4163 if (!IC.run())
4164 break;
4165
4166 MadeIRChange = true;
4167 }
4168
4169 return MadeIRChange;
4170}
4171
4172InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations) {}
4173
4174InstCombinePass::InstCombinePass(unsigned MaxIterations)
4175 : MaxIterations(MaxIterations) {}
4176
4177PreservedAnalyses InstCombinePass::run(Function &F,
4178 FunctionAnalysisManager &AM) {
4179 auto &AC = AM.getResult<AssumptionAnalysis>(F);
4180 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
4181 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
4182 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4183 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
4184
4185 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
4186
4187 auto *AA = &AM.getResult<AAManager>(F);
4188 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
4189 ProfileSummaryInfo *PSI =
4190 MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
4191 auto *BFI = (PSI && PSI->hasProfileSummary()) ?
4192 &AM.getResult<BlockFrequencyAnalysis>(F) : nullptr;
4193
4194 if (!combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
4195 BFI, PSI, MaxIterations, LI))
4196 // No changes, all analyses are preserved.
4197 return PreservedAnalyses::all();
4198
4199 // Mark all the analyses that instcombine updates as preserved.
4200 PreservedAnalyses PA;
4201 PA.preserveSet<CFGAnalyses>();
4202 return PA;
4203}
4204
4205void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
4206 AU.setPreservesCFG();
4207 AU.addRequired<AAResultsWrapperPass>();
4208 AU.addRequired<AssumptionCacheTracker>();
4209 AU.addRequired<TargetLibraryInfoWrapperPass>();
4210 AU.addRequired<TargetTransformInfoWrapperPass>();
4211 AU.addRequired<DominatorTreeWrapperPass>();
4212 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4213 AU.addPreserved<DominatorTreeWrapperPass>();
4214 AU.addPreserved<AAResultsWrapperPass>();
4215 AU.addPreserved<BasicAAWrapperPass>();
4216 AU.addPreserved<GlobalsAAWrapperPass>();
4217 AU.addRequired<ProfileSummaryInfoWrapperPass>();
4218 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
4219}
4220
4221bool InstructionCombiningPass::runOnFunction(Function &F) {
4222 if (skipFunction(F))
4223 return false;
4224
4225 // Required analyses.
4226 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4227 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4228 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
4229 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4230 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4231 auto &ORE = getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4232
4233 // Optional analyses.
4234 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
4235 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
4236 ProfileSummaryInfo *PSI =
4237 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
4238 BlockFrequencyInfo *BFI =
4239 (PSI && PSI->hasProfileSummary()) ?
4240 &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI() :
4241 nullptr;
4242
4243 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, TTI, DT, ORE,
4244 BFI, PSI, MaxIterations, LI);
4245}
4246
4247char InstructionCombiningPass::ID = 0;
4248
4249InstructionCombiningPass::InstructionCombiningPass()
4250 : FunctionPass(ID), MaxIterations(InstCombineDefaultMaxIterations) {
4251 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
4252}
4253
4254InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations)
4255 : FunctionPass(ID), MaxIterations(MaxIterations) {
4256 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
4257}
4258
4259INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",static void *initializeInstructionCombiningPassPassOnce(PassRegistry
&Registry) {
4260 "Combine redundant instructions", false, false)static void *initializeInstructionCombiningPassPassOnce(PassRegistry
&Registry) {
4261INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
4262INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
4263INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
4264INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
4265INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
4266INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry);
4267INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)initializeOptimizationRemarkEmitterWrapperPassPass(Registry);
4268INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass)initializeLazyBlockFrequencyInfoPassPass(Registry);
4269INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry);
4270INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",PassInfo *PI = new PassInfo( "Combine redundant instructions"
, "instcombine", &InstructionCombiningPass::ID, PassInfo::
NormalCtor_t(callDefaultCtor<InstructionCombiningPass>)
, false, false); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeInstructionCombiningPassPassFlag
; void llvm::initializeInstructionCombiningPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeInstructionCombiningPassPassFlag
, initializeInstructionCombiningPassPassOnce, std::ref(Registry
)); }
4271 "Combine redundant instructions", false, false)PassInfo *PI = new PassInfo( "Combine redundant instructions"
, "instcombine", &InstructionCombiningPass::ID, PassInfo::
NormalCtor_t(callDefaultCtor<InstructionCombiningPass>)
, false, false); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeInstructionCombiningPassPassFlag
; void llvm::initializeInstructionCombiningPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeInstructionCombiningPassPassFlag
, initializeInstructionCombiningPassPassOnce, std::ref(Registry
)); }
4272
4273// Initialization Routines
4274void llvm::initializeInstCombine(PassRegistry &Registry) {
4275 initializeInstructionCombiningPassPass(Registry);
4276}
4277
4278void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
4279 initializeInstructionCombiningPassPass(*unwrap(R));
4280}
4281
4282FunctionPass *llvm::createInstructionCombiningPass() {
4283 return new InstructionCombiningPass();
4284}
4285
4286FunctionPass *llvm::createInstructionCombiningPass(unsigned MaxIterations) {
4287 return new InstructionCombiningPass(MaxIterations);
4288}
4289
4290void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM) {
4291 unwrap(PM)->add(createInstructionCombiningPass());
4292}

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstCombineInternal.h

1//===- InstCombineInternal.h - InstCombine pass internals -------*- 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/// \file
10///
11/// This file provides internal interfaces used to implement the InstCombine.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/InstructionSimplify.h"
20#include "llvm/Analysis/TargetFolder.h"
21#include "llvm/Analysis/ValueTracking.h"
22#include "llvm/IR/IRBuilder.h"
23#include "llvm/IR/InstVisitor.h"
24#include "llvm/IR/PatternMatch.h"
25#include "llvm/IR/Value.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/KnownBits.h"
28#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
29#include "llvm/Transforms/InstCombine/InstCombiner.h"
30#include "llvm/Transforms/Utils/Local.h"
31#include <cassert>
32
33#define DEBUG_TYPE"instcombine" "instcombine"
34
35using namespace llvm::PatternMatch;
36
37// As a default, let's assume that we want to be aggressive,
38// and attempt to traverse with no limits in attempt to sink negation.
39static constexpr unsigned NegatorDefaultMaxDepth = ~0U;
40
41// Let's guesstimate that most often we will end up visiting/producing
42// fairly small number of new instructions.
43static constexpr unsigned NegatorMaxNodesSSO = 16;
44
45namespace llvm {
46
47class AAResults;
48class APInt;
49class AssumptionCache;
50class BlockFrequencyInfo;
51class DataLayout;
52class DominatorTree;
53class GEPOperator;
54class GlobalVariable;
55class LoopInfo;
56class OptimizationRemarkEmitter;
57class ProfileSummaryInfo;
58class TargetLibraryInfo;
59class User;
60
61class LLVM_LIBRARY_VISIBILITY__attribute__ ((visibility("hidden"))) InstCombinerImpl final
62 : public InstCombiner,
63 public InstVisitor<InstCombinerImpl, Instruction *> {
64public:
65 InstCombinerImpl(InstCombineWorklist &Worklist, BuilderTy &Builder,
66 bool MinimizeSize, AAResults *AA, AssumptionCache &AC,
67 TargetLibraryInfo &TLI, TargetTransformInfo &TTI,
68 DominatorTree &DT, OptimizationRemarkEmitter &ORE,
69 BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
70 const DataLayout &DL, LoopInfo *LI)
71 : InstCombiner(Worklist, Builder, MinimizeSize, AA, AC, TLI, TTI, DT, ORE,
72 BFI, PSI, DL, LI) {}
73
74 virtual ~InstCombinerImpl() {}
75
76 /// Run the combiner over the entire worklist until it is empty.
77 ///
78 /// \returns true if the IR is changed.
79 bool run();
80
81 // Visitation implementation - Implement instruction combining for different
82 // instruction types. The semantics are as follows:
83 // Return Value:
84 // null - No change was made
85 // I - Change was made, I is still valid, I may be dead though
86 // otherwise - Change was made, replace I with returned instruction
87 //
88 Instruction *visitFNeg(UnaryOperator &I);
89 Instruction *visitAdd(BinaryOperator &I);
90 Instruction *visitFAdd(BinaryOperator &I);
91 Value *OptimizePointerDifference(
92 Value *LHS, Value *RHS, Type *Ty, bool isNUW);
93 Instruction *visitSub(BinaryOperator &I);
94 Instruction *visitFSub(BinaryOperator &I);
95 Instruction *visitMul(BinaryOperator &I);
96 Instruction *visitFMul(BinaryOperator &I);
97 Instruction *visitURem(BinaryOperator &I);
98 Instruction *visitSRem(BinaryOperator &I);
99 Instruction *visitFRem(BinaryOperator &I);
100 bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
101 Instruction *commonIRemTransforms(BinaryOperator &I);
102 Instruction *commonIDivTransforms(BinaryOperator &I);
103 Instruction *visitUDiv(BinaryOperator &I);
104 Instruction *visitSDiv(BinaryOperator &I);
105 Instruction *visitFDiv(BinaryOperator &I);
106 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
107 Instruction *visitAnd(BinaryOperator &I);
108 Instruction *visitOr(BinaryOperator &I);
109 bool sinkNotIntoOtherHandOfAndOrOr(BinaryOperator &I);
110 Instruction *visitXor(BinaryOperator &I);
111 Instruction *visitShl(BinaryOperator &I);
112 Value *reassociateShiftAmtsOfTwoSameDirectionShifts(
113 BinaryOperator *Sh0, const SimplifyQuery &SQ,
114 bool AnalyzeForSignBitExtraction = false);
115 Instruction *canonicalizeCondSignextOfHighBitExtractToSignextHighBitExtract(
116 BinaryOperator &I);
117 Instruction *foldVariableSignZeroExtensionOfVariableHighBitExtract(
118 BinaryOperator &OldAShr);
119 Instruction *visitAShr(BinaryOperator &I);
120 Instruction *visitLShr(BinaryOperator &I);
121 Instruction *commonShiftTransforms(BinaryOperator &I);
122 Instruction *visitFCmpInst(FCmpInst &I);
123 CmpInst *canonicalizeICmpPredicate(CmpInst &I);
124 Instruction *visitICmpInst(ICmpInst &I);
125 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
126 BinaryOperator &I);
127 Instruction *commonCastTransforms(CastInst &CI);
128 Instruction *commonPointerCastTransforms(CastInst &CI);
129 Instruction *visitTrunc(TruncInst &CI);
130 Instruction *visitZExt(ZExtInst &CI);
131 Instruction *visitSExt(SExtInst &CI);
132 Instruction *visitFPTrunc(FPTruncInst &CI);
133 Instruction *visitFPExt(CastInst &CI);
134 Instruction *visitFPToUI(FPToUIInst &FI);
135 Instruction *visitFPToSI(FPToSIInst &FI);
136 Instruction *visitUIToFP(CastInst &CI);
137 Instruction *visitSIToFP(CastInst &CI);
138 Instruction *visitPtrToInt(PtrToIntInst &CI);
139 Instruction *visitIntToPtr(IntToPtrInst &CI);
140 Instruction *visitBitCast(BitCastInst &CI);
141 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
142 Instruction *foldItoFPtoI(CastInst &FI);
143 Instruction *visitSelectInst(SelectInst &SI);
144 Instruction *visitCallInst(CallInst &CI);
145 Instruction *visitInvokeInst(InvokeInst &II);
146 Instruction *visitCallBrInst(CallBrInst &CBI);
147
148 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
149 Instruction *visitPHINode(PHINode &PN);
150 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
151 Instruction *visitAllocaInst(AllocaInst &AI);
152 Instruction *visitAllocSite(Instruction &FI);
153 Instruction *visitFree(CallInst &FI);
154 Instruction *visitLoadInst(LoadInst &LI);
155 Instruction *visitStoreInst(StoreInst &SI);
156 Instruction *visitAtomicRMWInst(AtomicRMWInst &SI);
157 Instruction *visitUnconditionalBranchInst(BranchInst &BI);
158 Instruction *visitBranchInst(BranchInst &BI);
159 Instruction *visitFenceInst(FenceInst &FI);
160 Instruction *visitSwitchInst(SwitchInst &SI);
161 Instruction *visitReturnInst(ReturnInst &RI);
162 Instruction *visitUnreachableInst(UnreachableInst &I);
163 Instruction *
164 foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI);
165 Instruction *visitInsertValueInst(InsertValueInst &IV);
166 Instruction *visitInsertElementInst(InsertElementInst &IE);
167 Instruction *visitExtractElementInst(ExtractElementInst &EI);
168 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
169 Instruction *visitExtractValueInst(ExtractValueInst &EV);
170 Instruction *visitLandingPadInst(LandingPadInst &LI);
171 Instruction *visitVAEndInst(VAEndInst &I);
172 Value *pushFreezeToPreventPoisonFromPropagating(FreezeInst &FI);
173 bool freezeDominatedUses(FreezeInst &FI);
174 Instruction *visitFreeze(FreezeInst &I);
175
176 /// Specify what to return for unhandled instructions.
177 Instruction *visitInstruction(Instruction &I) { return nullptr; }
178
179 /// True when DB dominates all uses of DI except UI.
180 /// UI must be in the same block as DI.
181 /// The routine checks that the DI parent and DB are different.
182 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
183 const BasicBlock *DB) const;
184
185 /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
186 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
187 const unsigned SIOpd);
188
189 LoadInst *combineLoadToNewType(LoadInst &LI, Type *NewTy,
190 const Twine &Suffix = "");
191
192private:
193 void annotateAnyAllocSite(CallBase &Call, const TargetLibraryInfo *TLI);
194 bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
195 bool shouldChangeType(Type *From, Type *To) const;
196 Value *dyn_castNegVal(Value *V) const;
197 Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
198 SmallVectorImpl<Value *> &NewIndices);
199
200 /// Classify whether a cast is worth optimizing.
201 ///
202 /// This is a helper to decide whether the simplification of
203 /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
204 ///
205 /// \param CI The cast we are interested in.
206 ///
207 /// \return true if this cast actually results in any code being generated and
208 /// if it cannot already be eliminated by some other transformation.
209 bool shouldOptimizeCast(CastInst *CI);
210
211 /// Try to optimize a sequence of instructions checking if an operation
212 /// on LHS and RHS overflows.
213 ///
214 /// If this overflow check is done via one of the overflow check intrinsics,
215 /// then CtxI has to be the call instruction calling that intrinsic. If this
216 /// overflow check is done by arithmetic followed by a compare, then CtxI has
217 /// to be the arithmetic instruction.
218 ///
219 /// If a simplification is possible, stores the simplified result of the
220 /// operation in OperationResult and result of the overflow check in
221 /// OverflowResult, and return true. If no simplification is possible,
222 /// returns false.
223 bool OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp, bool IsSigned,
224 Value *LHS, Value *RHS,
225 Instruction &CtxI, Value *&OperationResult,
226 Constant *&OverflowResult);
227
228 Instruction *visitCallBase(CallBase &Call);
229 Instruction *tryOptimizeCall(CallInst *CI);
230 bool transformConstExprCastCall(CallBase &Call);
231 Instruction *transformCallThroughTrampoline(CallBase &Call,
232 IntrinsicInst &Tramp);
233
234 Value *simplifyMaskedLoad(IntrinsicInst &II);
235 Instruction *simplifyMaskedStore(IntrinsicInst &II);
236 Instruction *simplifyMaskedGather(IntrinsicInst &II);
237 Instruction *simplifyMaskedScatter(IntrinsicInst &II);
238
239 /// Transform (zext icmp) to bitwise / integer operations in order to
240 /// eliminate it.
241 ///
242 /// \param ICI The icmp of the (zext icmp) pair we are interested in.
243 /// \parem CI The zext of the (zext icmp) pair we are interested in.
244 /// \param DoTransform Pass false to just test whether the given (zext icmp)
245 /// would be transformed. Pass true to actually perform the transformation.
246 ///
247 /// \return null if the transformation cannot be performed. If the
248 /// transformation can be performed the new instruction that replaces the
249 /// (zext icmp) pair will be returned (if \p DoTransform is false the
250 /// unmodified \p ICI will be returned in this case).
251 Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
252 bool DoTransform = true);
253
254 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
255
256 bool willNotOverflowSignedAdd(const Value *LHS, const Value *RHS,
257 const Instruction &CxtI) const {
258 return computeOverflowForSignedAdd(LHS, RHS, &CxtI) ==
259 OverflowResult::NeverOverflows;
260 }
261
262 bool willNotOverflowUnsignedAdd(const Value *LHS, const Value *RHS,
263 const Instruction &CxtI) const {
264 return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) ==
265 OverflowResult::NeverOverflows;
266 }
267
268 bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
269 const Instruction &CxtI, bool IsSigned) const {
270 return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
271 : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
272 }
273
274 bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
275 const Instruction &CxtI) const {
276 return computeOverflowForSignedSub(LHS, RHS, &CxtI) ==
277 OverflowResult::NeverOverflows;
278 }
279
280 bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
281 const Instruction &CxtI) const {
282 return computeOverflowForUnsignedSub(LHS, RHS, &CxtI) ==
283 OverflowResult::NeverOverflows;
284 }
285
286 bool willNotOverflowSub(const Value *LHS, const Value *RHS,
287 const Instruction &CxtI, bool IsSigned) const {
288 return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
289 : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
290 }
291
292 bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
293 const Instruction &CxtI) const {
294 return computeOverflowForSignedMul(LHS, RHS, &CxtI) ==
295 OverflowResult::NeverOverflows;
296 }
297
298 bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
299 const Instruction &CxtI) const {
300 return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) ==
301 OverflowResult::NeverOverflows;
302 }
303
304 bool willNotOverflowMul(const Value *LHS, const Value *RHS,
305 const Instruction &CxtI, bool IsSigned) const {
306 return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
307 : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
308 }
309
310 bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
311 const Value *RHS, const Instruction &CxtI,
312 bool IsSigned) const {
313 switch (Opcode) {
314 case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CxtI, IsSigned);
315 case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
316 case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
317 default: llvm_unreachable("Unexpected opcode for overflow query")::llvm::llvm_unreachable_internal("Unexpected opcode for overflow query"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstCombineInternal.h"
, 317)
;
318 }
319 }
320
321 Value *EmitGEPOffset(User *GEP);
322 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
323 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
324 Instruction *narrowBinOp(TruncInst &Trunc);
325 Instruction *narrowMaskedBinOp(BinaryOperator &And);
326 Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
327 Instruction *narrowFunnelShift(TruncInst &Trunc);
328 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
329 Instruction *matchSAddSubSat(Instruction &MinMax1);
330
331 void freelyInvertAllUsersOf(Value *V);
332
333 /// Determine if a pair of casts can be replaced by a single cast.
334 ///
335 /// \param CI1 The first of a pair of casts.
336 /// \param CI2 The second of a pair of casts.
337 ///
338 /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
339 /// Instruction::CastOps value for a cast that can replace the pair, casting
340 /// CI1->getSrcTy() to CI2->getDstTy().
341 ///
342 /// \see CastInst::isEliminableCastPair
343 Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
344 const CastInst *CI2);
345 Value *simplifyIntToPtrRoundTripCast(Value *Val);
346
347 Value *foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &And);
348 Value *foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Or);
349 Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS, BinaryOperator &Xor);
350
351 Value *foldEqOfParts(ICmpInst *Cmp0, ICmpInst *Cmp1, bool IsAnd);
352
353 /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
354 /// NOTE: Unlike most of instcombine, this returns a Value which should
355 /// already be inserted into the function.
356 Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd);
357
358 Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
359 Instruction *CxtI, bool IsAnd,
360 bool IsLogical = false);
361 Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D);
362 Value *getSelectCondition(Value *A, Value *B);
363
364 Instruction *foldIntrinsicWithOverflowCommon(IntrinsicInst *II);
365 Instruction *foldFPSignBitOps(BinaryOperator &I);
366
367 // Optimize one of these forms:
368 // and i1 Op, SI / select i1 Op, i1 SI, i1 false (if IsAnd = true)
369 // or i1 Op, SI / select i1 Op, i1 true, i1 SI (if IsAnd = false)
370 // into simplier select instruction using isImpliedCondition.
371 Instruction *foldAndOrOfSelectUsingImpliedCond(Value *Op, SelectInst &SI,
372 bool IsAnd);
373
374public:
375 /// Inserts an instruction \p New before instruction \p Old
376 ///
377 /// Also adds the new instruction to the worklist and returns \p New so that
378 /// it is suitable for use as the return from the visitation patterns.
379 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
380 assert(New && !New->getParent() &&(static_cast <bool> (New && !New->getParent(
) && "New instruction already inserted into a basic block!"
) ? void (0) : __assert_fail ("New && !New->getParent() && \"New instruction already inserted into a basic block!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstCombineInternal.h"
, 381, __extension__ __PRETTY_FUNCTION__))
381 "New instruction already inserted into a basic block!")(static_cast <bool> (New && !New->getParent(
) && "New instruction already inserted into a basic block!"
) ? void (0) : __assert_fail ("New && !New->getParent() && \"New instruction already inserted into a basic block!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstCombineInternal.h"
, 381, __extension__ __PRETTY_FUNCTION__))
;
382 BasicBlock *BB = Old.getParent();
383 BB->getInstList().insert(Old.getIterator(), New); // Insert inst
384 Worklist.add(New);
385 return New;
386 }
387
388 /// Same as InsertNewInstBefore, but also sets the debug loc.
389 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
390 New->setDebugLoc(Old.getDebugLoc());
391 return InsertNewInstBefore(New, Old);
392 }
393
394 /// A combiner-aware RAUW-like routine.
395 ///
396 /// This method is to be used when an instruction is found to be dead,
397 /// replaceable with another preexisting expression. Here we add all uses of
398 /// I to the worklist, replace all uses of I with the new value, then return
399 /// I, so that the inst combiner will know that I was modified.
400 Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
401 // If there are no uses to replace, then we return nullptr to indicate that
402 // no changes were made to the program.
403 if (I.use_empty()) return nullptr;
15
Calling 'Value::use_empty'
18
Returning from 'Value::use_empty'
19
Taking false branch
404
405 Worklist.pushUsersToWorkList(I); // Add all modified instrs to worklist.
406
407 // If we are replacing the instruction with itself, this must be in a
408 // segment of unreachable code, so just clobber the instruction.
409 if (&I == V)
410 V = UndefValue::get(I.getType());
411
412 LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Replacing " << I
<< "\n" << " with " << *V << '\n'
; } } while (false)
20
Taking false branch
21
Assuming 'DebugFlag' is true
22
Assuming the condition is true
23
Taking true branch
24
Forming reference to null pointer
413 << " with " << *V << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: Replacing " << I
<< "\n" << " with " << *V << '\n'
; } } while (false)
;
414
415 I.replaceAllUsesWith(V);
416 MadeIRChange = true;
417 return &I;
418 }
419
420 /// Replace operand of instruction and add old operand to the worklist.
421 Instruction *replaceOperand(Instruction &I, unsigned OpNum, Value *V) {
422 Worklist.addValue(I.getOperand(OpNum));
423 I.setOperand(OpNum, V);
424 return &I;
425 }
426
427 /// Replace use and add the previously used value to the worklist.
428 void replaceUse(Use &U, Value *NewValue) {
429 Worklist.addValue(U);
430 U = NewValue;
431 }
432
433 /// Create and insert the idiom we use to indicate a block is unreachable
434 /// without having to rewrite the CFG from within InstCombine.
435 void CreateNonTerminatorUnreachable(Instruction *InsertAt) {
436 auto &Ctx = InsertAt->getContext();
437 new StoreInst(ConstantInt::getTrue(Ctx),
438 UndefValue::get(Type::getInt1PtrTy(Ctx)),
439 InsertAt);
440 }
441
442
443 /// Combiner aware instruction erasure.
444 ///
445 /// When dealing with an instruction that has side effects or produces a void
446 /// value, we can't rely on DCE to delete the instruction. Instead, visit
447 /// methods should return the value returned by this function.
448 Instruction *eraseInstFromFunction(Instruction &I) override {
449 LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("instcombine")) { dbgs() << "IC: ERASE " << I <<
'\n'; } } while (false)
;
450 assert(I.use_empty() && "Cannot erase instruction that is used!")(static_cast <bool> (I.use_empty() && "Cannot erase instruction that is used!"
) ? void (0) : __assert_fail ("I.use_empty() && \"Cannot erase instruction that is used!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/lib/Transforms/InstCombine/InstCombineInternal.h"
, 450, __extension__ __PRETTY_FUNCTION__))
;
451 salvageDebugInfo(I);
452
453 // Make sure that we reprocess all operands now that we reduced their
454 // use counts.
455 for (Use &Operand : I.operands())
456 if (auto *Inst = dyn_cast<Instruction>(Operand))
457 Worklist.add(Inst);
458
459 Worklist.remove(&I);
460 I.eraseFromParent();
461 MadeIRChange = true;
462 return nullptr; // Don't do anything with FI
463 }
464
465 void computeKnownBits(const Value *V, KnownBits &Known,
466 unsigned Depth, const Instruction *CxtI) const {
467 llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
468 }
469
470 KnownBits computeKnownBits(const Value *V, unsigned Depth,
471 const Instruction *CxtI) const {
472 return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT);
473 }
474
475 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
476 unsigned Depth = 0,
477 const Instruction *CxtI = nullptr) {
478 return llvm::isKnownToBeAPowerOfTwo(V, DL, OrZero, Depth, &AC, CxtI, &DT);
479 }
480
481 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth = 0,
482 const Instruction *CxtI = nullptr) const {
483 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
484 }
485
486 unsigned ComputeNumSignBits(const Value *Op, unsigned Depth = 0,
487 const Instruction *CxtI = nullptr) const {
488 return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
489 }
490
491 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
492 const Value *RHS,
493 const Instruction *CxtI) const {
494 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
495 }
496
497 OverflowResult computeOverflowForSignedMul(const Value *LHS,
498 const Value *RHS,
499 const Instruction *CxtI) const {
500 return llvm::computeOverflowForSignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
501 }
502
503 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
504 const Value *RHS,
505 const Instruction *CxtI) const {
506 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
507 }
508
509 OverflowResult computeOverflowForSignedAdd(const Value *LHS,
510 const Value *RHS,
511 const Instruction *CxtI) const {
512 return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
513 }
514
515 OverflowResult computeOverflowForUnsignedSub(const Value *LHS,
516 const Value *RHS,
517 const Instruction *CxtI) const {
518 return llvm::computeOverflowForUnsignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
519 }
520
521 OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
522 const Instruction *CxtI) const {
523 return llvm::computeOverflowForSignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
524 }
525
526 OverflowResult computeOverflow(
527 Instruction::BinaryOps BinaryOp, bool IsSigned,
528 Value *LHS, Value *RHS, Instruction *CxtI) const;
529
530 /// Performs a few simplifications for operators which are associative
531 /// or commutative.
532 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
533
534 /// Tries to simplify binary operations which some other binary
535 /// operation distributes over.
536 ///
537 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
538 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
539 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
540 /// value, or null if it didn't simplify.
541 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
542
543 /// Tries to simplify add operations using the definition of remainder.
544 ///
545 /// The definition of remainder is X % C = X - (X / C ) * C. The add
546 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
547 /// X % (C0 * C1)
548 Value *SimplifyAddWithRemainder(BinaryOperator &I);
549
550 // Binary Op helper for select operations where the expression can be
551 // efficiently reorganized.
552 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
553 Value *RHS);
554
555 /// This tries to simplify binary operations by factorizing out common terms
556 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
557 Value *tryFactorization(BinaryOperator &, Instruction::BinaryOps, Value *,
558 Value *, Value *, Value *);
559
560 /// Match a select chain which produces one of three values based on whether
561 /// the LHS is less than, equal to, or greater than RHS respectively.
562 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
563 /// Equal and Greater values are saved in the matching process and returned to
564 /// the caller.
565 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
566 ConstantInt *&Less, ConstantInt *&Equal,
567 ConstantInt *&Greater);
568
569 /// Attempts to replace V with a simpler value based on the demanded
570 /// bits.
571 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
572 unsigned Depth, Instruction *CxtI);
573 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
574 const APInt &DemandedMask, KnownBits &Known,
575 unsigned Depth = 0) override;
576
577 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
578 /// bits. It also tries to handle simplifications that can be done based on
579 /// DemandedMask, but without modifying the Instruction.
580 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
581 const APInt &DemandedMask,
582 KnownBits &Known,
583 unsigned Depth, Instruction *CxtI);
584
585 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
586 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
587 Value *simplifyShrShlDemandedBits(
588 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
589 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
590
591 /// Tries to simplify operands to an integer instruction based on its
592 /// demanded bits.
593 bool SimplifyDemandedInstructionBits(Instruction &Inst);
594
595 virtual Value *
596 SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &UndefElts,
597 unsigned Depth = 0,
598 bool AllowMultipleUsers = false) override;
599
600 /// Canonicalize the position of binops relative to shufflevector.
601 Instruction *foldVectorBinop(BinaryOperator &Inst);
602 Instruction *foldVectorSelect(SelectInst &Sel);
603
604 /// Given a binary operator, cast instruction, or select which has a PHI node
605 /// as operand #0, see if we can fold the instruction into the PHI (which is
606 /// only possible if all operands to the PHI are constants).
607 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
608
609 /// Given an instruction with a select as one operand and a constant as the
610 /// other operand, try to fold the binary operator into the select arguments.
611 /// This also works for Cast instructions, which obviously do not have a
612 /// second operand.
613 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
614
615 /// This is a convenience wrapper function for the above two functions.
616 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
617
618 Instruction *foldAddWithConstant(BinaryOperator &Add);
619
620 /// Try to rotate an operation below a PHI node, using PHI nodes for
621 /// its operands.
622 Instruction *foldPHIArgOpIntoPHI(PHINode &PN);
623 Instruction *foldPHIArgBinOpIntoPHI(PHINode &PN);
624 Instruction *foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN);
625 Instruction *foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN);
626 Instruction *foldPHIArgGEPIntoPHI(PHINode &PN);
627 Instruction *foldPHIArgLoadIntoPHI(PHINode &PN);
628 Instruction *foldPHIArgZextsIntoPHI(PHINode &PN);
629 Instruction *foldPHIArgIntToPtrToPHI(PHINode &PN);
630
631 /// If an integer typed PHI has only one use which is an IntToPtr operation,
632 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
633 /// insert a new pointer typed PHI and replace the original one.
634 Instruction *foldIntegerTypedPHI(PHINode &PN);
635
636 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
637 /// folded operation.
638 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
639
640 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
641 ICmpInst::Predicate Cond, Instruction &I);
642 Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
643 const Value *Other);
644 Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
645 GlobalVariable *GV, CmpInst &ICI,
646 ConstantInt *AndCst = nullptr);
647 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
648 Constant *RHSC);
649 Instruction *foldICmpAddOpConst(Value *X, const APInt &C,
650 ICmpInst::Predicate Pred);
651 Instruction *foldICmpWithCastOp(ICmpInst &ICI);
652
653 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
654 Instruction *foldICmpWithDominatingICmp(ICmpInst &Cmp);
655 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
656 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
657 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
658 Instruction *foldICmpBinOp(ICmpInst &Cmp, const SimplifyQuery &SQ);
659 Instruction *foldICmpEquality(ICmpInst &Cmp);
660 Instruction *foldIRemByPowerOfTwoToBitTest(ICmpInst &I);
661 Instruction *foldSignBitTest(ICmpInst &I);
662 Instruction *foldICmpWithZero(ICmpInst &Cmp);
663
664 Value *foldUnsignedMultiplicationOverflowCheck(ICmpInst &Cmp);
665
666 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
667 ConstantInt *C);
668 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
669 const APInt &C);
670 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
671 const APInt &C);
672 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
673 const APInt &C);
674 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
675 const APInt &C);
676 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
677 const APInt &C);
678 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
679 const APInt &C);
680 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
681 const APInt &C);
682 Instruction *foldICmpSRemConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
683 const APInt &C);
684 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
685 const APInt &C);
686 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
687 const APInt &C);
688 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
689 const APInt &C);
690 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
691 const APInt &C);
692 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
693 const APInt &C1);
694 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
695 const APInt &C1, const APInt &C2);
696 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
697 const APInt &C2);
698 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
699 const APInt &C2);
700
701 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
702 BinaryOperator *BO,
703 const APInt &C);
704 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
705 const APInt &C);
706 Instruction *foldICmpEqIntrinsicWithConstant(ICmpInst &ICI, IntrinsicInst *II,
707 const APInt &C);
708 Instruction *foldICmpBitCast(ICmpInst &Cmp);
709
710 // Helpers of visitSelectInst().
711 Instruction *foldSelectExtConst(SelectInst &Sel);
712 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
713 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
714 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
715 Value *A, Value *B, Instruction &Outer,
716 SelectPatternFlavor SPF2, Value *C);
717 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
718 Instruction *foldSelectValueEquivalence(SelectInst &SI, ICmpInst &ICI);
719
720 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
721 bool isSigned, bool Inside);
722 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
723 bool mergeStoreIntoSuccessor(StoreInst &SI);
724
725 /// Given an initial instruction, check to see if it is the root of a
726 /// bswap/bitreverse idiom. If so, return the equivalent bswap/bitreverse
727 /// intrinsic.
728 Instruction *matchBSwapOrBitReverse(Instruction &I, bool MatchBSwaps,
729 bool MatchBitReversals);
730
731 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
732 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
733
734 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
735
736 /// Returns a value X such that Val = X * Scale, or null if none.
737 ///
738 /// If the multiplication is known not to overflow then NoSignedWrap is set.
739 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
740};
741
742class Negator final {
743 /// Top-to-bottom, def-to-use negated instruction tree we produced.
744 SmallVector<Instruction *, NegatorMaxNodesSSO> NewInstructions;
745
746 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
747 BuilderTy Builder;
748
749 const DataLayout &DL;
750 AssumptionCache &AC;
751 const DominatorTree &DT;
752
753 const bool IsTrulyNegation;
754
755 SmallDenseMap<Value *, Value *> NegationsCache;
756
757 Negator(LLVMContext &C, const DataLayout &DL, AssumptionCache &AC,
758 const DominatorTree &DT, bool IsTrulyNegation);
759
760#if LLVM_ENABLE_STATS1
761 unsigned NumValuesVisitedInThisNegator = 0;
762 ~Negator();
763#endif
764
765 using Result = std::pair<ArrayRef<Instruction *> /*NewInstructions*/,
766 Value * /*NegatedRoot*/>;
767
768 std::array<Value *, 2> getSortedOperandsOfBinOp(Instruction *I);
769
770 LLVM_NODISCARD[[clang::warn_unused_result]] Value *visitImpl(Value *V, unsigned Depth);
771
772 LLVM_NODISCARD[[clang::warn_unused_result]] Value *negate(Value *V, unsigned Depth);
773
774 /// Recurse depth-first and attempt to sink the negation.
775 /// FIXME: use worklist?
776 LLVM_NODISCARD[[clang::warn_unused_result]] Optional<Result> run(Value *Root);
777
778 Negator(const Negator &) = delete;
779 Negator(Negator &&) = delete;
780 Negator &operator=(const Negator &) = delete;
781 Negator &operator=(Negator &&) = delete;
782
783public:
784 /// Attempt to negate \p Root. Retuns nullptr if negation can't be performed,
785 /// otherwise returns negated value.
786 LLVM_NODISCARD[[clang::warn_unused_result]] static Value *Negate(bool LHSIsZero, Value *Root,
787 InstCombinerImpl &IC);
788};
789
790} // end namespace llvm
791
792#undef DEBUG_TYPE"instcombine"
793
794#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H

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