1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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
7 //===----------------------------------------------------------------------===//
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.
13 // This pass combines things like:
19 // This is a simple worklist driven algorithm.
21 // This pass guarantees that the following canonicalizations are performed on
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
33 //===----------------------------------------------------------------------===//
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"
112 using namespace llvm
;
113 using namespace llvm::PatternMatch
;
115 #define DEBUG_TYPE "instcombine"
117 STATISTIC(NumWorklistIterations
,
118 "Number of instruction combining iterations performed");
120 STATISTIC(NumCombined
, "Number of insts combined");
121 STATISTIC(NumConstProp
, "Number of constant folds");
122 STATISTIC(NumDeadInst
, "Number of dead inst eliminated");
123 STATISTIC(NumSunkInst
, "Number of instructions sunk");
124 STATISTIC(NumExpand
, "Number of expansions");
125 STATISTIC(NumFactor
, "Number of factorizations");
126 STATISTIC(NumReassoc
, "Number of reassociations");
127 DEBUG_COUNTER(VisitCounter
, "instcombine-visit",
128 "Controls which instructions are visited");
130 // FIXME: these limits eventually should be as low as 2.
131 static constexpr unsigned InstCombineDefaultMaxIterations
= 1000;
133 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold
= 100;
135 static constexpr unsigned InstCombineDefaultInfiniteLoopThreshold
= 1000;
139 EnableCodeSinking("instcombine-code-sinking", cl::desc("Enable code sinking"),
142 static cl::opt
<unsigned> LimitMaxIterations(
143 "instcombine-max-iterations",
144 cl::desc("Limit the maximum number of instruction combining iterations"),
145 cl::init(InstCombineDefaultMaxIterations
));
147 static cl::opt
<unsigned> InfiniteLoopDetectionThreshold(
148 "instcombine-infinite-loop-threshold",
149 cl::desc("Number of instruction combining iterations considered an "
151 cl::init(InstCombineDefaultInfiniteLoopThreshold
), cl::Hidden
);
153 static cl::opt
<unsigned>
154 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
155 cl::desc("Maximum array size considered when doing a combine"));
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.
164 static cl::opt
<unsigned> ShouldLowerDbgDeclare("instcombine-lower-dbg-declare",
165 cl::Hidden
, cl::init(true));
167 Optional
<Instruction
*>
168 InstCombiner::targetInstCombineIntrinsic(IntrinsicInst
&II
) {
169 // Handle target specific intrinsics
170 if (II
.getCalledFunction()->isTargetIntrinsic()) {
171 return TTI
.instCombineIntrinsic(*this, II
);
176 Optional
<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
,
187 Optional
<Value
*> InstCombiner::targetSimplifyDemandedVectorEltsIntrinsic(
188 IntrinsicInst
&II
, APInt DemandedElts
, APInt
&UndefElts
, APInt
&UndefElts2
,
190 std::function
<void(Instruction
*, unsigned, APInt
, APInt
&)>
192 // Handle target specific intrinsics
193 if (II
.getCalledFunction()->isTargetIntrinsic()) {
194 return TTI
.simplifyDemandedVectorEltsIntrinsic(
195 *this, II
, DemandedElts
, UndefElts
, UndefElts2
, UndefElts3
,
201 Value
*InstCombinerImpl::EmitGEPOffset(User
*GEP
) {
202 return llvm::EmitGEPOffset(&Builder
, DL
, GEP
);
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.
214 bool InstCombinerImpl::shouldChangeType(unsigned FromWidth
,
215 unsigned ToWidth
) const {
216 bool FromLegal
= FromWidth
== 1 || DL
.isLegalInteger(FromWidth
);
217 bool ToLegal
= ToWidth
== 1 || DL
.isLegalInteger(ToWidth
);
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))
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
)
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
)
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
242 bool 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())
248 unsigned FromWidth
= From
->getPrimitiveSizeInBits();
249 unsigned ToWidth
= To
->getPrimitiveSizeInBits();
250 return shouldChangeType(FromWidth
, ToWidth
);
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.
258 static bool maintainNoSignedWrap(BinaryOperator
&I
, Value
*B
, Value
*C
) {
259 auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(&I
);
260 if (!OBO
|| !OBO
->hasNoSignedWrap())
263 // We reason about Add and Sub Only.
264 Instruction::BinaryOps Opcode
= I
.getOpcode();
265 if (Opcode
!= Instruction::Add
&& Opcode
!= Instruction::Sub
)
268 const APInt
*BVal
, *CVal
;
269 if (!match(B
, m_APInt(BVal
)) || !match(C
, m_APInt(CVal
)))
272 bool Overflow
= false;
273 if (Opcode
== Instruction::Add
)
274 (void)BVal
->sadd_ov(*CVal
, Overflow
);
276 (void)BVal
->ssub_ov(*CVal
, Overflow
);
281 static bool hasNoUnsignedWrap(BinaryOperator
&I
) {
282 auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(&I
);
283 return OBO
&& OBO
->hasNoUnsignedWrap();
286 static bool hasNoSignedWrap(BinaryOperator
&I
) {
287 auto *OBO
= dyn_cast
<OverflowingBinaryOperator
>(&I
);
288 return OBO
&& OBO
->hasNoSignedWrap();
291 /// Conservatively clears subclassOptionalData after a reassociation or
292 /// commutation. We preserve fast-math flags when applicable as they can be
294 static void ClearSubclassDataAfterReassociation(BinaryOperator
&I
) {
295 FPMathOperator
*FPMO
= dyn_cast
<FPMathOperator
>(&I
);
297 I
.clearSubclassOptionalData();
301 FastMathFlags FMF
= I
.getFastMathFlags();
302 I
.clearSubclassOptionalData();
303 I
.setFastMathFlags(FMF
);
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))
310 static bool simplifyAssocCastAssoc(BinaryOperator
*BinOp1
,
311 InstCombinerImpl
&IC
) {
312 auto *Cast
= dyn_cast
<CastInst
>(BinOp1
->getOperand(0));
313 if (!Cast
|| !Cast
->hasOneUse())
316 // TODO: Enhance logic for other casts and remove this check.
317 auto CastOpcode
= Cast
->getOpcode();
318 if (CastOpcode
!= Instruction::ZExt
)
321 // TODO: Enhance logic for other BinOps and remove this check.
322 if (!BinOp1
->isBitwiseLogicOp())
325 auto AssocOpcode
= BinOp1
->getOpcode();
326 auto *BinOp2
= dyn_cast
<BinaryOperator
>(Cast
->getOperand(0));
327 if (!BinOp2
|| !BinOp2
->hasOneUse() || BinOp2
->getOpcode() != AssocOpcode
)
331 if (!match(BinOp1
->getOperand(1), m_Constant(C1
)) ||
332 !match(BinOp2
->getOperand(1), m_Constant(C2
)))
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.
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
);
349 // Simplifies IntToPtr/PtrToInt RoundTrip Cast To BitCast.
350 // inttoptr ( ptrtoint (x) ) --> x
351 Value
*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();
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
,
369 /// This performs a few simplifications for operators that are associative or
372 /// Commutative operators:
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.
378 /// Associative operators:
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.
383 /// Associative and commutative operators:
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.
389 bool InstCombinerImpl::SimplifyAssociativeOrCommutative(BinaryOperator
&I
) {
390 Instruction::BinaryOps Opcode
= I
.getOpcode();
391 bool Changed
= false;
394 // Order operands such that they are listed from right (least complex) to
395 // left (most complex). This puts constants before unary operators before
397 if (I
.isCommutative() && getComplexity(I
.getOperand(0)) <
398 getComplexity(I
.getOperand(1)))
399 Changed
= !I
.swapOperands();
401 BinaryOperator
*Op0
= dyn_cast
<BinaryOperator
>(I
.getOperand(0));
402 BinaryOperator
*Op1
= dyn_cast
<BinaryOperator
>(I
.getOperand(1));
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);
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
);
419 // Conservatively clear all optional flags since they may not be
420 // preserved by the reassociation. Reset nsw/nuw based on the above
422 ClearSubclassDataAfterReassociation(I
);
424 // Note: this is only valid because SimplifyBinOp doesn't look at
425 // the operands to Op0.
427 I
.setHasNoUnsignedWrap(true);
430 I
.setHasNoSignedWrap(true);
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);
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
);
459 if (I
.isAssociative() && I
.isCommutative()) {
460 if (simplifyAssocCastAssoc(&I
, *this)) {
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);
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
);
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);
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
);
506 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
507 // if C1 and C2 are constants.
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
);
521 if (isa
<FPMathOperator
>(NewBO
)) {
522 FastMathFlags Flags
= I
.getFastMathFlags();
523 Flags
&= Op0
->getFastMathFlags();
524 Flags
&= Op1
->getFastMathFlags();
525 NewBO
->setFastMathFlags(Flags
);
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
);
535 I
.setHasNoUnsignedWrap(true);
542 // No further simplifications.
547 /// Return whether "X LOp (Y ROp Z)" is always equal to
548 /// "(X LOp Y) ROp (X LOp Z)".
549 static 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
;
556 // X | (Y & Z) <--> (X | Y) & (X | Z)
557 if (LOp
== Instruction::Or
)
558 return ROp
== Instruction::And
;
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
;
568 /// Return whether "(X LOp Y) ROp Z" is always equal to
569 /// "(X ROp Z) LOp (Y ROp Z)".
570 static bool rightDistributesOverLeft(Instruction::BinaryOps LOp
,
571 Instruction::BinaryOps ROp
) {
572 if (Instruction::isCommutative(ROp
))
573 return leftDistributesOverRight(ROp
, LOp
);
575 // (X {&|^} Y) >> Z <--> (X >> Z) {&|^} (Y >> Z) for all shifts.
576 return Instruction::isBitwiseLogicOp(LOp
) && Instruction::isShift(ROp
);
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
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).
585 static Value
*getIdentityValue(Instruction::BinaryOps Opcode
, Value
*V
) {
586 if (isa
<Constant
>(V
))
589 return ConstantExpr::getBinOpIdentity(Opcode
, V
->getType());
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.
597 static Instruction::BinaryOps
598 getBinOpsForFactorization(Instruction::BinaryOps TopOpcode
, BinaryOperator
*Op
,
599 Value
*&LHS
, Value
*&RHS
) {
600 assert(Op
&& "Expected a binary operator");
601 LHS
= Op
->getOperand(0);
602 RHS
= Op
->getOperand(1);
603 if (TopOpcode
== Instruction::Add
|| TopOpcode
== Instruction::Sub
) {
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
;
610 // TODO: We can add other conversions e.g. shr => div etc.
612 return Op
->getOpcode();
615 /// This tries to simplify binary operations by factorizing out common terms
616 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
617 Value
*InstCombinerImpl::tryFactorization(BinaryOperator
&I
,
618 Instruction::BinaryOps InnerOpcode
,
619 Value
*A
, Value
*B
, Value
*C
,
621 assert(A
&& B
&& C
&& D
&& "All values must be provided");
624 Value
*SimplifiedInst
= nullptr;
625 Value
*LHS
= I
.getOperand(0), *RHS
= I
.getOperand(1);
626 Instruction::BinaryOps TopLevelOpcode
= I
.getOpcode();
628 // Does "X op' Y" always equal "Y op' X"?
629 bool InnerCommutative
= Instruction::isCommutative(InnerOpcode
);
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
)) {
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());
646 SimplifiedInst
= Builder
.CreateBinOp(InnerOpcode
, A
, V
);
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
)) {
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
));
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());
666 SimplifiedInst
= Builder
.CreateBinOp(InnerOpcode
, V
, B
);
670 if (SimplifiedInst
) {
672 SimplifiedInst
->takeName(&I
);
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
)) {
679 if (isa
<OverflowingBinaryOperator
>(&I
)) {
680 HasNSW
= I
.hasNoSignedWrap();
681 HasNUW
= I
.hasNoUnsignedWrap();
684 if (auto *LOBO
= dyn_cast
<OverflowingBinaryOperator
>(LHS
)) {
685 HasNSW
&= LOBO
->hasNoSignedWrap();
686 HasNUW
&= LOBO
->hasNoUnsignedWrap();
689 if (auto *ROBO
= dyn_cast
<OverflowingBinaryOperator
>(RHS
)) {
690 HasNSW
&= ROBO
->hasNoSignedWrap();
691 HasNUW
&= ROBO
->hasNoUnsignedWrap();
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
700 // %Z = mul nsw i16 %X, C+1
702 // iff C+1 isn't INT_MIN
704 if (match(V
, m_APInt(CInt
))) {
705 if (!CInt
->isMinSignedValue())
706 BO
->setHasNoSignedWrap(HasNSW
);
709 // nuw can be propagated with any constant or nuw value.
710 BO
->setHasNoUnsignedWrap(HasNUW
);
715 return SimplifiedInst
;
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.
723 Value
*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();
731 Value
*A
, *B
, *C
, *D
;
732 Instruction::BinaryOps LHSOpcode
, RHSOpcode
;
734 LHSOpcode
= getBinOpsForFactorization(TopLevelOpcode
, Op0
, A
, B
);
736 RHSOpcode
= getBinOpsForFactorization(TopLevelOpcode
, Op1
, C
, D
);
738 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
740 if (Op0
&& Op1
&& LHSOpcode
== RHSOpcode
)
741 if (Value
*V
= tryFactorization(I
, LHSOpcode
, A
, B
, C
, D
))
744 // The instruction has the form "(A op' B) op (C)". Try to factorize common
747 if (Value
*Ident
= getIdentityValue(LHSOpcode
, RHS
))
748 if (Value
*V
= tryFactorization(I
, LHSOpcode
, A
, B
, RHS
, Ident
))
751 // The instruction has the form "(B) op (C op' D)". Try to factorize common
754 if (Value
*Ident
= getIdentityValue(RHSOpcode
, LHS
))
755 if (Value
*V
= tryFactorization(I
, RHSOpcode
, LHS
, Ident
, C
, D
))
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'
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
);
771 // Do "A op C" and "B op C" both simplify?
773 // They do! Return "L op' R".
775 C
= Builder
.CreateBinOp(InnerOpcode
, L
, R
);
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".
784 C
= Builder
.CreateBinOp(TopLevelOpcode
, B
, C
);
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".
793 C
= Builder
.CreateBinOp(TopLevelOpcode
, A
, C
);
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'
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
);
810 // Do "A op B" and "A op C" both simplify?
812 // They do! Return "L op' R".
814 A
= Builder
.CreateBinOp(InnerOpcode
, L
, R
);
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".
823 A
= Builder
.CreateBinOp(TopLevelOpcode
, A
, C
);
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".
832 A
= Builder
.CreateBinOp(TopLevelOpcode
, A
, B
);
838 return SimplifySelectsFeedingBinaryOp(I
, LHS
, RHS
);
841 Value
*InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator
&I
,
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
)
851 BuilderTy::FastMathFlagGuard
Guard(Builder
);
852 if (isa
<FPMathOperator
>(&I
)) {
853 FMF
= I
.getFastMathFlags();
854 Builder
.setFastMathFlags(FMF
);
857 Instruction::BinaryOps Opcode
= I
.getOpcode();
858 SimplifyQuery Q
= SQ
.getWithInstruction(&I
);
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)
864 True
= SimplifyBinOp(Opcode
, B
, E
, FMF
, Q
);
865 False
= SimplifyBinOp(Opcode
, C
, F
, FMF
, Q
);
867 if (LHS
->hasOneUse() && RHS
->hasOneUse()) {
869 True
= Builder
.CreateBinOp(Opcode
, B
, E
);
870 else if (True
&& !False
)
871 False
= Builder
.CreateBinOp(Opcode
, C
, F
);
873 } else if (LHSIsSelect
&& LHS
->hasOneUse()) {
874 // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
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)
881 True
= SimplifyBinOp(Opcode
, LHS
, E
, FMF
, Q
);
882 False
= SimplifyBinOp(Opcode
, LHS
, F
, FMF
, Q
);
888 Value
*SI
= Builder
.CreateSelect(Cond
, True
, False
);
893 /// Freely adapt every user of V as-if V was changed to !V.
894 /// WARNING: only if canFreelyInvertAllUsersOf() said this can be done.
895 void 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
);
901 SI
->swapProfMetadata();
904 case Instruction::Br
:
905 cast
<BranchInst
>(U
)->swapSuccessors(); // swaps prof metadata too
907 case Instruction::Xor
:
908 replaceInstUsesWith(cast
<Instruction
>(*U
), I
);
911 llvm_unreachable("Got unexpected user - out of sync with "
912 "canFreelyInvertAllUsersOf() ?");
917 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
918 /// constant zero (which is the 'negate' form).
919 Value
*InstCombinerImpl::dyn_castNegVal(Value
*V
) const {
921 if (match(V
, m_Neg(m_Value(NegV
))))
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
);
928 if (ConstantDataVector
*C
= dyn_cast
<ConstantDataVector
>(V
))
929 if (C
->getType()->getElementType()->isIntegerTy())
930 return ConstantExpr::getNeg(C
);
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
);
938 if (isa
<UndefValue
>(Elt
))
941 if (!isa
<ConstantInt
>(Elt
))
944 return ConstantExpr::getNeg(CV
);
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
);
956 static 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());
961 if (auto *II
= dyn_cast
<IntrinsicInst
>(&I
)) {
962 assert(canConstantFoldCallTo(II
, cast
<Function
>(II
->getCalledOperand())) &&
963 "Expected constant-foldable intrinsic");
964 Intrinsic::ID IID
= II
->getIntrinsicID();
965 if (II
->getNumArgOperands() == 1)
966 return Builder
.CreateUnaryIntrinsic(IID
, SO
);
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");
973 assert(isa
<Constant
>(II
->getArgOperand(1)) && "Expected constant operand");
974 return Builder
.CreateBinaryIntrinsic(IID
, SO
, II
->getArgOperand(1));
977 assert(I
.isBinaryOp() && "Unexpected opcode for select folding");
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
));
983 if (auto *SOC
= dyn_cast
<Constant
>(SO
)) {
985 return ConstantExpr::get(I
.getOpcode(), SOC
, ConstOperand
);
986 return ConstantExpr::get(I
.getOpcode(), ConstOperand
, SOC
);
989 Value
*Op0
= SO
, *Op1
= ConstOperand
;
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
);
1002 Instruction
*InstCombinerImpl::FoldOpIntoSelect(Instruction
&Op
,
1004 // Don't modify shared select instructions.
1005 if (!SI
->hasOneUse())
1008 Value
*TV
= SI
->getTrueValue();
1009 Value
*FV
= SI
->getFalseValue();
1010 if (!(isa
<Constant
>(TV
) || isa
<Constant
>(FV
)))
1013 // Bool selects with constant operands can be folded to logical ops.
1014 if (SI
->getType()->isIntOrIntVectorTy(1))
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());
1023 // Verify that either both or neither are vectors.
1024 if ((SrcTy
== nullptr) != (DestTy
== nullptr))
1027 // If vectors, verify that they have the same number of elements.
1028 if (SrcTy
&& SrcTy
->getElementCount() != DestTy
->getElementCount())
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);
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
) {
1050 // Test for vector constants.
1051 Constant
*ConstA
, *ConstB
;
1052 if (!match(A
, m_Constant(ConstA
)) || !match(B
, m_Constant(ConstB
)))
1055 // TODO: Deal with FP constants?
1056 if (!A
->getType()->isIntOrIntVectorTy() || A
->getType() != B
->getType())
1059 // Compare for equality including undefs as equal.
1060 auto *Cmp
= ConstantExpr::getCompare(ICmpInst::ICMP_EQ
, ConstA
, ConstB
);
1062 return match(Cmp
, m_APIntAllowUndef(C
)) && C
->isOneValue();
1065 if ((areLooselyEqual(TV
, Op0
) && areLooselyEqual(FV
, Op1
)) ||
1066 (areLooselyEqual(FV
, Op0
) && areLooselyEqual(TV
, Op1
)))
1071 Value
*NewTV
= foldOperationIntoSelectOperand(Op
, TV
, Builder
);
1072 Value
*NewFV
= foldOperationIntoSelectOperand(Op
, FV
, Builder
);
1073 return SelectInst::Create(SI
->getCondition(), NewTV
, NewFV
, "", nullptr, SI
);
1076 static 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
));
1081 if (auto *InC
= dyn_cast
<Constant
>(InV
)) {
1083 return ConstantExpr::get(I
->getOpcode(), InC
, C
);
1084 return ConstantExpr::get(I
->getOpcode(), C
, InC
);
1087 Value
*Op0
= InV
, *Op1
= C
;
1089 std::swap(Op0
, Op1
);
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
);
1098 Instruction
*InstCombinerImpl::foldOpIntoPhi(Instruction
&I
, PHINode
*PN
) {
1099 unsigned NumPHIValues
= PN
->getNumIncomingValues();
1100 if (NumPHIValues
== 0)
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
))
1113 // Otherwise, we can replace *all* users with the new PHI we form.
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
)))
1129 if (isa
<PHINode
>(InVal
)) return nullptr; // Itself a phi.
1130 if (NonConstBB
) return nullptr; // More than one non-const value.
1132 NonConstBB
= PN
->getIncomingBlock(i
);
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
)
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
1143 if (isPotentiallyReachable(I
.getParent(), NonConstBB
, nullptr, &DT
, LI
))
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
))
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
);
1163 // If we are going to have to insert a new computation, do so right before the
1164 // predecessor's terminator.
1166 Builder
.SetInsertPoint(NonConstBB
->getTerminator());
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
1187 if (InC
&& isa
<ConstantInt
>(InC
))
1188 InV
= InC
->isNullValue() ? FalseVInPred
: TrueVInPred
;
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");
1202 NewPN
->addIncoming(InV
, ThisBB
);
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
);
1211 InV
= Builder
.CreateCmp(CI
->getPredicate(), PN
->getIncomingValue(i
),
1213 NewPN
->addIncoming(InV
, PN
->getIncomingBlock(i
));
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
),
1219 NewPN
->addIncoming(InV
, PN
->getIncomingBlock(i
));
1221 } else if (isa
<FreezeInst
>(&I
)) {
1222 for (unsigned i
= 0; i
!= NumPHIValues
; ++i
) {
1224 if (NonConstBB
== PN
->getIncomingBlock(i
))
1225 InV
= Builder
.CreateFreeze(PN
->getIncomingValue(i
), "phi.fr");
1227 InV
= PN
->getIncomingValue(i
);
1228 NewPN
->addIncoming(InV
, PN
->getIncomingBlock(i
));
1231 CastInst
*CI
= cast
<CastInst
>(&I
);
1232 Type
*RetTy
= CI
->getType();
1233 for (unsigned i
= 0; i
!= NumPHIValues
; ++i
) {
1235 if (Constant
*InC
= dyn_cast
<Constant
>(PN
->getIncomingValue(i
)))
1236 InV
= ConstantExpr::getCast(CI
->getOpcode(), InC
, RetTy
);
1238 InV
= Builder
.CreateCast(CI
->getOpcode(), PN
->getIncomingValue(i
),
1239 I
.getType(), "phi.cast");
1240 NewPN
->addIncoming(InV
, PN
->getIncomingBlock(i
));
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
);
1250 return replaceInstUsesWith(I
, NewPN
);
1253 Instruction
*InstCombinerImpl::foldBinOpIntoSelectOrPhi(BinaryOperator
&I
) {
1254 if (!isa
<Constant
>(I
.getOperand(1)))
1257 if (auto *Sel
= dyn_cast
<SelectInst
>(I
.getOperand(0))) {
1258 if (Instruction
*NewSel
= FoldOpIntoSelect(I
, Sel
))
1260 } else if (auto *PN
= dyn_cast
<PHINode
>(I
.getOperand(0))) {
1261 if (Instruction
*NewPhi
= foldOpIntoPhi(I
, PN
))
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.
1272 InstCombinerImpl::FindElementAtOffset(PointerType
*PtrTy
, int64_t Offset
,
1273 SmallVectorImpl
<Value
*> &NewIndices
) {
1274 Type
*Ty
= PtrTy
->getElementType();
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
;
1287 // Handle hosts where % returns negative instead of values [0..TySize).
1291 assert(Offset
>= 0);
1293 assert((uint64_t)Offset
< (uint64_t)TySize
&& "Out of range offset");
1296 NewIndices
.push_back(ConstantInt::get(IndexTy
, FirstIdx
));
1298 // Index into the types. If we fail, set OrigBase to null.
1300 // Indexing into tail padding between struct/array elements.
1301 if (uint64_t(Offset
* 8) >= DL
.getTypeSizeInBits(Ty
))
1304 if (StructType
*STy
= dyn_cast
<StructType
>(Ty
)) {
1305 const StructLayout
*SL
= DL
.getStructLayout(STy
);
1306 assert(Offset
< (int64_t)SL
->getSizeInBytes() &&
1307 "Offset must stay within the indexed type");
1309 unsigned Elt
= SL
->getElementContainingOffset(Offset
);
1310 NewIndices
.push_back(ConstantInt::get(Type::getInt32Ty(Ty
->getContext()),
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");
1318 NewIndices
.push_back(ConstantInt::get(IndexTy
,Offset
/EltSize
));
1320 Ty
= AT
->getElementType();
1322 // Otherwise, we can't index into the middle of this atomic type, bail.
1330 static 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
1334 if (GEP
.hasAllZeroIndices() && !Src
.hasAllZeroIndices() &&
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.
1342 Value
*InstCombinerImpl::Descale(Value
*Val
, APInt Scale
, bool &NoSignedWrap
) {
1343 assert(isa
<IntegerType
>(Val
->getType()) && "Can only descale integers!");
1344 assert(cast
<IntegerType
>(Val
->getType())->getBitWidth() ==
1345 Scale
.getBitWidth() && "Scale not compatible with value!");
1347 // If Val is zero or Scale is one then Val = Val * Scale.
1348 if (match(Val
, m_Zero()) || Scale
== 1) {
1349 NoSignedWrap
= true;
1353 // If Scale is zero then it does not divide Val.
1354 if (Scale
.isMinValue())
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
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
1367 // Then to modify a term at the bottom:
1370 // M1 = Z * Y || Replaced M2 with Z
1372 // Then to work back up correcting nsw flags.
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.
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
;
1383 // Set if the transform requires a descaling at deeper levels that doesn't
1385 bool RequireNoSignedWrap
= false;
1387 // Log base 2 of the scale. Negative if not a power of 2.
1388 int32_t logScale
= Scale
.exactLogBase2();
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.
1398 // Replace with the quotient in the parent.
1399 Op
= ConstantInt::get(CI
->getType(), Quotient
);
1400 NoSignedWrap
= true;
1404 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(Op
)) {
1405 if (BO
->getOpcode() == Instruction::Mul
) {
1407 NoSignedWrap
= BO
->hasNoSignedWrap();
1408 if (RequireNoSignedWrap
&& !NoSignedWrap
)
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);
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.
1426 // Otherwise drill down into the constant.
1427 if (!Op
->hasOneUse())
1430 Parent
= std::make_pair(BO
, 1);
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())
1439 Parent
= std::make_pair(BO
, 0);
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
)
1450 Value
*LHS
= BO
->getOperand(0);
1451 int32_t Amt
= cast
<ConstantInt
>(BO
->getOperand(1))->
1452 getLimitedValue(Scale
.getBitWidth());
1455 if (Amt
== logScale
) {
1456 // Multiplication by exactly the scale, replace the multiplication
1457 // by its left-hand side in the parent.
1461 if (Amt
< logScale
|| !Op
->hasOneUse())
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
);
1472 if (!Op
->hasOneUse())
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.
1488 assert(SmallScale
.exactLogBase2() == logScale
);
1489 // Require that Y * SmallScale must not overflow.
1490 RequireNoSignedWrap
= true;
1492 // Drill down through the cast.
1493 Parent
= std::make_pair(Cast
, 0);
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
)
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())
1514 assert(Scale
.exactLogBase2() == logScale
);
1519 // Unsupported expression, bail out.
1523 // If Op is zero then Val = Op * Scale.
1524 if (match(Op
, m_Zero())) {
1525 NoSignedWrap
= true;
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
1535 // The expression only had one term.
1538 // Rewrite the parent using the descaled version of its operand.
1539 assert(Parent
.first
->hasOneUse() && "Drilled down when more than one use!");
1540 assert(Op
!= Parent
.first
->getOperand(Parent
.second
) &&
1541 "Descaling was a no-op?");
1542 replaceOperand(*Parent
.first
, Parent
.second
, Op
);
1543 Worklist
.push(Parent
.first
);
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
;
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
);
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;
1569 assert((Ancestor
->getOpcode() != Instruction::SExt
|| NoSignedWrap
) &&
1570 "Failed to keep proper track of nsw flags while drilling down?");
1572 if (Ancestor
== Val
)
1573 // Got to the top, all done!
1576 // Move up one level in the expression.
1577 assert(Ancestor
->hasOneUse() && "Drilled down when more than one use!");
1578 Ancestor
= Ancestor
->user_back();
1582 Instruction
*InstCombinerImpl::foldVectorBinop(BinaryOperator
&Inst
) {
1583 if (!isa
<VectorType
>(Inst
.getType()))
1586 BinaryOperator::BinaryOps Opcode
= Inst
.getOpcode();
1587 Value
*LHS
= Inst
.getOperand(0), *RHS
= Inst
.getOperand(1);
1588 assert(cast
<VectorType
>(LHS
->getType())->getElementCount() ==
1589 cast
<VectorType
>(Inst
.getType())->getElementCount());
1590 assert(cast
<VectorType
>(RHS
->getType())->getElementCount() ==
1591 cast
<VectorType
>(Inst
.getType())->getElementCount());
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
1596 Value
*L0
, *L1
, *R0
, *R1
;
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
);
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.
1620 if (!isSafeToSpeculativelyExecute(&Inst
))
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
);
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.
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
);
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
))) &&
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
)) {
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
);
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
1673 auto *InstVTy
= dyn_cast
<FixedVectorType
>(Inst
.getType());
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() &&
1681 "Shuffle should not change scalar type");
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");
1700 Constant
*NewCElt
= NewVecC
[ShMask
[I
]];
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
) {
1712 NewVecC
[ShMask
[I
]] = CElt
;
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())) {
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
);
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
);
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
);
1756 ArrayRef
<int> MaskC
;
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
)
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.
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);
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
);
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
);
1794 if (auto *NewInstBO
= dyn_cast
<BinaryOperator
>(NewBO
))
1795 NewInstBO
->copyIRFlags(R
);
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.
1805 Instruction
*InstCombinerImpl::narrowMathIfNoOverflow(BinaryOperator
&BO
) {
1806 // We need at least one extended operand.
1807 Value
*Op0
= BO
.getOperand(0), *Op1
= BO
.getOperand(1);
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
);
1815 bool IsSext
= match(Op0
, m_SExt(m_Value(X
)));
1816 if (!IsSext
&& !match(Op0
, m_ZExt(m_Value(X
))))
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
;
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.
1829 if (!Op0
->hasOneUse() || !match(Op1
, m_Constant(WideC
)))
1831 Constant
*NarrowC
= ConstantExpr::getTrunc(WideC
, X
->getType());
1832 if (ConstantExpr::getCast(CastOpc
, NarrowC
, BO
.getType()) != WideC
)
1837 // Swap back now that we found our operands.
1838 if (BO
.getOpcode() == Instruction::Sub
)
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
))
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
)) {
1851 NewBinOp
->setHasNoSignedWrap();
1853 NewBinOp
->setHasNoUnsignedWrap();
1855 return CastInst::Create(CastOpc
, NarrowBO
, BO
.getType());
1858 static bool isMergedGEPInBounds(GEPOperator
&GEP1
, GEPOperator
&GEP2
) {
1859 // At least one GEP must be inbounds.
1860 if (!GEP1
.isInBounds() && !GEP2
.isInBounds())
1863 return (GEP1
.isInBounds() || GEP1
.hasAllZeroIndices()) &&
1864 (GEP2
.isInBounds() || GEP2
.hasAllZeroIndices());
1867 /// Thread a GEP operation with constant indices through the constant true/false
1868 /// arms of a select.
1869 static Instruction
*foldSelectGEP(GetElementPtrInst
&GEP
,
1870 InstCombiner::BuilderTy
&Builder
) {
1871 if (!GEP
.hasAllConstantIndices())
1876 Constant
*TrueC
, *FalseC
;
1877 if (!match(GEP
.getPointerOperand(), m_Instruction(Sel
)) ||
1879 m_Select(m_Value(Cond
), m_Constant(TrueC
), m_Constant(FalseC
))))
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
);
1895 Instruction
*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
);
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
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
,
1913 return replaceInstUsesWith(GEP
, V
);
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
1922 Value
*PtrOp
= GEP
.getOperand(0);
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;
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());
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
;
1936 // Skip indices into struct types.
1940 Type
*IndexTy
= (*I
)->getType();
1941 Type
*NewIndexType
=
1942 IndexTy
->isVectorTy()
1943 ? VectorType::get(NewScalarIndexTy
,
1944 cast
<VectorType
>(IndexTy
)->getElementCount())
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
);
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);
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));
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
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())
1989 // As for Op1 above, don't try to fold a GEP into itself.
1993 // Keep track of the type as we walk the GEP.
1994 Type
*CurTy
= nullptr;
1996 for (unsigned J
= 0, F
= Op1
->getNumOperands(); J
!= F
; ++J
) {
1997 if (Op1
->getOperand(J
)->getType() != Op2
->getOperand(J
)->getType())
2000 if (Op1
->getOperand(J
) != Op2
->getOperand(J
)) {
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
2006 // The first two arguments can vary for any GEP, the rest have to be
2007 // static for struct slots
2009 assert(CurTy
&& "No current type?");
2010 if (CurTy
->isStructTy())
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.
2026 // Sink down a layer of the type for the next iteration.
2029 CurTy
= Op1
->getSourceElementType();
2032 GetElementPtrInst::getTypeAtIndex(CurTy
, Op1
->getOperand(J
));
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
2041 if (DI
!= -1 && !PN
->hasOneUse())
2044 auto *NewGEP
= cast
<GetElementPtrInst
>(Op1
->clone());
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.
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
2054 IRBuilderBase::InsertPointGuard
Guard(Builder
);
2055 Builder
.SetInsertPoint(PN
);
2056 NewPN
= Builder
.CreatePHI(Op1
->getOperand(DI
)->getType(),
2057 PN
->getNumOperands());
2060 for (auto &I
: PN
->operands())
2061 NewPN
->addIncoming(cast
<GEPOperator
>(I
)->getOperand(DI
),
2062 PN
->getIncomingBlock(I
));
2064 NewGEP
->setOperand(DI
, NewPN
);
2067 GEP
.getParent()->getInstList().insert(
2068 GEP
.getParent()->getFirstInsertionPt(), NewGEP
);
2069 replaceOperand(GEP
, 0, NewGEP
);
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
))
2080 if (Src
->getNumOperands() == 2 && GEP
.getNumOperands() == 2 &&
2082 Value
*GO1
= GEP
.getOperand(1);
2083 Value
*SO1
= Src
->getOperand(1);
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.
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
);
2118 // -- have to recreate %src & %gep
2119 // put NewSrc at same location as %src
2120 Builder
.SetInsertPoint(cast
<Instruction
>(PtrOp
));
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());
2135 // Guard the gep(gep) fold so we don't create an add inside a loop
2136 // when there wasn't an equivalent instruction there before.
2137 bool DifferentLoops
= false;
2139 if (auto *GEPLoop
= LI
->getLoopFor(GEP
.getParent()))
2140 if (auto *SrcOpI
= dyn_cast
<Instruction
>(Src
))
2141 if (LI
->getLoopFor(SrcOpI
->getParent()) != GEPLoop
)
2142 DifferentLoops
= true;
2144 // Fold (gep(gep(Ptr,Idx0),Idx1) -> gep(Ptr,add(Idx0,Idx1))
2145 if (!DifferentLoops
&& GO1
->getType() == SO1
->getType()) {
2146 bool NewInBounds
= GEP
.isInBounds() && Src
->isInBounds();
2148 Builder
.CreateAdd(GO1
, SO1
, GEP
.getName() + ".idx",
2149 /*HasNUW*/ false, /*HasNSW*/ NewInBounds
);
2150 auto *NewGEP
= GetElementPtrInst::Create(
2151 GEPEltType
, Src
->getPointerOperand(), {NewIdx
});
2152 NewGEP
->setIsInBounds(NewInBounds
);
2157 // Note that if our source is a gep chain itself then we wait for that
2158 // chain to be resolved before we perform this transformation. This
2159 // avoids us creating a TON of code in some cases.
2160 if (auto *SrcGEP
= dyn_cast
<GEPOperator
>(Src
->getOperand(0)))
2161 if (SrcGEP
->getNumOperands() == 2 && shouldMergeGEPs(*Src
, *SrcGEP
))
2162 return nullptr; // Wait until our source is folded to completion.
2164 SmallVector
<Value
*, 8> Indices
;
2166 // Find out whether the last index in the source GEP is a sequential idx.
2167 bool EndsWithSequential
= false;
2168 for (gep_type_iterator I
= gep_type_begin(*Src
), E
= gep_type_end(*Src
);
2170 EndsWithSequential
= I
.isSequential();
2172 // Can we combine the two pointer arithmetics offsets?
2173 if (EndsWithSequential
) {
2174 // Replace: gep (gep %P, long B), long A, ...
2175 // With: T = long A+B; gep %P, T, ...
2176 Value
*SO1
= Src
->getOperand(Src
->getNumOperands()-1);
2177 Value
*GO1
= GEP
.getOperand(1);
2179 // If they aren't the same type, then the input hasn't been processed
2180 // by the loop above yet (which canonicalizes sequential index types to
2181 // intptr_t). Just avoid transforming this until the input has been
2183 if (SO1
->getType() != GO1
->getType())
2187 SimplifyAddInst(GO1
, SO1
, false, false, SQ
.getWithInstruction(&GEP
));
2188 // Only do the combine when we are sure the cost after the
2189 // merge is never more than that before the merge.
2193 // Update the GEP in place if possible.
2194 if (Src
->getNumOperands() == 2) {
2195 GEP
.setIsInBounds(isMergedGEPInBounds(*Src
, *cast
<GEPOperator
>(&GEP
)));
2196 replaceOperand(GEP
, 0, Src
->getOperand(0));
2197 replaceOperand(GEP
, 1, Sum
);
2200 Indices
.append(Src
->op_begin()+1, Src
->op_end()-1);
2201 Indices
.push_back(Sum
);
2202 Indices
.append(GEP
.op_begin()+2, GEP
.op_end());
2203 } else if (isa
<Constant
>(*GEP
.idx_begin()) &&
2204 cast
<Constant
>(*GEP
.idx_begin())->isNullValue() &&
2205 Src
->getNumOperands() != 1) {
2206 // Otherwise we can do the fold if the first index of the GEP is a zero
2207 Indices
.append(Src
->op_begin()+1, Src
->op_end());
2208 Indices
.append(GEP
.idx_begin()+1, GEP
.idx_end());
2211 if (!Indices
.empty())
2212 return isMergedGEPInBounds(*Src
, *cast
<GEPOperator
>(&GEP
))
2213 ? GetElementPtrInst::CreateInBounds(
2214 Src
->getSourceElementType(), Src
->getOperand(0), Indices
,
2216 : GetElementPtrInst::Create(Src
->getSourceElementType(),
2217 Src
->getOperand(0), Indices
,
2221 // Skip if GEP source element type is scalable. The type alloc size is unknown
2223 if (GEP
.getNumIndices() == 1 && !IsGEPSrcEleScalable
) {
2224 unsigned AS
= GEP
.getPointerAddressSpace();
2225 if (GEP
.getOperand(1)->getType()->getScalarSizeInBits() ==
2226 DL
.getIndexSizeInBits(AS
)) {
2227 uint64_t TyAllocSize
= DL
.getTypeAllocSize(GEPEltType
).getFixedSize();
2229 bool Matched
= false;
2232 if (TyAllocSize
== 1) {
2233 V
= GEP
.getOperand(1);
2235 } else if (match(GEP
.getOperand(1),
2236 m_AShr(m_Value(V
), m_ConstantInt(C
)))) {
2237 if (TyAllocSize
== 1ULL << C
)
2239 } else if (match(GEP
.getOperand(1),
2240 m_SDiv(m_Value(V
), m_ConstantInt(C
)))) {
2241 if (TyAllocSize
== C
)
2245 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X)) to (bitcast Y), but
2246 // only if both point to the same underlying object (otherwise provenance
2247 // is not necessarily retained).
2249 Value
*X
= GEP
.getOperand(0);
2251 match(V
, m_Sub(m_PtrToInt(m_Value(Y
)), m_PtrToInt(m_Specific(X
)))) &&
2252 getUnderlyingObject(X
) == getUnderlyingObject(Y
))
2253 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y
, GEPType
);
2257 // We do not handle pointer-vector geps here.
2258 if (GEPType
->isVectorTy())
2261 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
2262 Value
*StrippedPtr
= PtrOp
->stripPointerCasts();
2263 PointerType
*StrippedPtrTy
= cast
<PointerType
>(StrippedPtr
->getType());
2265 if (StrippedPtr
!= PtrOp
) {
2266 bool HasZeroPointerIndex
= false;
2267 Type
*StrippedPtrEltTy
= StrippedPtrTy
->getElementType();
2269 if (auto *C
= dyn_cast
<ConstantInt
>(GEP
.getOperand(1)))
2270 HasZeroPointerIndex
= C
->isZero();
2272 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
2273 // into : GEP [10 x i8]* X, i32 0, ...
2275 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
2276 // into : GEP i8* X, ...
2278 // This occurs when the program declares an array extern like "int X[];"
2279 if (HasZeroPointerIndex
) {
2280 if (auto *CATy
= dyn_cast
<ArrayType
>(GEPEltType
)) {
2281 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
2282 if (CATy
->getElementType() == StrippedPtrEltTy
) {
2283 // -> GEP i8* X, ...
2284 SmallVector
<Value
*, 8> Idx(drop_begin(GEP
.indices()));
2285 GetElementPtrInst
*Res
= GetElementPtrInst::Create(
2286 StrippedPtrEltTy
, StrippedPtr
, Idx
, GEP
.getName());
2287 Res
->setIsInBounds(GEP
.isInBounds());
2288 if (StrippedPtrTy
->getAddressSpace() == GEP
.getAddressSpace())
2290 // Insert Res, and create an addrspacecast.
2292 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
2294 // %0 = GEP i8 addrspace(1)* X, ...
2295 // addrspacecast i8 addrspace(1)* %0 to i8*
2296 return new AddrSpaceCastInst(Builder
.Insert(Res
), GEPType
);
2299 if (auto *XATy
= dyn_cast
<ArrayType
>(StrippedPtrEltTy
)) {
2300 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
2301 if (CATy
->getElementType() == XATy
->getElementType()) {
2302 // -> GEP [10 x i8]* X, i32 0, ...
2303 // At this point, we know that the cast source type is a pointer
2304 // to an array of the same type as the destination pointer
2305 // array. Because the array type is never stepped over (there
2306 // is a leading zero) we can fold the cast into this GEP.
2307 if (StrippedPtrTy
->getAddressSpace() == GEP
.getAddressSpace()) {
2308 GEP
.setSourceElementType(XATy
);
2309 return replaceOperand(GEP
, 0, StrippedPtr
);
2311 // Cannot replace the base pointer directly because StrippedPtr's
2312 // address space is different. Instead, create a new GEP followed by
2313 // an addrspacecast.
2315 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
2318 // %0 = GEP [10 x i8] addrspace(1)* X, ...
2319 // addrspacecast i8 addrspace(1)* %0 to i8*
2320 SmallVector
<Value
*, 8> Idx(GEP
.indices());
2323 ? Builder
.CreateInBoundsGEP(StrippedPtrEltTy
, StrippedPtr
,
2325 : Builder
.CreateGEP(StrippedPtrEltTy
, StrippedPtr
, Idx
,
2327 return new AddrSpaceCastInst(NewGEP
, GEPType
);
2331 } else if (GEP
.getNumOperands() == 2 && !IsGEPSrcEleScalable
) {
2332 // Skip if GEP source element type is scalable. The type alloc size is
2333 // unknown at compile-time.
2334 // Transform things like: %t = getelementptr i32*
2335 // bitcast ([2 x i32]* %str to i32*), i32 %V into: %t1 = getelementptr [2
2336 // x i32]* %str, i32 0, i32 %V; bitcast
2337 if (StrippedPtrEltTy
->isArrayTy() &&
2338 DL
.getTypeAllocSize(StrippedPtrEltTy
->getArrayElementType()) ==
2339 DL
.getTypeAllocSize(GEPEltType
)) {
2340 Type
*IdxType
= DL
.getIndexType(GEPType
);
2341 Value
*Idx
[2] = { Constant::getNullValue(IdxType
), GEP
.getOperand(1) };
2344 ? Builder
.CreateInBoundsGEP(StrippedPtrEltTy
, StrippedPtr
, Idx
,
2346 : Builder
.CreateGEP(StrippedPtrEltTy
, StrippedPtr
, Idx
,
2349 // V and GEP are both pointer types --> BitCast
2350 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP
, GEPType
);
2353 // Transform things like:
2354 // %V = mul i64 %N, 4
2355 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
2356 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
2357 if (GEPEltType
->isSized() && StrippedPtrEltTy
->isSized()) {
2358 // Check that changing the type amounts to dividing the index by a scale
2360 uint64_t ResSize
= DL
.getTypeAllocSize(GEPEltType
).getFixedSize();
2361 uint64_t SrcSize
= DL
.getTypeAllocSize(StrippedPtrEltTy
).getFixedSize();
2362 if (ResSize
&& SrcSize
% ResSize
== 0) {
2363 Value
*Idx
= GEP
.getOperand(1);
2364 unsigned BitWidth
= Idx
->getType()->getPrimitiveSizeInBits();
2365 uint64_t Scale
= SrcSize
/ ResSize
;
2367 // Earlier transforms ensure that the index has the right type
2368 // according to Data Layout, which considerably simplifies the
2369 // logic by eliminating implicit casts.
2370 assert(Idx
->getType() == DL
.getIndexType(GEPType
) &&
2371 "Index type does not match the Data Layout preferences");
2374 if (Value
*NewIdx
= Descale(Idx
, APInt(BitWidth
, Scale
), NSW
)) {
2375 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2376 // If the multiplication NewIdx * Scale may overflow then the new
2377 // GEP may not be "inbounds".
2379 GEP
.isInBounds() && NSW
2380 ? Builder
.CreateInBoundsGEP(StrippedPtrEltTy
, StrippedPtr
,
2381 NewIdx
, GEP
.getName())
2382 : Builder
.CreateGEP(StrippedPtrEltTy
, StrippedPtr
, NewIdx
,
2385 // The NewGEP must be pointer typed, so must the old one -> BitCast
2386 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP
,
2392 // Similarly, transform things like:
2393 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
2394 // (where tmp = 8*tmp2) into:
2395 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
2396 if (GEPEltType
->isSized() && StrippedPtrEltTy
->isSized() &&
2397 StrippedPtrEltTy
->isArrayTy()) {
2398 // Check that changing to the array element type amounts to dividing the
2399 // index by a scale factor.
2400 uint64_t ResSize
= DL
.getTypeAllocSize(GEPEltType
).getFixedSize();
2401 uint64_t ArrayEltSize
=
2402 DL
.getTypeAllocSize(StrippedPtrEltTy
->getArrayElementType())
2404 if (ResSize
&& ArrayEltSize
% ResSize
== 0) {
2405 Value
*Idx
= GEP
.getOperand(1);
2406 unsigned BitWidth
= Idx
->getType()->getPrimitiveSizeInBits();
2407 uint64_t Scale
= ArrayEltSize
/ ResSize
;
2409 // Earlier transforms ensure that the index has the right type
2410 // according to the Data Layout, which considerably simplifies
2411 // the logic by eliminating implicit casts.
2412 assert(Idx
->getType() == DL
.getIndexType(GEPType
) &&
2413 "Index type does not match the Data Layout preferences");
2416 if (Value
*NewIdx
= Descale(Idx
, APInt(BitWidth
, Scale
), NSW
)) {
2417 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
2418 // If the multiplication NewIdx * Scale may overflow then the new
2419 // GEP may not be "inbounds".
2420 Type
*IndTy
= DL
.getIndexType(GEPType
);
2421 Value
*Off
[2] = {Constant::getNullValue(IndTy
), NewIdx
};
2424 GEP
.isInBounds() && NSW
2425 ? Builder
.CreateInBoundsGEP(StrippedPtrEltTy
, StrippedPtr
,
2427 : Builder
.CreateGEP(StrippedPtrEltTy
, StrippedPtr
, Off
,
2429 // The NewGEP must be pointer typed, so must the old one -> BitCast
2430 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP
,
2438 // addrspacecast between types is canonicalized as a bitcast, then an
2439 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
2440 // through the addrspacecast.
2441 Value
*ASCStrippedPtrOp
= PtrOp
;
2442 if (auto *ASC
= dyn_cast
<AddrSpaceCastInst
>(PtrOp
)) {
2443 // X = bitcast A addrspace(1)* to B addrspace(1)*
2444 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
2445 // Z = gep Y, <...constant indices...>
2446 // Into an addrspacecasted GEP of the struct.
2447 if (auto *BC
= dyn_cast
<BitCastInst
>(ASC
->getOperand(0)))
2448 ASCStrippedPtrOp
= BC
;
2451 if (auto *BCI
= dyn_cast
<BitCastInst
>(ASCStrippedPtrOp
)) {
2452 Value
*SrcOp
= BCI
->getOperand(0);
2453 PointerType
*SrcType
= cast
<PointerType
>(BCI
->getSrcTy());
2454 Type
*SrcEltType
= SrcType
->getElementType();
2456 // GEP directly using the source operand if this GEP is accessing an element
2457 // of a bitcasted pointer to vector or array of the same dimensions:
2458 // gep (bitcast <c x ty>* X to [c x ty]*), Y, Z --> gep X, Y, Z
2459 // gep (bitcast [c x ty]* X to <c x ty>*), Y, Z --> gep X, Y, Z
2460 auto areMatchingArrayAndVecTypes
= [](Type
*ArrTy
, Type
*VecTy
,
2461 const DataLayout
&DL
) {
2462 auto *VecVTy
= cast
<FixedVectorType
>(VecTy
);
2463 return ArrTy
->getArrayElementType() == VecVTy
->getElementType() &&
2464 ArrTy
->getArrayNumElements() == VecVTy
->getNumElements() &&
2465 DL
.getTypeAllocSize(ArrTy
) == DL
.getTypeAllocSize(VecTy
);
2467 if (GEP
.getNumOperands() == 3 &&
2468 ((GEPEltType
->isArrayTy() && isa
<FixedVectorType
>(SrcEltType
) &&
2469 areMatchingArrayAndVecTypes(GEPEltType
, SrcEltType
, DL
)) ||
2470 (isa
<FixedVectorType
>(GEPEltType
) && SrcEltType
->isArrayTy() &&
2471 areMatchingArrayAndVecTypes(SrcEltType
, GEPEltType
, DL
)))) {
2473 // Create a new GEP here, as using `setOperand()` followed by
2474 // `setSourceElementType()` won't actually update the type of the
2475 // existing GEP Value. Causing issues if this Value is accessed when
2476 // constructing an AddrSpaceCastInst
2479 ? Builder
.CreateInBoundsGEP(SrcEltType
, SrcOp
, {Ops
[1], Ops
[2]})
2480 : Builder
.CreateGEP(SrcEltType
, SrcOp
, {Ops
[1], Ops
[2]});
2481 NGEP
->takeName(&GEP
);
2483 // Preserve GEP address space to satisfy users
2484 if (NGEP
->getType()->getPointerAddressSpace() != GEP
.getAddressSpace())
2485 return new AddrSpaceCastInst(NGEP
, GEPType
);
2487 return replaceInstUsesWith(GEP
, NGEP
);
2490 // See if we can simplify:
2491 // X = bitcast A* to B*
2492 // Y = gep X, <...constant indices...>
2493 // into a gep of the original struct. This is important for SROA and alias
2494 // analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
2495 unsigned OffsetBits
= DL
.getIndexTypeSizeInBits(GEPType
);
2496 APInt
Offset(OffsetBits
, 0);
2498 // If the bitcast argument is an allocation, The bitcast is for convertion
2499 // to actual type of allocation. Removing such bitcasts, results in having
2500 // GEPs with i8* base and pure byte offsets. That means GEP is not aware of
2501 // struct or array hierarchy.
2502 // By avoiding such GEPs, phi translation and MemoryDependencyAnalysis have
2503 // a better chance to succeed.
2504 if (!isa
<BitCastInst
>(SrcOp
) && GEP
.accumulateConstantOffset(DL
, Offset
) &&
2505 !isAllocationFn(SrcOp
, &TLI
)) {
2506 // If this GEP instruction doesn't move the pointer, just replace the GEP
2507 // with a bitcast of the real input to the dest type.
2509 // If the bitcast is of an allocation, and the allocation will be
2510 // converted to match the type of the cast, don't touch this.
2511 if (isa
<AllocaInst
>(SrcOp
)) {
2512 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
2513 if (Instruction
*I
= visitBitCast(*BCI
)) {
2516 BCI
->getParent()->getInstList().insert(BCI
->getIterator(), I
);
2517 replaceInstUsesWith(*BCI
, I
);
2523 if (SrcType
->getPointerAddressSpace() != GEP
.getAddressSpace())
2524 return new AddrSpaceCastInst(SrcOp
, GEPType
);
2525 return new BitCastInst(SrcOp
, GEPType
);
2528 // Otherwise, if the offset is non-zero, we need to find out if there is a
2529 // field at Offset in 'A's type. If so, we can pull the cast through the
2531 SmallVector
<Value
*, 8> NewIndices
;
2532 if (FindElementAtOffset(SrcType
, Offset
.getSExtValue(), NewIndices
)) {
2535 ? Builder
.CreateInBoundsGEP(SrcEltType
, SrcOp
, NewIndices
)
2536 : Builder
.CreateGEP(SrcEltType
, SrcOp
, NewIndices
);
2538 if (NGEP
->getType() == GEPType
)
2539 return replaceInstUsesWith(GEP
, NGEP
);
2540 NGEP
->takeName(&GEP
);
2542 if (NGEP
->getType()->getPointerAddressSpace() != GEP
.getAddressSpace())
2543 return new AddrSpaceCastInst(NGEP
, GEPType
);
2544 return new BitCastInst(NGEP
, GEPType
);
2549 if (!GEP
.isInBounds()) {
2551 DL
.getIndexSizeInBits(PtrOp
->getType()->getPointerAddressSpace());
2552 APInt
BasePtrOffset(IdxWidth
, 0);
2553 Value
*UnderlyingPtrOp
=
2554 PtrOp
->stripAndAccumulateInBoundsConstantOffsets(DL
,
2556 if (auto *AI
= dyn_cast
<AllocaInst
>(UnderlyingPtrOp
)) {
2557 if (GEP
.accumulateConstantOffset(DL
, BasePtrOffset
) &&
2558 BasePtrOffset
.isNonNegative()) {
2561 DL
.getTypeAllocSize(AI
->getAllocatedType()).getKnownMinSize());
2562 if (BasePtrOffset
.ule(AllocSize
)) {
2563 return GetElementPtrInst::CreateInBounds(
2564 GEP
.getSourceElementType(), PtrOp
, makeArrayRef(Ops
).slice(1),
2571 if (Instruction
*R
= foldSelectGEP(GEP
, Builder
))
2577 static bool isNeverEqualToUnescapedAlloc(Value
*V
, const TargetLibraryInfo
*TLI
,
2579 if (isa
<ConstantPointerNull
>(V
))
2581 if (auto *LI
= dyn_cast
<LoadInst
>(V
))
2582 return isa
<GlobalVariable
>(LI
->getPointerOperand());
2583 // Two distinct allocations will never be equal.
2584 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
2585 // through bitcasts of V can cause
2586 // the result statement below to be true, even when AI and V (ex:
2587 // i8* ->i32* ->i8* of AI) are the same allocations.
2588 return isAllocLikeFn(V
, TLI
) && V
!= AI
;
2591 static bool isAllocSiteRemovable(Instruction
*AI
,
2592 SmallVectorImpl
<WeakTrackingVH
> &Users
,
2593 const TargetLibraryInfo
*TLI
) {
2594 SmallVector
<Instruction
*, 4> Worklist
;
2595 Worklist
.push_back(AI
);
2598 Instruction
*PI
= Worklist
.pop_back_val();
2599 for (User
*U
: PI
->users()) {
2600 Instruction
*I
= cast
<Instruction
>(U
);
2601 switch (I
->getOpcode()) {
2603 // Give up the moment we see something we can't handle.
2606 case Instruction::AddrSpaceCast
:
2607 case Instruction::BitCast
:
2608 case Instruction::GetElementPtr
:
2609 Users
.emplace_back(I
);
2610 Worklist
.push_back(I
);
2613 case Instruction::ICmp
: {
2614 ICmpInst
*ICI
= cast
<ICmpInst
>(I
);
2615 // We can fold eq/ne comparisons with null to false/true, respectively.
2616 // We also fold comparisons in some conditions provided the alloc has
2617 // not escaped (see isNeverEqualToUnescapedAlloc).
2618 if (!ICI
->isEquality())
2620 unsigned OtherIndex
= (ICI
->getOperand(0) == PI
) ? 1 : 0;
2621 if (!isNeverEqualToUnescapedAlloc(ICI
->getOperand(OtherIndex
), TLI
, AI
))
2623 Users
.emplace_back(I
);
2627 case Instruction::Call
:
2628 // Ignore no-op and store intrinsics.
2629 if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
2630 switch (II
->getIntrinsicID()) {
2634 case Intrinsic::memmove
:
2635 case Intrinsic::memcpy
:
2636 case Intrinsic::memset
: {
2637 MemIntrinsic
*MI
= cast
<MemIntrinsic
>(II
);
2638 if (MI
->isVolatile() || MI
->getRawDest() != PI
)
2642 case Intrinsic::assume
:
2643 case Intrinsic::invariant_start
:
2644 case Intrinsic::invariant_end
:
2645 case Intrinsic::lifetime_start
:
2646 case Intrinsic::lifetime_end
:
2647 case Intrinsic::objectsize
:
2648 Users
.emplace_back(I
);
2650 case Intrinsic::launder_invariant_group
:
2651 case Intrinsic::strip_invariant_group
:
2652 Users
.emplace_back(I
);
2653 Worklist
.push_back(I
);
2658 if (isFreeCall(I
, TLI
)) {
2659 Users
.emplace_back(I
);
2664 case Instruction::Store
: {
2665 StoreInst
*SI
= cast
<StoreInst
>(I
);
2666 if (SI
->isVolatile() || SI
->getPointerOperand() != PI
)
2668 Users
.emplace_back(I
);
2672 llvm_unreachable("missing a return?");
2674 } while (!Worklist
.empty());
2678 Instruction
*InstCombinerImpl::visitAllocSite(Instruction
&MI
) {
2679 // If we have a malloc call which is only used in any amount of comparisons to
2680 // null and free calls, delete the calls and replace the comparisons with true
2681 // or false as appropriate.
2683 // This is based on the principle that we can substitute our own allocation
2684 // function (which will never return null) rather than knowledge of the
2685 // specific function being called. In some sense this can change the permitted
2686 // outputs of a program (when we convert a malloc to an alloca, the fact that
2687 // the allocation is now on the stack is potentially visible, for example),
2688 // but we believe in a permissible manner.
2689 SmallVector
<WeakTrackingVH
, 64> Users
;
2691 // If we are removing an alloca with a dbg.declare, insert dbg.value calls
2692 // before each store.
2693 SmallVector
<DbgVariableIntrinsic
*, 8> DVIs
;
2694 std::unique_ptr
<DIBuilder
> DIB
;
2695 if (isa
<AllocaInst
>(MI
)) {
2696 findDbgUsers(DVIs
, &MI
);
2697 DIB
.reset(new DIBuilder(*MI
.getModule(), /*AllowUnresolved=*/false));
2700 if (isAllocSiteRemovable(&MI
, Users
, &TLI
)) {
2701 for (unsigned i
= 0, e
= Users
.size(); i
!= e
; ++i
) {
2702 // Lowering all @llvm.objectsize calls first because they may
2703 // use a bitcast/GEP of the alloca we are removing.
2707 Instruction
*I
= cast
<Instruction
>(&*Users
[i
]);
2709 if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
2710 if (II
->getIntrinsicID() == Intrinsic::objectsize
) {
2712 lowerObjectSizeCall(II
, DL
, &TLI
, /*MustSucceed=*/true);
2713 replaceInstUsesWith(*I
, Result
);
2714 eraseInstFromFunction(*I
);
2715 Users
[i
] = nullptr; // Skip examining in the next loop.
2719 for (unsigned i
= 0, e
= Users
.size(); i
!= e
; ++i
) {
2723 Instruction
*I
= cast
<Instruction
>(&*Users
[i
]);
2725 if (ICmpInst
*C
= dyn_cast
<ICmpInst
>(I
)) {
2726 replaceInstUsesWith(*C
,
2727 ConstantInt::get(Type::getInt1Ty(C
->getContext()),
2728 C
->isFalseWhenEqual()));
2729 } else if (auto *SI
= dyn_cast
<StoreInst
>(I
)) {
2730 for (auto *DVI
: DVIs
)
2731 if (DVI
->isAddressOfVariable())
2732 ConvertDebugDeclareToDebugValue(DVI
, SI
, *DIB
);
2734 // Casts, GEP, or anything else: we're about to delete this instruction,
2735 // so it can not have any valid uses.
2736 replaceInstUsesWith(*I
, PoisonValue::get(I
->getType()));
2738 eraseInstFromFunction(*I
);
2741 if (InvokeInst
*II
= dyn_cast
<InvokeInst
>(&MI
)) {
2742 // Replace invoke with a NOP intrinsic to maintain the original CFG
2743 Module
*M
= II
->getModule();
2744 Function
*F
= Intrinsic::getDeclaration(M
, Intrinsic::donothing
);
2745 InvokeInst::Create(F
, II
->getNormalDest(), II
->getUnwindDest(),
2746 None
, "", II
->getParent());
2749 // Remove debug intrinsics which describe the value contained within the
2750 // alloca. In addition to removing dbg.{declare,addr} which simply point to
2751 // the alloca, remove dbg.value(<alloca>, ..., DW_OP_deref)'s as well, e.g.:
2754 // define void @foo(i32 %0) {
2755 // %a = alloca i32 ; Deleted.
2756 // store i32 %0, i32* %a
2757 // dbg.value(i32 %0, "arg0") ; Not deleted.
2758 // dbg.value(i32* %a, "arg0", DW_OP_deref) ; Deleted.
2759 // call void @trivially_inlinable_no_op(i32* %a)
2764 // This may not be required if we stop describing the contents of allocas
2765 // using dbg.value(<alloca>, ..., DW_OP_deref), but we currently do this in
2766 // the LowerDbgDeclare utility.
2768 // If there is a dead store to `%a` in @trivially_inlinable_no_op, the
2769 // "arg0" dbg.value may be stale after the call. However, failing to remove
2770 // the DW_OP_deref dbg.value causes large gaps in location coverage.
2771 for (auto *DVI
: DVIs
)
2772 if (DVI
->isAddressOfVariable() || DVI
->getExpression()->startsWithDeref())
2773 DVI
->eraseFromParent();
2775 return eraseInstFromFunction(MI
);
2780 /// Move the call to free before a NULL test.
2782 /// Check if this free is accessed after its argument has been test
2783 /// against NULL (property 0).
2784 /// If yes, it is legal to move this call in its predecessor block.
2786 /// The move is performed only if the block containing the call to free
2787 /// will be removed, i.e.:
2788 /// 1. it has only one predecessor P, and P has two successors
2789 /// 2. it contains the call, noops, and an unconditional branch
2790 /// 3. its successor is the same as its predecessor's successor
2792 /// The profitability is out-of concern here and this function should
2793 /// be called only if the caller knows this transformation would be
2794 /// profitable (e.g., for code size).
2795 static Instruction
*tryToMoveFreeBeforeNullTest(CallInst
&FI
,
2796 const DataLayout
&DL
) {
2797 Value
*Op
= FI
.getArgOperand(0);
2798 BasicBlock
*FreeInstrBB
= FI
.getParent();
2799 BasicBlock
*PredBB
= FreeInstrBB
->getSinglePredecessor();
2801 // Validate part of constraint #1: Only one predecessor
2802 // FIXME: We can extend the number of predecessor, but in that case, we
2803 // would duplicate the call to free in each predecessor and it may
2804 // not be profitable even for code size.
2808 // Validate constraint #2: Does this block contains only the call to
2809 // free, noops, and an unconditional branch?
2811 Instruction
*FreeInstrBBTerminator
= FreeInstrBB
->getTerminator();
2812 if (!match(FreeInstrBBTerminator
, m_UnconditionalBr(SuccBB
)))
2815 // If there are only 2 instructions in the block, at this point,
2816 // this is the call to free and unconditional.
2817 // If there are more than 2 instructions, check that they are noops
2818 // i.e., they won't hurt the performance of the generated code.
2819 if (FreeInstrBB
->size() != 2) {
2820 for (const Instruction
&Inst
: FreeInstrBB
->instructionsWithoutDebug()) {
2821 if (&Inst
== &FI
|| &Inst
== FreeInstrBBTerminator
)
2823 auto *Cast
= dyn_cast
<CastInst
>(&Inst
);
2824 if (!Cast
|| !Cast
->isNoopCast(DL
))
2828 // Validate the rest of constraint #1 by matching on the pred branch.
2829 Instruction
*TI
= PredBB
->getTerminator();
2830 BasicBlock
*TrueBB
, *FalseBB
;
2831 ICmpInst::Predicate Pred
;
2832 if (!match(TI
, m_Br(m_ICmp(Pred
,
2833 m_CombineOr(m_Specific(Op
),
2834 m_Specific(Op
->stripPointerCasts())),
2838 if (Pred
!= ICmpInst::ICMP_EQ
&& Pred
!= ICmpInst::ICMP_NE
)
2841 // Validate constraint #3: Ensure the null case just falls through.
2842 if (SuccBB
!= (Pred
== ICmpInst::ICMP_EQ
? TrueBB
: FalseBB
))
2844 assert(FreeInstrBB
== (Pred
== ICmpInst::ICMP_EQ
? FalseBB
: TrueBB
) &&
2845 "Broken CFG: missing edge from predecessor to successor");
2847 // At this point, we know that everything in FreeInstrBB can be moved
2849 for (BasicBlock::iterator It
= FreeInstrBB
->begin(), End
= FreeInstrBB
->end();
2851 Instruction
&Instr
= *It
++;
2852 if (&Instr
== FreeInstrBBTerminator
)
2854 Instr
.moveBefore(TI
);
2856 assert(FreeInstrBB
->size() == 1 &&
2857 "Only the branch instruction should remain");
2861 Instruction
*InstCombinerImpl::visitFree(CallInst
&FI
) {
2862 Value
*Op
= FI
.getArgOperand(0);
2864 // free undef -> unreachable.
2865 if (isa
<UndefValue
>(Op
)) {
2866 // Leave a marker since we can't modify the CFG here.
2867 CreateNonTerminatorUnreachable(&FI
);
2868 return eraseInstFromFunction(FI
);
2871 // If we have 'free null' delete the instruction. This can happen in stl code
2872 // when lots of inlining happens.
2873 if (isa
<ConstantPointerNull
>(Op
))
2874 return eraseInstFromFunction(FI
);
2876 // If we optimize for code size, try to move the call to free before the null
2877 // test so that simplify cfg can remove the empty block and dead code
2878 // elimination the branch. I.e., helps to turn something like:
2879 // if (foo) free(foo);
2883 // Note that we can only do this for 'free' and not for any flavor of
2884 // 'operator delete'; there is no 'operator delete' symbol for which we are
2885 // permitted to invent a call, even if we're passing in a null pointer.
2888 if (TLI
.getLibFunc(FI
, Func
) && TLI
.has(Func
) && Func
== LibFunc_free
)
2889 if (Instruction
*I
= tryToMoveFreeBeforeNullTest(FI
, DL
))
2896 static bool isMustTailCall(Value
*V
) {
2897 if (auto *CI
= dyn_cast
<CallInst
>(V
))
2898 return CI
->isMustTailCall();
2902 Instruction
*InstCombinerImpl::visitReturnInst(ReturnInst
&RI
) {
2903 if (RI
.getNumOperands() == 0) // ret void
2906 Value
*ResultOp
= RI
.getOperand(0);
2907 Type
*VTy
= ResultOp
->getType();
2908 if (!VTy
->isIntegerTy() || isa
<Constant
>(ResultOp
))
2911 // Don't replace result of musttail calls.
2912 if (isMustTailCall(ResultOp
))
2915 // There might be assume intrinsics dominating this return that completely
2916 // determine the value. If so, constant fold it.
2917 KnownBits Known
= computeKnownBits(ResultOp
, 0, &RI
);
2918 if (Known
.isConstant())
2919 return replaceOperand(RI
, 0,
2920 Constant::getIntegerValue(VTy
, Known
.getConstant()));
2925 // WARNING: keep in sync with SimplifyCFGOpt::simplifyUnreachable()!
2926 Instruction
*InstCombinerImpl::visitUnreachableInst(UnreachableInst
&I
) {
2927 // Try to remove the previous instruction if it must lead to unreachable.
2928 // This includes instructions like stores and "llvm.assume" that may not get
2929 // removed by simple dead code elimination.
2930 while (Instruction
*Prev
= I
.getPrevNonDebugInstruction()) {
2931 // While we theoretically can erase EH, that would result in a block that
2932 // used to start with an EH no longer starting with EH, which is invalid.
2933 // To make it valid, we'd need to fixup predecessors to no longer refer to
2934 // this block, but that changes CFG, which is not allowed in InstCombine.
2935 if (Prev
->isEHPad())
2936 return nullptr; // Can not drop any more instructions. We're done here.
2938 if (!isGuaranteedToTransferExecutionToSuccessor(Prev
))
2939 return nullptr; // Can not drop any more instructions. We're done here.
2940 // Otherwise, this instruction can be freely erased,
2941 // even if it is not side-effect free.
2943 // A value may still have uses before we process it here (for example, in
2944 // another unreachable block), so convert those to poison.
2945 replaceInstUsesWith(*Prev
, PoisonValue::get(Prev
->getType()));
2946 eraseInstFromFunction(*Prev
);
2948 assert(I
.getParent()->sizeWithoutDebug() == 1 && "The block is now empty.");
2949 // FIXME: recurse into unconditional predecessors?
2953 Instruction
*InstCombinerImpl::visitUnconditionalBranchInst(BranchInst
&BI
) {
2954 assert(BI
.isUnconditional() && "Only for unconditional branches.");
2956 // If this store is the second-to-last instruction in the basic block
2957 // (excluding debug info and bitcasts of pointers) and if the block ends with
2958 // an unconditional branch, try to move the store to the successor block.
2960 auto GetLastSinkableStore
= [](BasicBlock::iterator BBI
) {
2961 auto IsNoopInstrForStoreMerging
= [](BasicBlock::iterator BBI
) {
2962 return isa
<DbgInfoIntrinsic
>(BBI
) ||
2963 (isa
<BitCastInst
>(BBI
) && BBI
->getType()->isPointerTy());
2966 BasicBlock::iterator FirstInstr
= BBI
->getParent()->begin();
2968 if (BBI
!= FirstInstr
)
2970 } while (BBI
!= FirstInstr
&& IsNoopInstrForStoreMerging(BBI
));
2972 return dyn_cast
<StoreInst
>(BBI
);
2975 if (StoreInst
*SI
= GetLastSinkableStore(BasicBlock::iterator(BI
)))
2976 if (mergeStoreIntoSuccessor(*SI
))
2982 Instruction
*InstCombinerImpl::visitBranchInst(BranchInst
&BI
) {
2983 if (BI
.isUnconditional())
2984 return visitUnconditionalBranchInst(BI
);
2986 // Change br (not X), label True, label False to: br X, label False, True
2988 if (match(&BI
, m_Br(m_Not(m_Value(X
)), m_BasicBlock(), m_BasicBlock())) &&
2989 !isa
<Constant
>(X
)) {
2990 // Swap Destinations and condition...
2991 BI
.swapSuccessors();
2992 return replaceOperand(BI
, 0, X
);
2995 // If the condition is irrelevant, remove the use so that other
2996 // transforms on the condition become more effective.
2997 if (!isa
<ConstantInt
>(BI
.getCondition()) &&
2998 BI
.getSuccessor(0) == BI
.getSuccessor(1))
2999 return replaceOperand(
3000 BI
, 0, ConstantInt::getFalse(BI
.getCondition()->getType()));
3002 // Canonicalize, for example, fcmp_one -> fcmp_oeq.
3003 CmpInst::Predicate Pred
;
3004 if (match(&BI
, m_Br(m_OneUse(m_FCmp(Pred
, m_Value(), m_Value())),
3005 m_BasicBlock(), m_BasicBlock())) &&
3006 !isCanonicalPredicate(Pred
)) {
3007 // Swap destinations and condition.
3008 CmpInst
*Cond
= cast
<CmpInst
>(BI
.getCondition());
3009 Cond
->setPredicate(CmpInst::getInversePredicate(Pred
));
3010 BI
.swapSuccessors();
3011 Worklist
.push(Cond
);
3018 Instruction
*InstCombinerImpl::visitSwitchInst(SwitchInst
&SI
) {
3019 Value
*Cond
= SI
.getCondition();
3021 ConstantInt
*AddRHS
;
3022 if (match(Cond
, m_Add(m_Value(Op0
), m_ConstantInt(AddRHS
)))) {
3023 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
3024 for (auto Case
: SI
.cases()) {
3025 Constant
*NewCase
= ConstantExpr::getSub(Case
.getCaseValue(), AddRHS
);
3026 assert(isa
<ConstantInt
>(NewCase
) &&
3027 "Result of expression should be constant");
3028 Case
.setValue(cast
<ConstantInt
>(NewCase
));
3030 return replaceOperand(SI
, 0, Op0
);
3033 KnownBits Known
= computeKnownBits(Cond
, 0, &SI
);
3034 unsigned LeadingKnownZeros
= Known
.countMinLeadingZeros();
3035 unsigned LeadingKnownOnes
= Known
.countMinLeadingOnes();
3037 // Compute the number of leading bits we can ignore.
3038 // TODO: A better way to determine this would use ComputeNumSignBits().
3039 for (auto &C
: SI
.cases()) {
3040 LeadingKnownZeros
= std::min(
3041 LeadingKnownZeros
, C
.getCaseValue()->getValue().countLeadingZeros());
3042 LeadingKnownOnes
= std::min(
3043 LeadingKnownOnes
, C
.getCaseValue()->getValue().countLeadingOnes());
3046 unsigned NewWidth
= Known
.getBitWidth() - std::max(LeadingKnownZeros
, LeadingKnownOnes
);
3048 // Shrink the condition operand if the new type is smaller than the old type.
3049 // But do not shrink to a non-standard type, because backend can't generate
3050 // good code for that yet.
3051 // TODO: We can make it aggressive again after fixing PR39569.
3052 if (NewWidth
> 0 && NewWidth
< Known
.getBitWidth() &&
3053 shouldChangeType(Known
.getBitWidth(), NewWidth
)) {
3054 IntegerType
*Ty
= IntegerType::get(SI
.getContext(), NewWidth
);
3055 Builder
.SetInsertPoint(&SI
);
3056 Value
*NewCond
= Builder
.CreateTrunc(Cond
, Ty
, "trunc");
3058 for (auto Case
: SI
.cases()) {
3059 APInt TruncatedCase
= Case
.getCaseValue()->getValue().trunc(NewWidth
);
3060 Case
.setValue(ConstantInt::get(SI
.getContext(), TruncatedCase
));
3062 return replaceOperand(SI
, 0, NewCond
);
3068 Instruction
*InstCombinerImpl::visitExtractValueInst(ExtractValueInst
&EV
) {
3069 Value
*Agg
= EV
.getAggregateOperand();
3071 if (!EV
.hasIndices())
3072 return replaceInstUsesWith(EV
, Agg
);
3074 if (Value
*V
= SimplifyExtractValueInst(Agg
, EV
.getIndices(),
3075 SQ
.getWithInstruction(&EV
)))
3076 return replaceInstUsesWith(EV
, V
);
3078 if (InsertValueInst
*IV
= dyn_cast
<InsertValueInst
>(Agg
)) {
3079 // We're extracting from an insertvalue instruction, compare the indices
3080 const unsigned *exti
, *exte
, *insi
, *inse
;
3081 for (exti
= EV
.idx_begin(), insi
= IV
->idx_begin(),
3082 exte
= EV
.idx_end(), inse
= IV
->idx_end();
3083 exti
!= exte
&& insi
!= inse
;
3086 // The insert and extract both reference distinctly different elements.
3087 // This means the extract is not influenced by the insert, and we can
3088 // replace the aggregate operand of the extract with the aggregate
3089 // operand of the insert. i.e., replace
3090 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3091 // %E = extractvalue { i32, { i32 } } %I, 0
3093 // %E = extractvalue { i32, { i32 } } %A, 0
3094 return ExtractValueInst::Create(IV
->getAggregateOperand(),
3097 if (exti
== exte
&& insi
== inse
)
3098 // Both iterators are at the end: Index lists are identical. Replace
3099 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3100 // %C = extractvalue { i32, { i32 } } %B, 1, 0
3102 return replaceInstUsesWith(EV
, IV
->getInsertedValueOperand());
3104 // The extract list is a prefix of the insert list. i.e. replace
3105 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
3106 // %E = extractvalue { i32, { i32 } } %I, 1
3108 // %X = extractvalue { i32, { i32 } } %A, 1
3109 // %E = insertvalue { i32 } %X, i32 42, 0
3110 // by switching the order of the insert and extract (though the
3111 // insertvalue should be left in, since it may have other uses).
3112 Value
*NewEV
= Builder
.CreateExtractValue(IV
->getAggregateOperand(),
3114 return InsertValueInst::Create(NewEV
, IV
->getInsertedValueOperand(),
3115 makeArrayRef(insi
, inse
));
3118 // The insert list is a prefix of the extract list
3119 // We can simply remove the common indices from the extract and make it
3120 // operate on the inserted value instead of the insertvalue result.
3122 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
3123 // %E = extractvalue { i32, { i32 } } %I, 1, 0
3125 // %E extractvalue { i32 } { i32 42 }, 0
3126 return ExtractValueInst::Create(IV
->getInsertedValueOperand(),
3127 makeArrayRef(exti
, exte
));
3129 if (WithOverflowInst
*WO
= dyn_cast
<WithOverflowInst
>(Agg
)) {
3130 // We're extracting from an overflow intrinsic, see if we're the only user,
3131 // which allows us to simplify multiple result intrinsics to simpler
3132 // things that just get one value.
3133 if (WO
->hasOneUse()) {
3134 // Check if we're grabbing only the result of a 'with overflow' intrinsic
3135 // and replace it with a traditional binary instruction.
3136 if (*EV
.idx_begin() == 0) {
3137 Instruction::BinaryOps BinOp
= WO
->getBinaryOp();
3138 Value
*LHS
= WO
->getLHS(), *RHS
= WO
->getRHS();
3139 // Replace the old instruction's uses with poison.
3140 replaceInstUsesWith(*WO
, PoisonValue::get(WO
->getType()));
3141 eraseInstFromFunction(*WO
);
3142 return BinaryOperator::Create(BinOp
, LHS
, RHS
);
3145 assert(*EV
.idx_begin() == 1 &&
3146 "unexpected extract index for overflow inst");
3148 // If only the overflow result is used, and the right hand side is a
3149 // constant (or constant splat), we can remove the intrinsic by directly
3150 // checking for overflow.
3152 if (match(WO
->getRHS(), m_APInt(C
))) {
3153 // Compute the no-wrap range [X,Y) for LHS given RHS=C, then
3154 // check for the inverted range using range offset trick (i.e.
3155 // use a subtract to shift the range to bottom of either the
3156 // signed or unsigned domain and then use a single compare to
3157 // check range membership).
3159 ConstantRange::makeExactNoWrapRegion(WO
->getBinaryOp(), *C
,
3160 WO
->getNoWrapKind());
3161 APInt Min
= WO
->isSigned() ? NWR
.getSignedMin() : NWR
.getUnsignedMin();
3162 NWR
= NWR
.subtract(Min
);
3164 CmpInst::Predicate Pred
;
3166 if (NWR
.getEquivalentICmp(Pred
, NewRHSC
)) {
3167 auto *OpTy
= WO
->getRHS()->getType();
3168 auto *NewLHS
= Builder
.CreateSub(WO
->getLHS(),
3169 ConstantInt::get(OpTy
, Min
));
3170 return new ICmpInst(ICmpInst::getInversePredicate(Pred
), NewLHS
,
3171 ConstantInt::get(OpTy
, NewRHSC
));
3176 if (LoadInst
*L
= dyn_cast
<LoadInst
>(Agg
))
3177 // If the (non-volatile) load only has one use, we can rewrite this to a
3178 // load from a GEP. This reduces the size of the load. If a load is used
3179 // only by extractvalue instructions then this either must have been
3180 // optimized before, or it is a struct with padding, in which case we
3181 // don't want to do the transformation as it loses padding knowledge.
3182 if (L
->isSimple() && L
->hasOneUse()) {
3183 // extractvalue has integer indices, getelementptr has Value*s. Convert.
3184 SmallVector
<Value
*, 4> Indices
;
3185 // Prefix an i32 0 since we need the first element.
3186 Indices
.push_back(Builder
.getInt32(0));
3187 for (unsigned Idx
: EV
.indices())
3188 Indices
.push_back(Builder
.getInt32(Idx
));
3190 // We need to insert these at the location of the old load, not at that of
3191 // the extractvalue.
3192 Builder
.SetInsertPoint(L
);
3193 Value
*GEP
= Builder
.CreateInBoundsGEP(L
->getType(),
3194 L
->getPointerOperand(), Indices
);
3195 Instruction
*NL
= Builder
.CreateLoad(EV
.getType(), GEP
);
3196 // Whatever aliasing information we had for the orignal load must also
3197 // hold for the smaller load, so propagate the annotations.
3199 L
->getAAMetadata(Nodes
);
3200 NL
->setAAMetadata(Nodes
);
3201 // Returning the load directly will cause the main loop to insert it in
3202 // the wrong spot, so use replaceInstUsesWith().
3203 return replaceInstUsesWith(EV
, NL
);
3205 // We could simplify extracts from other values. Note that nested extracts may
3206 // already be simplified implicitly by the above: extract (extract (insert) )
3207 // will be translated into extract ( insert ( extract ) ) first and then just
3208 // the value inserted, if appropriate. Similarly for extracts from single-use
3209 // loads: extract (extract (load)) will be translated to extract (load (gep))
3210 // and if again single-use then via load (gep (gep)) to load (gep).
3211 // However, double extracts from e.g. function arguments or return values
3212 // aren't handled yet.
3216 /// Return 'true' if the given typeinfo will match anything.
3217 static bool isCatchAll(EHPersonality Personality
, Constant
*TypeInfo
) {
3218 switch (Personality
) {
3219 case EHPersonality::GNU_C
:
3220 case EHPersonality::GNU_C_SjLj
:
3221 case EHPersonality::Rust
:
3222 // The GCC C EH and Rust personality only exists to support cleanups, so
3223 // it's not clear what the semantics of catch clauses are.
3225 case EHPersonality::Unknown
:
3227 case EHPersonality::GNU_Ada
:
3228 // While __gnat_all_others_value will match any Ada exception, it doesn't
3229 // match foreign exceptions (or didn't, before gcc-4.7).
3231 case EHPersonality::GNU_CXX
:
3232 case EHPersonality::GNU_CXX_SjLj
:
3233 case EHPersonality::GNU_ObjC
:
3234 case EHPersonality::MSVC_X86SEH
:
3235 case EHPersonality::MSVC_TableSEH
:
3236 case EHPersonality::MSVC_CXX
:
3237 case EHPersonality::CoreCLR
:
3238 case EHPersonality::Wasm_CXX
:
3239 case EHPersonality::XL_CXX
:
3240 return TypeInfo
->isNullValue();
3242 llvm_unreachable("invalid enum");
3245 static bool shorter_filter(const Value
*LHS
, const Value
*RHS
) {
3247 cast
<ArrayType
>(LHS
->getType())->getNumElements()
3249 cast
<ArrayType
>(RHS
->getType())->getNumElements();
3252 Instruction
*InstCombinerImpl::visitLandingPadInst(LandingPadInst
&LI
) {
3253 // The logic here should be correct for any real-world personality function.
3254 // However if that turns out not to be true, the offending logic can always
3255 // be conditioned on the personality function, like the catch-all logic is.
3256 EHPersonality Personality
=
3257 classifyEHPersonality(LI
.getParent()->getParent()->getPersonalityFn());
3259 // Simplify the list of clauses, eg by removing repeated catch clauses
3260 // (these are often created by inlining).
3261 bool MakeNewInstruction
= false; // If true, recreate using the following:
3262 SmallVector
<Constant
*, 16> NewClauses
; // - Clauses for the new instruction;
3263 bool CleanupFlag
= LI
.isCleanup(); // - The new instruction is a cleanup.
3265 SmallPtrSet
<Value
*, 16> AlreadyCaught
; // Typeinfos known caught already.
3266 for (unsigned i
= 0, e
= LI
.getNumClauses(); i
!= e
; ++i
) {
3267 bool isLastClause
= i
+ 1 == e
;
3268 if (LI
.isCatch(i
)) {
3270 Constant
*CatchClause
= LI
.getClause(i
);
3271 Constant
*TypeInfo
= CatchClause
->stripPointerCasts();
3273 // If we already saw this clause, there is no point in having a second
3275 if (AlreadyCaught
.insert(TypeInfo
).second
) {
3276 // This catch clause was not already seen.
3277 NewClauses
.push_back(CatchClause
);
3279 // Repeated catch clause - drop the redundant copy.
3280 MakeNewInstruction
= true;
3283 // If this is a catch-all then there is no point in keeping any following
3284 // clauses or marking the landingpad as having a cleanup.
3285 if (isCatchAll(Personality
, TypeInfo
)) {
3287 MakeNewInstruction
= true;
3288 CleanupFlag
= false;
3292 // A filter clause. If any of the filter elements were already caught
3293 // then they can be dropped from the filter. It is tempting to try to
3294 // exploit the filter further by saying that any typeinfo that does not
3295 // occur in the filter can't be caught later (and thus can be dropped).
3296 // However this would be wrong, since typeinfos can match without being
3297 // equal (for example if one represents a C++ class, and the other some
3298 // class derived from it).
3299 assert(LI
.isFilter(i
) && "Unsupported landingpad clause!");
3300 Constant
*FilterClause
= LI
.getClause(i
);
3301 ArrayType
*FilterType
= cast
<ArrayType
>(FilterClause
->getType());
3302 unsigned NumTypeInfos
= FilterType
->getNumElements();
3304 // An empty filter catches everything, so there is no point in keeping any
3305 // following clauses or marking the landingpad as having a cleanup. By
3306 // dealing with this case here the following code is made a bit simpler.
3307 if (!NumTypeInfos
) {
3308 NewClauses
.push_back(FilterClause
);
3310 MakeNewInstruction
= true;
3311 CleanupFlag
= false;
3315 bool MakeNewFilter
= false; // If true, make a new filter.
3316 SmallVector
<Constant
*, 16> NewFilterElts
; // New elements.
3317 if (isa
<ConstantAggregateZero
>(FilterClause
)) {
3318 // Not an empty filter - it contains at least one null typeinfo.
3319 assert(NumTypeInfos
> 0 && "Should have handled empty filter already!");
3320 Constant
*TypeInfo
=
3321 Constant::getNullValue(FilterType
->getElementType());
3322 // If this typeinfo is a catch-all then the filter can never match.
3323 if (isCatchAll(Personality
, TypeInfo
)) {
3324 // Throw the filter away.
3325 MakeNewInstruction
= true;
3329 // There is no point in having multiple copies of this typeinfo, so
3330 // discard all but the first copy if there is more than one.
3331 NewFilterElts
.push_back(TypeInfo
);
3332 if (NumTypeInfos
> 1)
3333 MakeNewFilter
= true;
3335 ConstantArray
*Filter
= cast
<ConstantArray
>(FilterClause
);
3336 SmallPtrSet
<Value
*, 16> SeenInFilter
; // For uniquing the elements.
3337 NewFilterElts
.reserve(NumTypeInfos
);
3339 // Remove any filter elements that were already caught or that already
3340 // occurred in the filter. While there, see if any of the elements are
3341 // catch-alls. If so, the filter can be discarded.
3342 bool SawCatchAll
= false;
3343 for (unsigned j
= 0; j
!= NumTypeInfos
; ++j
) {
3344 Constant
*Elt
= Filter
->getOperand(j
);
3345 Constant
*TypeInfo
= Elt
->stripPointerCasts();
3346 if (isCatchAll(Personality
, TypeInfo
)) {
3347 // This element is a catch-all. Bail out, noting this fact.
3352 // Even if we've seen a type in a catch clause, we don't want to
3353 // remove it from the filter. An unexpected type handler may be
3354 // set up for a call site which throws an exception of the same
3355 // type caught. In order for the exception thrown by the unexpected
3356 // handler to propagate correctly, the filter must be correctly
3357 // described for the call site.
3361 // void unexpected() { throw 1;}
3362 // void foo() throw (int) {
3363 // std::set_unexpected(unexpected);
3366 // } catch (int i) {}
3369 // There is no point in having multiple copies of the same typeinfo in
3370 // a filter, so only add it if we didn't already.
3371 if (SeenInFilter
.insert(TypeInfo
).second
)
3372 NewFilterElts
.push_back(cast
<Constant
>(Elt
));
3374 // A filter containing a catch-all cannot match anything by definition.
3376 // Throw the filter away.
3377 MakeNewInstruction
= true;
3381 // If we dropped something from the filter, make a new one.
3382 if (NewFilterElts
.size() < NumTypeInfos
)
3383 MakeNewFilter
= true;
3385 if (MakeNewFilter
) {
3386 FilterType
= ArrayType::get(FilterType
->getElementType(),
3387 NewFilterElts
.size());
3388 FilterClause
= ConstantArray::get(FilterType
, NewFilterElts
);
3389 MakeNewInstruction
= true;
3392 NewClauses
.push_back(FilterClause
);
3394 // If the new filter is empty then it will catch everything so there is
3395 // no point in keeping any following clauses or marking the landingpad
3396 // as having a cleanup. The case of the original filter being empty was
3397 // already handled above.
3398 if (MakeNewFilter
&& !NewFilterElts
.size()) {
3399 assert(MakeNewInstruction
&& "New filter but not a new instruction!");
3400 CleanupFlag
= false;
3406 // If several filters occur in a row then reorder them so that the shortest
3407 // filters come first (those with the smallest number of elements). This is
3408 // advantageous because shorter filters are more likely to match, speeding up
3409 // unwinding, but mostly because it increases the effectiveness of the other
3410 // filter optimizations below.
3411 for (unsigned i
= 0, e
= NewClauses
.size(); i
+ 1 < e
; ) {
3413 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
3414 for (j
= i
; j
!= e
; ++j
)
3415 if (!isa
<ArrayType
>(NewClauses
[j
]->getType()))
3418 // Check whether the filters are already sorted by length. We need to know
3419 // if sorting them is actually going to do anything so that we only make a
3420 // new landingpad instruction if it does.
3421 for (unsigned k
= i
; k
+ 1 < j
; ++k
)
3422 if (shorter_filter(NewClauses
[k
+1], NewClauses
[k
])) {
3423 // Not sorted, so sort the filters now. Doing an unstable sort would be
3424 // correct too but reordering filters pointlessly might confuse users.
3425 std::stable_sort(NewClauses
.begin() + i
, NewClauses
.begin() + j
,
3427 MakeNewInstruction
= true;
3431 // Look for the next batch of filters.
3435 // If typeinfos matched if and only if equal, then the elements of a filter L
3436 // that occurs later than a filter F could be replaced by the intersection of
3437 // the elements of F and L. In reality two typeinfos can match without being
3438 // equal (for example if one represents a C++ class, and the other some class
3439 // derived from it) so it would be wrong to perform this transform in general.
3440 // However the transform is correct and useful if F is a subset of L. In that
3441 // case L can be replaced by F, and thus removed altogether since repeating a
3442 // filter is pointless. So here we look at all pairs of filters F and L where
3443 // L follows F in the list of clauses, and remove L if every element of F is
3444 // an element of L. This can occur when inlining C++ functions with exception
3446 for (unsigned i
= 0; i
+ 1 < NewClauses
.size(); ++i
) {
3447 // Examine each filter in turn.
3448 Value
*Filter
= NewClauses
[i
];
3449 ArrayType
*FTy
= dyn_cast
<ArrayType
>(Filter
->getType());
3451 // Not a filter - skip it.
3453 unsigned FElts
= FTy
->getNumElements();
3454 // Examine each filter following this one. Doing this backwards means that
3455 // we don't have to worry about filters disappearing under us when removed.
3456 for (unsigned j
= NewClauses
.size() - 1; j
!= i
; --j
) {
3457 Value
*LFilter
= NewClauses
[j
];
3458 ArrayType
*LTy
= dyn_cast
<ArrayType
>(LFilter
->getType());
3460 // Not a filter - skip it.
3462 // If Filter is a subset of LFilter, i.e. every element of Filter is also
3463 // an element of LFilter, then discard LFilter.
3464 SmallVectorImpl
<Constant
*>::iterator J
= NewClauses
.begin() + j
;
3465 // If Filter is empty then it is a subset of LFilter.
3468 NewClauses
.erase(J
);
3469 MakeNewInstruction
= true;
3470 // Move on to the next filter.
3473 unsigned LElts
= LTy
->getNumElements();
3474 // If Filter is longer than LFilter then it cannot be a subset of it.
3476 // Move on to the next filter.
3478 // At this point we know that LFilter has at least one element.
3479 if (isa
<ConstantAggregateZero
>(LFilter
)) { // LFilter only contains zeros.
3480 // Filter is a subset of LFilter iff Filter contains only zeros (as we
3481 // already know that Filter is not longer than LFilter).
3482 if (isa
<ConstantAggregateZero
>(Filter
)) {
3483 assert(FElts
<= LElts
&& "Should have handled this case earlier!");
3485 NewClauses
.erase(J
);
3486 MakeNewInstruction
= true;
3488 // Move on to the next filter.
3491 ConstantArray
*LArray
= cast
<ConstantArray
>(LFilter
);
3492 if (isa
<ConstantAggregateZero
>(Filter
)) { // Filter only contains zeros.
3493 // Since Filter is non-empty and contains only zeros, it is a subset of
3494 // LFilter iff LFilter contains a zero.
3495 assert(FElts
> 0 && "Should have eliminated the empty filter earlier!");
3496 for (unsigned l
= 0; l
!= LElts
; ++l
)
3497 if (LArray
->getOperand(l
)->isNullValue()) {
3498 // LFilter contains a zero - discard it.
3499 NewClauses
.erase(J
);
3500 MakeNewInstruction
= true;
3503 // Move on to the next filter.
3506 // At this point we know that both filters are ConstantArrays. Loop over
3507 // operands to see whether every element of Filter is also an element of
3508 // LFilter. Since filters tend to be short this is probably faster than
3509 // using a method that scales nicely.
3510 ConstantArray
*FArray
= cast
<ConstantArray
>(Filter
);
3511 bool AllFound
= true;
3512 for (unsigned f
= 0; f
!= FElts
; ++f
) {
3513 Value
*FTypeInfo
= FArray
->getOperand(f
)->stripPointerCasts();
3515 for (unsigned l
= 0; l
!= LElts
; ++l
) {
3516 Value
*LTypeInfo
= LArray
->getOperand(l
)->stripPointerCasts();
3517 if (LTypeInfo
== FTypeInfo
) {
3527 NewClauses
.erase(J
);
3528 MakeNewInstruction
= true;
3530 // Move on to the next filter.
3534 // If we changed any of the clauses, replace the old landingpad instruction
3536 if (MakeNewInstruction
) {
3537 LandingPadInst
*NLI
= LandingPadInst::Create(LI
.getType(),
3539 for (unsigned i
= 0, e
= NewClauses
.size(); i
!= e
; ++i
)
3540 NLI
->addClause(NewClauses
[i
]);
3541 // A landing pad with no clauses must have the cleanup flag set. It is
3542 // theoretically possible, though highly unlikely, that we eliminated all
3543 // clauses. If so, force the cleanup flag to true.
3544 if (NewClauses
.empty())
3546 NLI
->setCleanup(CleanupFlag
);
3550 // Even if none of the clauses changed, we may nonetheless have understood
3551 // that the cleanup flag is pointless. Clear it if so.
3552 if (LI
.isCleanup() != CleanupFlag
) {
3553 assert(!CleanupFlag
&& "Adding a cleanup, not removing one?!");
3554 LI
.setCleanup(CleanupFlag
);
3562 InstCombinerImpl::pushFreezeToPreventPoisonFromPropagating(FreezeInst
&OrigFI
) {
3563 // Try to push freeze through instructions that propagate but don't produce
3564 // poison as far as possible. If an operand of freeze follows three
3565 // conditions 1) one-use, 2) does not produce poison, and 3) has all but one
3566 // guaranteed-non-poison operands then push the freeze through to the one
3567 // operand that is not guaranteed non-poison. The actual transform is as
3569 // Op1 = ... ; Op1 can be posion
3570 // Op0 = Inst(Op1, NonPoisonOps...) ; Op0 has only one use and only have
3571 // ; single guaranteed-non-poison operands
3572 // ... = Freeze(Op0)
3575 // Op1.fr = Freeze(Op1)
3576 // ... = Inst(Op1.fr, NonPoisonOps...)
3577 auto *OrigOp
= OrigFI
.getOperand(0);
3578 auto *OrigOpInst
= dyn_cast
<Instruction
>(OrigOp
);
3580 // While we could change the other users of OrigOp to use freeze(OrigOp), that
3581 // potentially reduces their optimization potential, so let's only do this iff
3582 // the OrigOp is only used by the freeze.
3583 if (!OrigOpInst
|| !OrigOpInst
->hasOneUse() || isa
<PHINode
>(OrigOp
) ||
3584 canCreateUndefOrPoison(dyn_cast
<Operator
>(OrigOp
)))
3587 // If operand is guaranteed not to be poison, there is no need to add freeze
3588 // to the operand. So we first find the operand that is not guaranteed to be
3590 Use
*MaybePoisonOperand
= nullptr;
3591 for (Use
&U
: OrigOpInst
->operands()) {
3592 if (isGuaranteedNotToBeUndefOrPoison(U
.get()))
3594 if (!MaybePoisonOperand
)
3595 MaybePoisonOperand
= &U
;
3600 // If all operands are guaranteed to be non-poison, we can drop freeze.
3601 if (!MaybePoisonOperand
)
3604 auto *FrozenMaybePoisonOperand
= new FreezeInst(
3605 MaybePoisonOperand
->get(), MaybePoisonOperand
->get()->getName() + ".fr");
3607 replaceUse(*MaybePoisonOperand
, FrozenMaybePoisonOperand
);
3608 FrozenMaybePoisonOperand
->insertBefore(OrigOpInst
);
3612 bool InstCombinerImpl::freezeDominatedUses(FreezeInst
&FI
) {
3613 Value
*Op
= FI
.getOperand(0);
3615 if (isa
<Constant
>(Op
))
3618 bool Changed
= false;
3619 Op
->replaceUsesWithIf(&FI
, [&](Use
&U
) -> bool {
3620 bool Dominates
= DT
.dominates(&FI
, U
);
3621 Changed
|= Dominates
;
3628 Instruction
*InstCombinerImpl::visitFreeze(FreezeInst
&I
) {
3629 Value
*Op0
= I
.getOperand(0);
3631 if (Value
*V
= SimplifyFreezeInst(Op0
, SQ
.getWithInstruction(&I
)))
3632 return replaceInstUsesWith(I
, V
);
3634 // freeze (phi const, x) --> phi const, (freeze x)
3635 if (auto *PN
= dyn_cast
<PHINode
>(Op0
)) {
3636 if (Instruction
*NV
= foldOpIntoPhi(I
, PN
))
3640 if (Value
*NI
= pushFreezeToPreventPoisonFromPropagating(I
))
3641 return replaceInstUsesWith(I
, NI
);
3643 if (match(Op0
, m_Undef())) {
3644 // If I is freeze(undef), see its uses and fold it to the best constant.
3646 // - select's condition: pick the value that leads to choosing a constant
3647 // - other ops: pick 0
3648 Constant
*BestValue
= nullptr;
3649 Constant
*NullValue
= Constant::getNullValue(I
.getType());
3650 for (const auto *U
: I
.users()) {
3651 Constant
*C
= NullValue
;
3653 if (match(U
, m_Or(m_Value(), m_Value())))
3654 C
= Constant::getAllOnesValue(I
.getType());
3655 else if (const auto *SI
= dyn_cast
<SelectInst
>(U
)) {
3656 if (SI
->getCondition() == &I
) {
3657 APInt
CondVal(1, isa
<Constant
>(SI
->getFalseValue()) ? 0 : 1);
3658 C
= Constant::getIntegerValue(I
.getType(), CondVal
);
3664 else if (BestValue
!= C
)
3665 BestValue
= NullValue
;
3668 return replaceInstUsesWith(I
, BestValue
);
3671 // Replace all dominated uses of Op to freeze(Op).
3672 if (freezeDominatedUses(I
))
3678 /// Try to move the specified instruction from its current block into the
3679 /// beginning of DestBlock, which can only happen if it's safe to move the
3680 /// instruction past all of the instructions between it and the end of its
3682 static bool TryToSinkInstruction(Instruction
*I
, BasicBlock
*DestBlock
) {
3683 assert(I
->getSingleUndroppableUse() && "Invariants didn't hold!");
3684 BasicBlock
*SrcBlock
= I
->getParent();
3686 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
3687 if (isa
<PHINode
>(I
) || I
->isEHPad() || I
->mayHaveSideEffects() ||
3691 // Do not sink static or dynamic alloca instructions. Static allocas must
3692 // remain in the entry block, and dynamic allocas must not be sunk in between
3693 // a stacksave / stackrestore pair, which would incorrectly shorten its
3695 if (isa
<AllocaInst
>(I
))
3698 // Do not sink into catchswitch blocks.
3699 if (isa
<CatchSwitchInst
>(DestBlock
->getTerminator()))
3702 // Do not sink convergent call instructions.
3703 if (auto *CI
= dyn_cast
<CallInst
>(I
)) {
3704 if (CI
->isConvergent())
3707 // We can only sink load instructions if there is nothing between the load and
3708 // the end of block that could change the value.
3709 if (I
->mayReadFromMemory()) {
3710 // We don't want to do any sophisticated alias analysis, so we only check
3711 // the instructions after I in I's parent block if we try to sink to its
3713 if (DestBlock
->getUniquePredecessor() != I
->getParent())
3715 for (BasicBlock::iterator Scan
= I
->getIterator(),
3716 E
= I
->getParent()->end();
3718 if (Scan
->mayWriteToMemory())
3722 I
->dropDroppableUses([DestBlock
](const Use
*U
) {
3723 if (auto *I
= dyn_cast
<Instruction
>(U
->getUser()))
3724 return I
->getParent() != DestBlock
;
3727 /// FIXME: We could remove droppable uses that are not dominated by
3728 /// the new position.
3730 BasicBlock::iterator InsertPos
= DestBlock
->getFirstInsertionPt();
3731 I
->moveBefore(&*InsertPos
);
3734 // Also sink all related debug uses from the source basic block. Otherwise we
3735 // get debug use before the def. Attempt to salvage debug uses first, to
3736 // maximise the range variables have location for. If we cannot salvage, then
3737 // mark the location undef: we know it was supposed to receive a new location
3738 // here, but that computation has been sunk.
3739 SmallVector
<DbgVariableIntrinsic
*, 2> DbgUsers
;
3740 findDbgUsers(DbgUsers
, I
);
3741 // Process the sinking DbgUsers in reverse order, as we only want to clone the
3742 // last appearing debug intrinsic for each given variable.
3743 SmallVector
<DbgVariableIntrinsic
*, 2> DbgUsersToSink
;
3744 for (DbgVariableIntrinsic
*DVI
: DbgUsers
)
3745 if (DVI
->getParent() == SrcBlock
)
3746 DbgUsersToSink
.push_back(DVI
);
3747 llvm::sort(DbgUsersToSink
,
3748 [](auto *A
, auto *B
) { return B
->comesBefore(A
); });
3750 SmallVector
<DbgVariableIntrinsic
*, 2> DIIClones
;
3751 SmallSet
<DebugVariable
, 4> SunkVariables
;
3752 for (auto User
: DbgUsersToSink
) {
3753 // A dbg.declare instruction should not be cloned, since there can only be
3754 // one per variable fragment. It should be left in the original place
3755 // because the sunk instruction is not an alloca (otherwise we could not be
3757 if (isa
<DbgDeclareInst
>(User
))
3760 DebugVariable DbgUserVariable
=
3761 DebugVariable(User
->getVariable(), User
->getExpression(),
3762 User
->getDebugLoc()->getInlinedAt());
3764 if (!SunkVariables
.insert(DbgUserVariable
).second
)
3767 DIIClones
.emplace_back(cast
<DbgVariableIntrinsic
>(User
->clone()));
3768 if (isa
<DbgDeclareInst
>(User
) && isa
<CastInst
>(I
))
3769 DIIClones
.back()->replaceVariableLocationOp(I
, I
->getOperand(0));
3770 LLVM_DEBUG(dbgs() << "CLONE: " << *DIIClones
.back() << '\n');
3773 // Perform salvaging without the clones, then sink the clones.
3774 if (!DIIClones
.empty()) {
3775 salvageDebugInfoForDbgValues(*I
, DbgUsers
);
3776 // The clones are in reverse order of original appearance, reverse again to
3777 // maintain the original order.
3778 for (auto &DIIClone
: llvm::reverse(DIIClones
)) {
3779 DIIClone
->insertBefore(&*InsertPos
);
3780 LLVM_DEBUG(dbgs() << "SINK: " << *DIIClone
<< '\n');
3787 bool InstCombinerImpl::run() {
3788 while (!Worklist
.isEmpty()) {
3789 // Walk deferred instructions in reverse order, and push them to the
3790 // worklist, which means they'll end up popped from the worklist in-order.
3791 while (Instruction
*I
= Worklist
.popDeferred()) {
3792 // Check to see if we can DCE the instruction. We do this already here to
3793 // reduce the number of uses and thus allow other folds to trigger.
3794 // Note that eraseInstFromFunction() may push additional instructions on
3795 // the deferred worklist, so this will DCE whole instruction chains.
3796 if (isInstructionTriviallyDead(I
, &TLI
)) {
3797 eraseInstFromFunction(*I
);
3805 Instruction
*I
= Worklist
.removeOne();
3806 if (I
== nullptr) continue; // skip null values.
3808 // Check to see if we can DCE the instruction.
3809 if (isInstructionTriviallyDead(I
, &TLI
)) {
3810 eraseInstFromFunction(*I
);
3815 if (!DebugCounter::shouldExecute(VisitCounter
))
3818 // Instruction isn't dead, see if we can constant propagate it.
3819 if (!I
->use_empty() &&
3820 (I
->getNumOperands() == 0 || isa
<Constant
>(I
->getOperand(0)))) {
3821 if (Constant
*C
= ConstantFoldInstruction(I
, DL
, &TLI
)) {
3822 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C
<< " from: " << *I
3825 // Add operands to the worklist.
3826 replaceInstUsesWith(*I
, C
);
3828 if (isInstructionTriviallyDead(I
, &TLI
))
3829 eraseInstFromFunction(*I
);
3830 MadeIRChange
= true;
3835 // See if we can trivially sink this instruction to its user if we can
3836 // prove that the successor is not executed more frequently than our block.
3837 if (EnableCodeSinking
)
3838 if (Use
*SingleUse
= I
->getSingleUndroppableUse()) {
3839 BasicBlock
*BB
= I
->getParent();
3840 Instruction
*UserInst
= cast
<Instruction
>(SingleUse
->getUser());
3841 BasicBlock
*UserParent
;
3843 // Get the block the use occurs in.
3844 if (PHINode
*PN
= dyn_cast
<PHINode
>(UserInst
))
3845 UserParent
= PN
->getIncomingBlock(*SingleUse
);
3847 UserParent
= UserInst
->getParent();
3849 // Try sinking to another block. If that block is unreachable, then do
3850 // not bother. SimplifyCFG should handle it.
3851 if (UserParent
!= BB
&& DT
.isReachableFromEntry(UserParent
)) {
3852 // See if the user is one of our successors that has only one
3853 // predecessor, so that we don't have to split the critical edge.
3854 bool ShouldSink
= UserParent
->getUniquePredecessor() == BB
;
3855 // Another option where we can sink is a block that ends with a
3856 // terminator that does not pass control to other block (such as
3857 // return or unreachable). In this case:
3858 // - I dominates the User (by SSA form);
3859 // - the User will be executed at most once.
3860 // So sinking I down to User is always profitable or neutral.
3862 auto *Term
= UserParent
->getTerminator();
3863 ShouldSink
= isa
<ReturnInst
>(Term
) || isa
<UnreachableInst
>(Term
);
3866 assert(DT
.dominates(BB
, UserParent
) &&
3867 "Dominance relation broken?");
3868 // Okay, the CFG is simple enough, try to sink this instruction.
3869 if (TryToSinkInstruction(I
, UserParent
)) {
3870 LLVM_DEBUG(dbgs() << "IC: Sink: " << *I
<< '\n');
3871 MadeIRChange
= true;
3872 // We'll add uses of the sunk instruction below, but since sinking
3873 // can expose opportunities for it's *operands* add them to the
3875 for (Use
&U
: I
->operands())
3876 if (Instruction
*OpI
= dyn_cast
<Instruction
>(U
.get()))
3883 // Now that we have an instruction, try combining it to simplify it.
3884 Builder
.SetInsertPoint(I
);
3885 Builder
.CollectMetadataToCopy(
3886 I
, {LLVMContext::MD_dbg
, LLVMContext::MD_annotation
});
3891 LLVM_DEBUG(raw_string_ostream
SS(OrigI
); I
->print(SS
); OrigI
= SS
.str(););
3892 LLVM_DEBUG(dbgs() << "IC: Visiting: " << OrigI
<< '\n');
3894 if (Instruction
*Result
= visit(*I
)) {
3896 // Should we replace the old instruction with a new one?
3898 LLVM_DEBUG(dbgs() << "IC: Old = " << *I
<< '\n'
3899 << " New = " << *Result
<< '\n');
3901 Result
->copyMetadata(*I
,
3902 {LLVMContext::MD_dbg
, LLVMContext::MD_annotation
});
3903 // Everything uses the new instruction now.
3904 I
->replaceAllUsesWith(Result
);
3906 // Move the name to the new instruction first.
3907 Result
->takeName(I
);
3909 // Insert the new instruction into the basic block...
3910 BasicBlock
*InstParent
= I
->getParent();
3911 BasicBlock::iterator InsertPos
= I
->getIterator();
3913 // Are we replace a PHI with something that isn't a PHI, or vice versa?
3914 if (isa
<PHINode
>(Result
) != isa
<PHINode
>(I
)) {
3915 // We need to fix up the insertion point.
3916 if (isa
<PHINode
>(I
)) // PHI -> Non-PHI
3917 InsertPos
= InstParent
->getFirstInsertionPt();
3918 else // Non-PHI -> PHI
3919 InsertPos
= InstParent
->getFirstNonPHI()->getIterator();
3922 InstParent
->getInstList().insert(InsertPos
, Result
);
3924 // Push the new instruction and any users onto the worklist.
3925 Worklist
.pushUsersToWorkList(*Result
);
3926 Worklist
.push(Result
);
3928 eraseInstFromFunction(*I
);
3930 LLVM_DEBUG(dbgs() << "IC: Mod = " << OrigI
<< '\n'
3931 << " New = " << *I
<< '\n');
3933 // If the instruction was modified, it's possible that it is now dead.
3934 // if so, remove it.
3935 if (isInstructionTriviallyDead(I
, &TLI
)) {
3936 eraseInstFromFunction(*I
);
3938 Worklist
.pushUsersToWorkList(*I
);
3942 MadeIRChange
= true;
3947 return MadeIRChange
;
3950 // Track the scopes used by !alias.scope and !noalias. In a function, a
3951 // @llvm.experimental.noalias.scope.decl is only useful if that scope is used
3952 // by both sets. If not, the declaration of the scope can be safely omitted.
3953 // The MDNode of the scope can be omitted as well for the instructions that are
3954 // part of this function. We do not do that at this point, as this might become
3955 // too time consuming to do.
3956 class AliasScopeTracker
{
3957 SmallPtrSet
<const MDNode
*, 8> UsedAliasScopesAndLists
;
3958 SmallPtrSet
<const MDNode
*, 8> UsedNoAliasScopesAndLists
;
3961 void analyse(Instruction
*I
) {
3962 // This seems to be faster than checking 'mayReadOrWriteMemory()'.
3963 if (!I
->hasMetadataOtherThanDebugLoc())
3966 auto Track
= [](Metadata
*ScopeList
, auto &Container
) {
3967 const auto *MDScopeList
= dyn_cast_or_null
<MDNode
>(ScopeList
);
3968 if (!MDScopeList
|| !Container
.insert(MDScopeList
).second
)
3970 for (auto &MDOperand
: MDScopeList
->operands())
3971 if (auto *MDScope
= dyn_cast
<MDNode
>(MDOperand
))
3972 Container
.insert(MDScope
);
3975 Track(I
->getMetadata(LLVMContext::MD_alias_scope
), UsedAliasScopesAndLists
);
3976 Track(I
->getMetadata(LLVMContext::MD_noalias
), UsedNoAliasScopesAndLists
);
3979 bool isNoAliasScopeDeclDead(Instruction
*Inst
) {
3980 NoAliasScopeDeclInst
*Decl
= dyn_cast
<NoAliasScopeDeclInst
>(Inst
);
3984 assert(Decl
->use_empty() &&
3985 "llvm.experimental.noalias.scope.decl in use ?");
3986 const MDNode
*MDSL
= Decl
->getScopeList();
3987 assert(MDSL
->getNumOperands() == 1 &&
3988 "llvm.experimental.noalias.scope should refer to a single scope");
3989 auto &MDOperand
= MDSL
->getOperand(0);
3990 if (auto *MD
= dyn_cast
<MDNode
>(MDOperand
))
3991 return !UsedAliasScopesAndLists
.contains(MD
) ||
3992 !UsedNoAliasScopesAndLists
.contains(MD
);
3994 // Not an MDNode ? throw away.
3999 /// Populate the IC worklist from a function, by walking it in depth-first
4000 /// order and adding all reachable code to the worklist.
4002 /// This has a couple of tricks to make the code faster and more powerful. In
4003 /// particular, we constant fold and DCE instructions as we go, to avoid adding
4004 /// them to the worklist (this significantly speeds up instcombine on code where
4005 /// many instructions are dead or constant). Additionally, if we find a branch
4006 /// whose condition is a known constant, we only visit the reachable successors.
4007 static bool prepareICWorklistFromFunction(Function
&F
, const DataLayout
&DL
,
4008 const TargetLibraryInfo
*TLI
,
4009 InstCombineWorklist
&ICWorklist
) {
4010 bool MadeIRChange
= false;
4011 SmallPtrSet
<BasicBlock
*, 32> Visited
;
4012 SmallVector
<BasicBlock
*, 256> Worklist
;
4013 Worklist
.push_back(&F
.front());
4015 SmallVector
<Instruction
*, 128> InstrsForInstCombineWorklist
;
4016 DenseMap
<Constant
*, Constant
*> FoldedConstants
;
4017 AliasScopeTracker SeenAliasScopes
;
4020 BasicBlock
*BB
= Worklist
.pop_back_val();
4022 // We have now visited this block! If we've already been here, ignore it.
4023 if (!Visited
.insert(BB
).second
)
4026 for (BasicBlock::iterator BBI
= BB
->begin(), E
= BB
->end(); BBI
!= E
; ) {
4027 Instruction
*Inst
= &*BBI
++;
4029 // ConstantProp instruction if trivially constant.
4030 if (!Inst
->use_empty() &&
4031 (Inst
->getNumOperands() == 0 || isa
<Constant
>(Inst
->getOperand(0))))
4032 if (Constant
*C
= ConstantFoldInstruction(Inst
, DL
, TLI
)) {
4033 LLVM_DEBUG(dbgs() << "IC: ConstFold to: " << *C
<< " from: " << *Inst
4035 Inst
->replaceAllUsesWith(C
);
4037 if (isInstructionTriviallyDead(Inst
, TLI
))
4038 Inst
->eraseFromParent();
4039 MadeIRChange
= true;
4043 // See if we can constant fold its operands.
4044 for (Use
&U
: Inst
->operands()) {
4045 if (!isa
<ConstantVector
>(U
) && !isa
<ConstantExpr
>(U
))
4048 auto *C
= cast
<Constant
>(U
);
4049 Constant
*&FoldRes
= FoldedConstants
[C
];
4051 FoldRes
= ConstantFoldConstant(C
, DL
, TLI
);
4054 LLVM_DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
4055 << "\n Old = " << *C
4056 << "\n New = " << *FoldRes
<< '\n');
4058 MadeIRChange
= true;
4062 // Skip processing debug and pseudo intrinsics in InstCombine. Processing
4063 // these call instructions consumes non-trivial amount of time and
4064 // provides no value for the optimization.
4065 if (!Inst
->isDebugOrPseudoInst()) {
4066 InstrsForInstCombineWorklist
.push_back(Inst
);
4067 SeenAliasScopes
.analyse(Inst
);
4071 // Recursively visit successors. If this is a branch or switch on a
4072 // constant, only visit the reachable successor.
4073 Instruction
*TI
= BB
->getTerminator();
4074 if (BranchInst
*BI
= dyn_cast
<BranchInst
>(TI
)) {
4075 if (BI
->isConditional() && isa
<ConstantInt
>(BI
->getCondition())) {
4076 bool CondVal
= cast
<ConstantInt
>(BI
->getCondition())->getZExtValue();
4077 BasicBlock
*ReachableBB
= BI
->getSuccessor(!CondVal
);
4078 Worklist
.push_back(ReachableBB
);
4081 } else if (SwitchInst
*SI
= dyn_cast
<SwitchInst
>(TI
)) {
4082 if (ConstantInt
*Cond
= dyn_cast
<ConstantInt
>(SI
->getCondition())) {
4083 Worklist
.push_back(SI
->findCaseValue(Cond
)->getCaseSuccessor());
4088 append_range(Worklist
, successors(TI
));
4089 } while (!Worklist
.empty());
4091 // Remove instructions inside unreachable blocks. This prevents the
4092 // instcombine code from having to deal with some bad special cases, and
4093 // reduces use counts of instructions.
4094 for (BasicBlock
&BB
: F
) {
4095 if (Visited
.count(&BB
))
4098 unsigned NumDeadInstInBB
;
4099 unsigned NumDeadDbgInstInBB
;
4100 std::tie(NumDeadInstInBB
, NumDeadDbgInstInBB
) =
4101 removeAllNonTerminatorAndEHPadInstructions(&BB
);
4103 MadeIRChange
|= NumDeadInstInBB
+ NumDeadDbgInstInBB
> 0;
4104 NumDeadInst
+= NumDeadInstInBB
;
4107 // Once we've found all of the instructions to add to instcombine's worklist,
4108 // add them in reverse order. This way instcombine will visit from the top
4109 // of the function down. This jives well with the way that it adds all uses
4110 // of instructions to the worklist after doing a transformation, thus avoiding
4111 // some N^2 behavior in pathological cases.
4112 ICWorklist
.reserve(InstrsForInstCombineWorklist
.size());
4113 for (Instruction
*Inst
: reverse(InstrsForInstCombineWorklist
)) {
4114 // DCE instruction if trivially dead. As we iterate in reverse program
4115 // order here, we will clean up whole chains of dead instructions.
4116 if (isInstructionTriviallyDead(Inst
, TLI
) ||
4117 SeenAliasScopes
.isNoAliasScopeDeclDead(Inst
)) {
4119 LLVM_DEBUG(dbgs() << "IC: DCE: " << *Inst
<< '\n');
4120 salvageDebugInfo(*Inst
);
4121 Inst
->eraseFromParent();
4122 MadeIRChange
= true;
4126 ICWorklist
.push(Inst
);
4129 return MadeIRChange
;
4132 static bool combineInstructionsOverFunction(
4133 Function
&F
, InstCombineWorklist
&Worklist
, AliasAnalysis
*AA
,
4134 AssumptionCache
&AC
, TargetLibraryInfo
&TLI
, TargetTransformInfo
&TTI
,
4135 DominatorTree
&DT
, OptimizationRemarkEmitter
&ORE
, BlockFrequencyInfo
*BFI
,
4136 ProfileSummaryInfo
*PSI
, unsigned MaxIterations
, LoopInfo
*LI
) {
4137 auto &DL
= F
.getParent()->getDataLayout();
4138 MaxIterations
= std::min(MaxIterations
, LimitMaxIterations
.getValue());
4140 /// Builder - This is an IRBuilder that automatically inserts new
4141 /// instructions into the worklist when they are created.
4142 IRBuilder
<TargetFolder
, IRBuilderCallbackInserter
> Builder(
4143 F
.getContext(), TargetFolder(DL
),
4144 IRBuilderCallbackInserter([&Worklist
, &AC
](Instruction
*I
) {
4146 if (auto *Assume
= dyn_cast
<AssumeInst
>(I
))
4147 AC
.registerAssumption(Assume
);
4150 // Lower dbg.declare intrinsics otherwise their value may be clobbered
4152 bool MadeIRChange
= false;
4153 if (ShouldLowerDbgDeclare
)
4154 MadeIRChange
= LowerDbgDeclare(F
);
4156 // Iterate while there is work to do.
4157 unsigned Iteration
= 0;
4159 ++NumWorklistIterations
;
4162 if (Iteration
> InfiniteLoopDetectionThreshold
) {
4164 "Instruction Combining seems stuck in an infinite loop after " +
4165 Twine(InfiniteLoopDetectionThreshold
) + " iterations.");
4168 if (Iteration
> MaxIterations
) {
4169 LLVM_DEBUG(dbgs() << "\n\n[IC] Iteration limit #" << MaxIterations
4170 << " on " << F
.getName()
4171 << " reached; stopping before reaching a fixpoint\n");
4175 LLVM_DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration
<< " on "
4176 << F
.getName() << "\n");
4178 MadeIRChange
|= prepareICWorklistFromFunction(F
, DL
, &TLI
, Worklist
);
4180 InstCombinerImpl
IC(Worklist
, Builder
, F
.hasMinSize(), AA
, AC
, TLI
, TTI
, DT
,
4181 ORE
, BFI
, PSI
, DL
, LI
);
4182 IC
.MaxArraySizeForCombine
= MaxArraySize
;
4187 MadeIRChange
= true;
4190 return MadeIRChange
;
4193 InstCombinePass::InstCombinePass() : MaxIterations(LimitMaxIterations
) {}
4195 InstCombinePass::InstCombinePass(unsigned MaxIterations
)
4196 : MaxIterations(MaxIterations
) {}
4198 PreservedAnalyses
InstCombinePass::run(Function
&F
,
4199 FunctionAnalysisManager
&AM
) {
4200 auto &AC
= AM
.getResult
<AssumptionAnalysis
>(F
);
4201 auto &DT
= AM
.getResult
<DominatorTreeAnalysis
>(F
);
4202 auto &TLI
= AM
.getResult
<TargetLibraryAnalysis
>(F
);
4203 auto &ORE
= AM
.getResult
<OptimizationRemarkEmitterAnalysis
>(F
);
4204 auto &TTI
= AM
.getResult
<TargetIRAnalysis
>(F
);
4206 auto *LI
= AM
.getCachedResult
<LoopAnalysis
>(F
);
4208 auto *AA
= &AM
.getResult
<AAManager
>(F
);
4209 auto &MAMProxy
= AM
.getResult
<ModuleAnalysisManagerFunctionProxy
>(F
);
4210 ProfileSummaryInfo
*PSI
=
4211 MAMProxy
.getCachedResult
<ProfileSummaryAnalysis
>(*F
.getParent());
4212 auto *BFI
= (PSI
&& PSI
->hasProfileSummary()) ?
4213 &AM
.getResult
<BlockFrequencyAnalysis
>(F
) : nullptr;
4215 if (!combineInstructionsOverFunction(F
, Worklist
, AA
, AC
, TLI
, TTI
, DT
, ORE
,
4216 BFI
, PSI
, MaxIterations
, LI
))
4217 // No changes, all analyses are preserved.
4218 return PreservedAnalyses::all();
4220 // Mark all the analyses that instcombine updates as preserved.
4221 PreservedAnalyses PA
;
4222 PA
.preserveSet
<CFGAnalyses
>();
4226 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage
&AU
) const {
4227 AU
.setPreservesCFG();
4228 AU
.addRequired
<AAResultsWrapperPass
>();
4229 AU
.addRequired
<AssumptionCacheTracker
>();
4230 AU
.addRequired
<TargetLibraryInfoWrapperPass
>();
4231 AU
.addRequired
<TargetTransformInfoWrapperPass
>();
4232 AU
.addRequired
<DominatorTreeWrapperPass
>();
4233 AU
.addRequired
<OptimizationRemarkEmitterWrapperPass
>();
4234 AU
.addPreserved
<DominatorTreeWrapperPass
>();
4235 AU
.addPreserved
<AAResultsWrapperPass
>();
4236 AU
.addPreserved
<BasicAAWrapperPass
>();
4237 AU
.addPreserved
<GlobalsAAWrapperPass
>();
4238 AU
.addRequired
<ProfileSummaryInfoWrapperPass
>();
4239 LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU
);
4242 bool InstructionCombiningPass::runOnFunction(Function
&F
) {
4243 if (skipFunction(F
))
4246 // Required analyses.
4247 auto AA
= &getAnalysis
<AAResultsWrapperPass
>().getAAResults();
4248 auto &AC
= getAnalysis
<AssumptionCacheTracker
>().getAssumptionCache(F
);
4249 auto &TLI
= getAnalysis
<TargetLibraryInfoWrapperPass
>().getTLI(F
);
4250 auto &TTI
= getAnalysis
<TargetTransformInfoWrapperPass
>().getTTI(F
);
4251 auto &DT
= getAnalysis
<DominatorTreeWrapperPass
>().getDomTree();
4252 auto &ORE
= getAnalysis
<OptimizationRemarkEmitterWrapperPass
>().getORE();
4254 // Optional analyses.
4255 auto *LIWP
= getAnalysisIfAvailable
<LoopInfoWrapperPass
>();
4256 auto *LI
= LIWP
? &LIWP
->getLoopInfo() : nullptr;
4257 ProfileSummaryInfo
*PSI
=
4258 &getAnalysis
<ProfileSummaryInfoWrapperPass
>().getPSI();
4259 BlockFrequencyInfo
*BFI
=
4260 (PSI
&& PSI
->hasProfileSummary()) ?
4261 &getAnalysis
<LazyBlockFrequencyInfoPass
>().getBFI() :
4264 return combineInstructionsOverFunction(F
, Worklist
, AA
, AC
, TLI
, TTI
, DT
, ORE
,
4265 BFI
, PSI
, MaxIterations
, LI
);
4268 char InstructionCombiningPass::ID
= 0;
4270 InstructionCombiningPass::InstructionCombiningPass()
4271 : FunctionPass(ID
), MaxIterations(InstCombineDefaultMaxIterations
) {
4272 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
4275 InstructionCombiningPass::InstructionCombiningPass(unsigned MaxIterations
)
4276 : FunctionPass(ID
), MaxIterations(MaxIterations
) {
4277 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
4280 INITIALIZE_PASS_BEGIN(InstructionCombiningPass
, "instcombine",
4281 "Combine redundant instructions", false, false)
4282 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker
)
4283 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass
)
4284 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass
)
4285 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass
)
4286 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass
)
4287 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass
)
4288 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass
)
4289 INITIALIZE_PASS_DEPENDENCY(LazyBlockFrequencyInfoPass
)
4290 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass
)
4291 INITIALIZE_PASS_END(InstructionCombiningPass
, "instcombine",
4292 "Combine redundant instructions", false, false)
4294 // Initialization Routines
4295 void llvm::initializeInstCombine(PassRegistry
&Registry
) {
4296 initializeInstructionCombiningPassPass(Registry
);
4299 void LLVMInitializeInstCombine(LLVMPassRegistryRef R
) {
4300 initializeInstructionCombiningPassPass(*unwrap(R
));
4303 FunctionPass
*llvm::createInstructionCombiningPass() {
4304 return new InstructionCombiningPass();
4307 FunctionPass
*llvm::createInstructionCombiningPass(unsigned MaxIterations
) {
4308 return new InstructionCombiningPass(MaxIterations
);
4311 void LLVMAddInstructionCombiningPass(LLVMPassManagerRef PM
) {
4312 unwrap(PM
)->add(createInstructionCombiningPass());