1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/InstCombine/InstCombine.h"
37 #include "InstCombineInternal.h"
38 #include "llvm-c/Initialization.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/AssumptionCache.h"
44 #include "llvm/Analysis/BasicAliasAnalysis.h"
45 #include "llvm/Analysis/CFG.h"
46 #include "llvm/Analysis/ConstantFolding.h"
47 #include "llvm/Analysis/EHPersonalities.h"
48 #include "llvm/Analysis/GlobalsModRef.h"
49 #include "llvm/Analysis/InstructionSimplify.h"
50 #include "llvm/Analysis/LoopInfo.h"
51 #include "llvm/Analysis/MemoryBuiltins.h"
52 #include "llvm/Analysis/TargetLibraryInfo.h"
53 #include "llvm/Analysis/ValueTracking.h"
54 #include "llvm/IR/CFG.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/GetElementPtrTypeIterator.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/PatternMatch.h"
60 #include "llvm/IR/ValueHandle.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/Scalar.h"
65 #include "llvm/Transforms/Utils/Local.h"
69 using namespace llvm::PatternMatch;
71 #define DEBUG_TYPE "instcombine"
73 STATISTIC(NumCombined , "Number of insts combined");
74 STATISTIC(NumConstProp, "Number of constant folds");
75 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
77 STATISTIC(NumExpand, "Number of expansions");
78 STATISTIC(NumFactor , "Number of factorizations");
79 STATISTIC(NumReassoc , "Number of reassociations");
82 EnableExpensiveCombines("expensive-combines",
83 cl::desc("Enable expensive instruction combines"));
85 static cl::opt<unsigned>
86 MaxArraySize("instcombine-maxarray-size", cl::init(1024),
87 cl::desc("Maximum array size considered when doing a combine"));
89 Value *InstCombiner::EmitGEPOffset(User *GEP) {
90 return llvm::EmitGEPOffset(Builder, DL, GEP);
93 /// Return true if it is desirable to convert an integer computation from a
94 /// given bit width to a new bit width.
95 /// We don't want to convert from a legal to an illegal type or from a smaller
96 /// to a larger illegal type. A width of '1' is always treated as a legal type
97 /// because i1 is a fundamental type in IR, and there are many specialized
98 /// optimizations for i1 types.
99 bool InstCombiner::shouldChangeType(unsigned FromWidth,
100 unsigned ToWidth) const {
101 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
102 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
117 /// Return true if it is desirable to convert a computation from 'From' to 'To'.
118 /// We don't want to convert from a legal to an illegal type or from a smaller
119 /// to a larger illegal type. i1 is always treated as a legal type because it is
120 /// a fundamental type in IR, and there are many specialized optimizations for
122 bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
123 assert(From->isIntegerTy() && To->isIntegerTy());
125 unsigned FromWidth = From->getPrimitiveSizeInBits();
126 unsigned ToWidth = To->getPrimitiveSizeInBits();
127 return shouldChangeType(FromWidth, ToWidth);
130 // Return true, if No Signed Wrap should be maintained for I.
131 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
132 // where both B and C should be ConstantInts, results in a constant that does
133 // not overflow. This function only handles the Add and Sub opcodes. For
134 // all other opcodes, the function conservatively returns false.
135 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
136 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
137 if (!OBO || !OBO->hasNoSignedWrap())
140 // We reason about Add and Sub Only.
141 Instruction::BinaryOps Opcode = I.getOpcode();
142 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
145 const APInt *BVal, *CVal;
146 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
149 bool Overflow = false;
150 if (Opcode == Instruction::Add)
151 (void)BVal->sadd_ov(*CVal, Overflow);
153 (void)BVal->ssub_ov(*CVal, Overflow);
158 /// Conservatively clears subclassOptionalData after a reassociation or
159 /// commutation. We preserve fast-math flags when applicable as they can be
161 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
162 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
164 I.clearSubclassOptionalData();
168 FastMathFlags FMF = I.getFastMathFlags();
169 I.clearSubclassOptionalData();
170 I.setFastMathFlags(FMF);
173 /// Combine constant operands of associative operations either before or after a
174 /// cast to eliminate one of the associative operations:
175 /// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
176 /// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
177 static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
178 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
179 if (!Cast || !Cast->hasOneUse())
182 // TODO: Enhance logic for other casts and remove this check.
183 auto CastOpcode = Cast->getOpcode();
184 if (CastOpcode != Instruction::ZExt)
187 // TODO: Enhance logic for other BinOps and remove this check.
188 if (!BinOp1->isBitwiseLogicOp())
191 auto AssocOpcode = BinOp1->getOpcode();
192 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
193 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
197 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
198 !match(BinOp2->getOperand(1), m_Constant(C2)))
201 // TODO: This assumes a zext cast.
202 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
203 // to the destination type might lose bits.
205 // Fold the constants together in the destination type:
206 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
207 Type *DestTy = C1->getType();
208 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
209 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
210 Cast->setOperand(0, BinOp2->getOperand(0));
211 BinOp1->setOperand(1, FoldedC);
215 /// This performs a few simplifications for operators that are associative or
218 /// Commutative operators:
220 /// 1. Order operands such that they are listed from right (least complex) to
221 /// left (most complex). This puts constants before unary operators before
222 /// binary operators.
224 /// Associative operators:
226 /// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
227 /// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
229 /// Associative and commutative operators:
231 /// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
232 /// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
233 /// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
234 /// if C1 and C2 are constants.
235 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
236 Instruction::BinaryOps Opcode = I.getOpcode();
237 bool Changed = false;
240 // Order operands such that they are listed from right (least complex) to
241 // left (most complex). This puts constants before unary operators before
243 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
244 getComplexity(I.getOperand(1)))
245 Changed = !I.swapOperands();
247 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
248 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
250 if (I.isAssociative()) {
251 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
252 if (Op0 && Op0->getOpcode() == Opcode) {
253 Value *A = Op0->getOperand(0);
254 Value *B = Op0->getOperand(1);
255 Value *C = I.getOperand(1);
257 // Does "B op C" simplify?
258 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
259 // It simplifies to V. Form "A op V".
262 // Conservatively clear the optional flags, since they may not be
263 // preserved by the reassociation.
264 if (MaintainNoSignedWrap(I, B, C) &&
265 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
266 // Note: this is only valid because SimplifyBinOp doesn't look at
267 // the operands to Op0.
268 I.clearSubclassOptionalData();
269 I.setHasNoSignedWrap(true);
271 ClearSubclassDataAfterReassociation(I);
280 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
281 if (Op1 && Op1->getOpcode() == Opcode) {
282 Value *A = I.getOperand(0);
283 Value *B = Op1->getOperand(0);
284 Value *C = Op1->getOperand(1);
286 // Does "A op B" simplify?
287 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
288 // It simplifies to V. Form "V op C".
291 // Conservatively clear the optional flags, since they may not be
292 // preserved by the reassociation.
293 ClearSubclassDataAfterReassociation(I);
301 if (I.isAssociative() && I.isCommutative()) {
302 if (simplifyAssocCastAssoc(&I)) {
308 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
309 if (Op0 && Op0->getOpcode() == Opcode) {
310 Value *A = Op0->getOperand(0);
311 Value *B = Op0->getOperand(1);
312 Value *C = I.getOperand(1);
314 // Does "C op A" simplify?
315 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
316 // It simplifies to V. Form "V op B".
319 // Conservatively clear the optional flags, since they may not be
320 // preserved by the reassociation.
321 ClearSubclassDataAfterReassociation(I);
328 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
329 if (Op1 && Op1->getOpcode() == Opcode) {
330 Value *A = I.getOperand(0);
331 Value *B = Op1->getOperand(0);
332 Value *C = Op1->getOperand(1);
334 // Does "C op A" simplify?
335 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
336 // It simplifies to V. Form "B op V".
339 // Conservatively clear the optional flags, since they may not be
340 // preserved by the reassociation.
341 ClearSubclassDataAfterReassociation(I);
348 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
349 // if C1 and C2 are constants.
351 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
352 isa<Constant>(Op0->getOperand(1)) &&
353 isa<Constant>(Op1->getOperand(1)) &&
354 Op0->hasOneUse() && Op1->hasOneUse()) {
355 Value *A = Op0->getOperand(0);
356 Constant *C1 = cast<Constant>(Op0->getOperand(1));
357 Value *B = Op1->getOperand(0);
358 Constant *C2 = cast<Constant>(Op1->getOperand(1));
360 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
361 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
362 if (isa<FPMathOperator>(New)) {
363 FastMathFlags Flags = I.getFastMathFlags();
364 Flags &= Op0->getFastMathFlags();
365 Flags &= Op1->getFastMathFlags();
366 New->setFastMathFlags(Flags);
368 InsertNewInstWith(New, I);
370 I.setOperand(0, New);
371 I.setOperand(1, Folded);
372 // Conservatively clear the optional flags, since they may not be
373 // preserved by the reassociation.
374 ClearSubclassDataAfterReassociation(I);
381 // No further simplifications.
386 /// Return whether "X LOp (Y ROp Z)" is always equal to
387 /// "(X LOp Y) ROp (X LOp Z)".
388 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
389 Instruction::BinaryOps ROp) {
394 case Instruction::And:
395 // And distributes over Or and Xor.
399 case Instruction::Or:
400 case Instruction::Xor:
404 case Instruction::Mul:
405 // Multiplication distributes over addition and subtraction.
409 case Instruction::Add:
410 case Instruction::Sub:
414 case Instruction::Or:
415 // Or distributes over And.
419 case Instruction::And:
425 /// Return whether "(X LOp Y) ROp Z" is always equal to
426 /// "(X ROp Z) LOp (Y ROp Z)".
427 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
428 Instruction::BinaryOps ROp) {
429 if (Instruction::isCommutative(ROp))
430 return LeftDistributesOverRight(ROp, LOp);
435 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
436 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
437 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
438 case Instruction::And:
439 case Instruction::Or:
440 case Instruction::Xor:
444 case Instruction::Shl:
445 case Instruction::LShr:
446 case Instruction::AShr:
450 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
451 // but this requires knowing that the addition does not overflow and other
456 /// This function returns identity value for given opcode, which can be used to
457 /// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
458 static Value *getIdentityValue(Instruction::BinaryOps Opcode, Value *V) {
459 if (isa<Constant>(V))
462 return ConstantExpr::getBinOpIdentity(Opcode, V->getType());
465 /// This function factors binary ops which can be combined using distributive
466 /// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
467 /// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
468 /// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
469 /// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
471 static Instruction::BinaryOps
472 getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
473 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
474 assert(Op && "Expected a binary operator");
476 LHS = Op->getOperand(0);
477 RHS = Op->getOperand(1);
479 switch (TopLevelOpcode) {
481 return Op->getOpcode();
483 case Instruction::Add:
484 case Instruction::Sub:
485 if (Op->getOpcode() == Instruction::Shl) {
486 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
487 // The multiplier is really 1 << CST.
488 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
489 return Instruction::Mul;
492 return Op->getOpcode();
495 // TODO: We can add other conversions e.g. shr => div etc.
498 /// This tries to simplify binary operations by factorizing out common terms
499 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
500 static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
501 const DataLayout &DL, BinaryOperator &I,
502 Instruction::BinaryOps InnerOpcode, Value *A,
503 Value *B, Value *C, Value *D) {
504 assert(A && B && C && D && "All values must be provided");
507 Value *SimplifiedInst = nullptr;
508 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
509 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
511 // Does "X op' Y" always equal "Y op' X"?
512 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
514 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
515 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
516 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
517 // commutative case, "(A op' B) op (C op' A)"?
518 if (A == C || (InnerCommutative && A == D)) {
521 // Consider forming "A op' (B op D)".
522 // If "B op D" simplifies then it can be formed with no cost.
523 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
524 // If "B op D" doesn't simplify then only go on if both of the existing
525 // operations "A op' B" and "C op' D" will be zapped as no longer used.
526 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
527 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
529 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
533 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
534 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
535 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
536 // commutative case, "(A op' B) op (B op' D)"?
537 if (B == D || (InnerCommutative && B == C)) {
540 // Consider forming "(A op C) op' B".
541 // If "A op C" simplifies then it can be formed with no cost.
542 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
544 // If "A op C" doesn't simplify then only go on if both of the existing
545 // operations "A op' B" and "C op' D" will be zapped as no longer used.
546 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
547 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
549 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
553 if (SimplifiedInst) {
555 SimplifiedInst->takeName(&I);
557 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
558 // TODO: Check for NUW.
559 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
560 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
562 if (isa<OverflowingBinaryOperator>(&I))
563 HasNSW = I.hasNoSignedWrap();
565 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
566 HasNSW &= LOBO->hasNoSignedWrap();
568 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
569 HasNSW &= ROBO->hasNoSignedWrap();
571 // We can propagate 'nsw' if we know that
572 // %Y = mul nsw i16 %X, C
573 // %Z = add nsw i16 %Y, %X
575 // %Z = mul nsw i16 %X, C+1
577 // iff C+1 isn't INT_MIN
579 if (TopLevelOpcode == Instruction::Add &&
580 InnerOpcode == Instruction::Mul)
581 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
582 BO->setHasNoSignedWrap(HasNSW);
586 return SimplifiedInst;
589 /// This tries to simplify binary operations which some other binary operation
590 /// distributes over either by factorizing out common terms
591 /// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
592 /// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
593 /// Returns the simplified value, or null if it didn't simplify.
594 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
595 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
596 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
597 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
598 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
602 Value *A, *B, *C, *D;
603 Instruction::BinaryOps LHSOpcode, RHSOpcode;
605 LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
607 RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
609 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
611 if (Op0 && Op1 && LHSOpcode == RHSOpcode)
612 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
615 // The instruction has the form "(A op' B) op (C)". Try to factorize common
618 if (Value *Ident = getIdentityValue(LHSOpcode, RHS))
619 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
623 // The instruction has the form "(B) op (C op' D)". Try to factorize common
626 if (Value *Ident = getIdentityValue(RHSOpcode, LHS))
627 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS, Ident,
633 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
634 // The instruction has the form "(A op' B) op C". See if expanding it out
635 // to "(A op C) op' (B op C)" results in simplifications.
636 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
637 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
639 // Do "A op C" and "B op C" both simplify?
640 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
641 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
642 // They do! Return "L op' R".
644 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
645 if ((L == A && R == B) ||
646 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
648 // Otherwise return "L op' R" if it simplifies.
649 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
651 // Otherwise, create a new instruction.
652 C = Builder->CreateBinOp(InnerOpcode, L, R);
658 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
659 // The instruction has the form "A op (B op' C)". See if expanding it out
660 // to "(A op B) op' (A op C)" results in simplifications.
661 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
662 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
664 // Do "A op B" and "A op C" both simplify?
665 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
666 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
667 // They do! Return "L op' R".
669 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
670 if ((L == B && R == C) ||
671 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
673 // Otherwise return "L op' R" if it simplifies.
674 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
676 // Otherwise, create a new instruction.
677 A = Builder->CreateBinOp(InnerOpcode, L, R);
683 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
684 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
685 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
686 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
687 if (SI0->getCondition() == SI1->getCondition()) {
689 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
690 SI1->getFalseValue(), DL, &TLI, &DT, &AC))
691 SI = Builder->CreateSelect(SI0->getCondition(),
692 Builder->CreateBinOp(TopLevelOpcode,
694 SI1->getTrueValue()),
696 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
697 SI1->getTrueValue(), DL, &TLI, &DT, &AC))
698 SI = Builder->CreateSelect(
699 SI0->getCondition(), V,
700 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
701 SI1->getFalseValue()));
713 /// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
714 /// constant zero (which is the 'negate' form).
715 Value *InstCombiner::dyn_castNegVal(Value *V) const {
716 if (BinaryOperator::isNeg(V))
717 return BinaryOperator::getNegArgument(V);
719 // Constants can be considered to be negated values if they can be folded.
720 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
721 return ConstantExpr::getNeg(C);
723 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
724 if (C->getType()->getElementType()->isIntegerTy())
725 return ConstantExpr::getNeg(C);
727 if (ConstantVector *CV = dyn_cast<ConstantVector>(V)) {
728 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
729 Constant *Elt = CV->getAggregateElement(i);
733 if (isa<UndefValue>(Elt))
736 if (!isa<ConstantInt>(Elt))
739 return ConstantExpr::getNeg(CV);
745 /// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
746 /// a constant negative zero (which is the 'negate' form).
747 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
748 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
749 return BinaryOperator::getFNegArgument(V);
751 // Constants can be considered to be negated values if they can be folded.
752 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
753 return ConstantExpr::getFNeg(C);
755 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
756 if (C->getType()->getElementType()->isFloatingPointTy())
757 return ConstantExpr::getFNeg(C);
762 static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
764 if (auto *Cast = dyn_cast<CastInst>(&I))
765 return IC->Builder->CreateCast(Cast->getOpcode(), SO, I.getType());
767 assert(I.isBinaryOp() && "Unexpected opcode for select folding");
769 // Figure out if the constant is the left or the right argument.
770 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
771 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
773 if (auto *SOC = dyn_cast<Constant>(SO)) {
775 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
776 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
779 Value *Op0 = SO, *Op1 = ConstOperand;
783 auto *BO = cast<BinaryOperator>(&I);
784 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
785 SO->getName() + ".op");
786 auto *FPInst = dyn_cast<Instruction>(RI);
787 if (FPInst && isa<FPMathOperator>(FPInst))
788 FPInst->copyFastMathFlags(BO);
792 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
793 // Don't modify shared select instructions.
794 if (!SI->hasOneUse())
797 Value *TV = SI->getTrueValue();
798 Value *FV = SI->getFalseValue();
799 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
802 // Bool selects with constant operands can be folded to logical ops.
803 if (SI->getType()->getScalarType()->isIntegerTy(1))
806 // If it's a bitcast involving vectors, make sure it has the same number of
807 // elements on both sides.
808 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
809 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
810 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
812 // Verify that either both or neither are vectors.
813 if ((SrcTy == nullptr) != (DestTy == nullptr))
816 // If vectors, verify that they have the same number of elements.
817 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
821 // Test if a CmpInst instruction is used exclusively by a select as
822 // part of a minimum or maximum operation. If so, refrain from doing
823 // any other folding. This helps out other analyses which understand
824 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
825 // and CodeGen. And in this case, at least one of the comparison
826 // operands has at least one user besides the compare (the select),
827 // which would often largely negate the benefit of folding anyway.
828 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
829 if (CI->hasOneUse()) {
830 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
831 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
832 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
837 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, this);
838 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, this);
839 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
842 static Value *foldOperationIntoPhiValue(BinaryOperator *I, Value *InV,
844 bool ConstIsRHS = isa<Constant>(I->getOperand(1));
845 Constant *C = cast<Constant>(I->getOperand(ConstIsRHS));
847 if (auto *InC = dyn_cast<Constant>(InV)) {
849 return ConstantExpr::get(I->getOpcode(), InC, C);
850 return ConstantExpr::get(I->getOpcode(), C, InC);
853 Value *Op0 = InV, *Op1 = C;
857 Value *RI = IC->Builder->CreateBinOp(I->getOpcode(), Op0, Op1, "phitmp");
858 auto *FPInst = dyn_cast<Instruction>(RI);
859 if (FPInst && isa<FPMathOperator>(FPInst))
860 FPInst->copyFastMathFlags(I);
864 Instruction *InstCombiner::foldOpIntoPhi(Instruction &I, PHINode *PN) {
865 unsigned NumPHIValues = PN->getNumIncomingValues();
866 if (NumPHIValues == 0)
869 // We normally only transform phis with a single use. However, if a PHI has
870 // multiple uses and they are all the same operation, we can fold *all* of the
871 // uses into the PHI.
872 if (!PN->hasOneUse()) {
873 // Walk the use list for the instruction, comparing them to I.
874 for (User *U : PN->users()) {
875 Instruction *UI = cast<Instruction>(U);
876 if (UI != &I && !I.isIdenticalTo(UI))
879 // Otherwise, we can replace *all* users with the new PHI we form.
882 // Check to see if all of the operands of the PHI are simple constants
883 // (constantint/constantfp/undef). If there is one non-constant value,
884 // remember the BB it is in. If there is more than one or if *it* is a PHI,
885 // bail out. We don't do arbitrary constant expressions here because moving
886 // their computation can be expensive without a cost model.
887 BasicBlock *NonConstBB = nullptr;
888 for (unsigned i = 0; i != NumPHIValues; ++i) {
889 Value *InVal = PN->getIncomingValue(i);
890 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
893 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
894 if (NonConstBB) return nullptr; // More than one non-const value.
896 NonConstBB = PN->getIncomingBlock(i);
898 // If the InVal is an invoke at the end of the pred block, then we can't
899 // insert a computation after it without breaking the edge.
900 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
901 if (II->getParent() == NonConstBB)
904 // If the incoming non-constant value is in I's block, we will remove one
905 // instruction, but insert another equivalent one, leading to infinite
907 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
911 // If there is exactly one non-constant value, we can insert a copy of the
912 // operation in that block. However, if this is a critical edge, we would be
913 // inserting the computation on some other paths (e.g. inside a loop). Only
914 // do this if the pred block is unconditionally branching into the phi block.
915 if (NonConstBB != nullptr) {
916 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
917 if (!BI || !BI->isUnconditional()) return nullptr;
920 // Okay, we can do the transformation: create the new PHI node.
921 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
922 InsertNewInstBefore(NewPN, *PN);
925 // If we are going to have to insert a new computation, do so right before the
926 // predecessor's terminator.
928 Builder->SetInsertPoint(NonConstBB->getTerminator());
930 // Next, add all of the operands to the PHI.
931 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
932 // We only currently try to fold the condition of a select when it is a phi,
933 // not the true/false values.
934 Value *TrueV = SI->getTrueValue();
935 Value *FalseV = SI->getFalseValue();
936 BasicBlock *PhiTransBB = PN->getParent();
937 for (unsigned i = 0; i != NumPHIValues; ++i) {
938 BasicBlock *ThisBB = PN->getIncomingBlock(i);
939 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
940 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
941 Value *InV = nullptr;
942 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
943 // even if currently isNullValue gives false.
944 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
945 // For vector constants, we cannot use isNullValue to fold into
946 // FalseVInPred versus TrueVInPred. When we have individual nonzero
947 // elements in the vector, we will incorrectly fold InC to
949 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
950 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
952 InV = Builder->CreateSelect(PN->getIncomingValue(i),
953 TrueVInPred, FalseVInPred, "phitmp");
954 NewPN->addIncoming(InV, ThisBB);
956 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
957 Constant *C = cast<Constant>(I.getOperand(1));
958 for (unsigned i = 0; i != NumPHIValues; ++i) {
959 Value *InV = nullptr;
960 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
961 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
962 else if (isa<ICmpInst>(CI))
963 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
966 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
968 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
970 } else if (auto *BO = dyn_cast<BinaryOperator>(&I)) {
971 for (unsigned i = 0; i != NumPHIValues; ++i) {
972 Value *InV = foldOperationIntoPhiValue(BO, PN->getIncomingValue(i), this);
973 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
976 CastInst *CI = cast<CastInst>(&I);
977 Type *RetTy = CI->getType();
978 for (unsigned i = 0; i != NumPHIValues; ++i) {
980 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
981 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
983 InV = Builder->CreateCast(CI->getOpcode(),
984 PN->getIncomingValue(i), I.getType(), "phitmp");
985 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
989 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
990 Instruction *User = cast<Instruction>(*UI++);
991 if (User == &I) continue;
992 replaceInstUsesWith(*User, NewPN);
993 eraseInstFromFunction(*User);
995 return replaceInstUsesWith(I, NewPN);
998 Instruction *InstCombiner::foldOpWithConstantIntoOperand(BinaryOperator &I) {
999 assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
1001 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
1002 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
1004 } else if (auto *PN = dyn_cast<PHINode>(I.getOperand(0))) {
1005 if (Instruction *NewPhi = foldOpIntoPhi(I, PN))
1011 /// Given a pointer type and a constant offset, determine whether or not there
1012 /// is a sequence of GEP indices into the pointed type that will land us at the
1013 /// specified offset. If so, fill them into NewIndices and return the resultant
1014 /// element type, otherwise return null.
1015 Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
1016 SmallVectorImpl<Value *> &NewIndices) {
1017 Type *Ty = PtrTy->getElementType();
1021 // Start with the index over the outer type. Note that the type size
1022 // might be zero (even if the offset isn't zero) if the indexed type
1023 // is something like [0 x {int, int}]
1024 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
1025 int64_t FirstIdx = 0;
1026 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
1027 FirstIdx = Offset/TySize;
1028 Offset -= FirstIdx*TySize;
1030 // Handle hosts where % returns negative instead of values [0..TySize).
1034 assert(Offset >= 0);
1036 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1039 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
1041 // Index into the types. If we fail, set OrigBase to null.
1043 // Indexing into tail padding between struct/array elements.
1044 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
1047 if (StructType *STy = dyn_cast<StructType>(Ty)) {
1048 const StructLayout *SL = DL.getStructLayout(STy);
1049 assert(Offset < (int64_t)SL->getSizeInBytes() &&
1050 "Offset must stay within the indexed type");
1052 unsigned Elt = SL->getElementContainingOffset(Offset);
1053 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1056 Offset -= SL->getElementOffset(Elt);
1057 Ty = STy->getElementType(Elt);
1058 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
1059 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
1060 assert(EltSize && "Cannot index into a zero-sized array");
1061 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
1063 Ty = AT->getElementType();
1065 // Otherwise, we can't index into the middle of this atomic type, bail.
1073 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1074 // If this GEP has only 0 indices, it is the same pointer as
1075 // Src. If Src is not a trivial GEP too, don't combine
1077 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1083 /// Return a value X such that Val = X * Scale, or null if none.
1084 /// If the multiplication is known not to overflow, then NoSignedWrap is set.
1085 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1086 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1087 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1088 Scale.getBitWidth() && "Scale not compatible with value!");
1090 // If Val is zero or Scale is one then Val = Val * Scale.
1091 if (match(Val, m_Zero()) || Scale == 1) {
1092 NoSignedWrap = true;
1096 // If Scale is zero then it does not divide Val.
1097 if (Scale.isMinValue())
1100 // Look through chains of multiplications, searching for a constant that is
1101 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1102 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1103 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1106 // Val = M1 * X || Analysis starts here and works down
1107 // M1 = M2 * Y || Doesn't descend into terms with more
1108 // M2 = Z * 4 \/ than one use
1110 // Then to modify a term at the bottom:
1113 // M1 = Z * Y || Replaced M2 with Z
1115 // Then to work back up correcting nsw flags.
1117 // Op - the term we are currently analyzing. Starts at Val then drills down.
1118 // Replaced with its descaled value before exiting from the drill down loop.
1121 // Parent - initially null, but after drilling down notes where Op came from.
1122 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1123 // 0'th operand of Val.
1124 std::pair<Instruction*, unsigned> Parent;
1126 // Set if the transform requires a descaling at deeper levels that doesn't
1128 bool RequireNoSignedWrap = false;
1130 // Log base 2 of the scale. Negative if not a power of 2.
1131 int32_t logScale = Scale.exactLogBase2();
1133 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1136 // If Op is a constant divisible by Scale then descale to the quotient.
1137 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1138 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1139 if (!Remainder.isMinValue())
1140 // Not divisible by Scale.
1142 // Replace with the quotient in the parent.
1143 Op = ConstantInt::get(CI->getType(), Quotient);
1144 NoSignedWrap = true;
1148 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1150 if (BO->getOpcode() == Instruction::Mul) {
1152 NoSignedWrap = BO->hasNoSignedWrap();
1153 if (RequireNoSignedWrap && !NoSignedWrap)
1156 // There are three cases for multiplication: multiplication by exactly
1157 // the scale, multiplication by a constant different to the scale, and
1158 // multiplication by something else.
1159 Value *LHS = BO->getOperand(0);
1160 Value *RHS = BO->getOperand(1);
1162 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1163 // Multiplication by a constant.
1164 if (CI->getValue() == Scale) {
1165 // Multiplication by exactly the scale, replace the multiplication
1166 // by its left-hand side in the parent.
1171 // Otherwise drill down into the constant.
1172 if (!Op->hasOneUse())
1175 Parent = std::make_pair(BO, 1);
1179 // Multiplication by something else. Drill down into the left-hand side
1180 // since that's where the reassociate pass puts the good stuff.
1181 if (!Op->hasOneUse())
1184 Parent = std::make_pair(BO, 0);
1188 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1189 isa<ConstantInt>(BO->getOperand(1))) {
1190 // Multiplication by a power of 2.
1191 NoSignedWrap = BO->hasNoSignedWrap();
1192 if (RequireNoSignedWrap && !NoSignedWrap)
1195 Value *LHS = BO->getOperand(0);
1196 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1197 getLimitedValue(Scale.getBitWidth());
1200 if (Amt == logScale) {
1201 // Multiplication by exactly the scale, replace the multiplication
1202 // by its left-hand side in the parent.
1206 if (Amt < logScale || !Op->hasOneUse())
1209 // Multiplication by more than the scale. Reduce the multiplying amount
1210 // by the scale in the parent.
1211 Parent = std::make_pair(BO, 1);
1212 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1217 if (!Op->hasOneUse())
1220 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1221 if (Cast->getOpcode() == Instruction::SExt) {
1222 // Op is sign-extended from a smaller type, descale in the smaller type.
1223 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1224 APInt SmallScale = Scale.trunc(SmallSize);
1225 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1226 // descale Op as (sext Y) * Scale. In order to have
1227 // sext (Y * SmallScale) = (sext Y) * Scale
1228 // some conditions need to hold however: SmallScale must sign-extend to
1229 // Scale and the multiplication Y * SmallScale should not overflow.
1230 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1231 // SmallScale does not sign-extend to Scale.
1233 assert(SmallScale.exactLogBase2() == logScale);
1234 // Require that Y * SmallScale must not overflow.
1235 RequireNoSignedWrap = true;
1237 // Drill down through the cast.
1238 Parent = std::make_pair(Cast, 0);
1243 if (Cast->getOpcode() == Instruction::Trunc) {
1244 // Op is truncated from a larger type, descale in the larger type.
1245 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1246 // trunc (Y * sext Scale) = (trunc Y) * Scale
1247 // always holds. However (trunc Y) * Scale may overflow even if
1248 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1249 // from this point up in the expression (see later).
1250 if (RequireNoSignedWrap)
1253 // Drill down through the cast.
1254 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1255 Parent = std::make_pair(Cast, 0);
1256 Scale = Scale.sext(LargeSize);
1257 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1259 assert(Scale.exactLogBase2() == logScale);
1264 // Unsupported expression, bail out.
1268 // If Op is zero then Val = Op * Scale.
1269 if (match(Op, m_Zero())) {
1270 NoSignedWrap = true;
1274 // We know that we can successfully descale, so from here on we can safely
1275 // modify the IR. Op holds the descaled version of the deepest term in the
1276 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1280 // The expression only had one term.
1283 // Rewrite the parent using the descaled version of its operand.
1284 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1285 assert(Op != Parent.first->getOperand(Parent.second) &&
1286 "Descaling was a no-op?");
1287 Parent.first->setOperand(Parent.second, Op);
1288 Worklist.Add(Parent.first);
1290 // Now work back up the expression correcting nsw flags. The logic is based
1291 // on the following observation: if X * Y is known not to overflow as a signed
1292 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1293 // then X * Z will not overflow as a signed multiplication either. As we work
1294 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1295 // current level has strictly smaller absolute value than the original.
1296 Instruction *Ancestor = Parent.first;
1298 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1299 // If the multiplication wasn't nsw then we can't say anything about the
1300 // value of the descaled multiplication, and we have to clear nsw flags
1301 // from this point on up.
1302 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1303 NoSignedWrap &= OpNoSignedWrap;
1304 if (NoSignedWrap != OpNoSignedWrap) {
1305 BO->setHasNoSignedWrap(NoSignedWrap);
1306 Worklist.Add(Ancestor);
1308 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1309 // The fact that the descaled input to the trunc has smaller absolute
1310 // value than the original input doesn't tell us anything useful about
1311 // the absolute values of the truncations.
1312 NoSignedWrap = false;
1314 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1315 "Failed to keep proper track of nsw flags while drilling down?");
1317 if (Ancestor == Val)
1318 // Got to the top, all done!
1321 // Move up one level in the expression.
1322 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1323 Ancestor = Ancestor->user_back();
1327 /// \brief Creates node of binary operation with the same attributes as the
1328 /// specified one but with other operands.
1329 static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1330 InstCombiner::BuilderTy *B) {
1331 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1332 // If LHS and RHS are constant, BO won't be a binary operator.
1333 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1334 NewBO->copyIRFlags(&Inst);
1338 /// \brief Makes transformation of binary operation specific for vector types.
1339 /// \param Inst Binary operator to transform.
1340 /// \return Pointer to node that must replace the original binary operator, or
1341 /// null pointer if no transformation was made.
1342 Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1343 if (!Inst.getType()->isVectorTy()) return nullptr;
1345 // It may not be safe to reorder shuffles and things like div, urem, etc.
1346 // because we may trap when executing those ops on unknown vector elements.
1348 if (!isSafeToSpeculativelyExecute(&Inst))
1351 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1352 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1353 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1354 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1356 // If both arguments of the binary operation are shuffles that use the same
1357 // mask and shuffle within a single vector, move the shuffle after the binop:
1358 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1359 auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1360 auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1361 if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1362 isa<UndefValue>(LShuf->getOperand(1)) &&
1363 isa<UndefValue>(RShuf->getOperand(1)) &&
1364 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1365 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1366 RShuf->getOperand(0), Builder);
1367 return Builder->CreateShuffleVector(
1368 NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
1371 // If one argument is a shuffle within one vector, the other is a constant,
1372 // try moving the shuffle after the binary operation.
1373 ShuffleVectorInst *Shuffle = nullptr;
1374 Constant *C1 = nullptr;
1375 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1376 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1377 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1378 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
1379 if (Shuffle && C1 &&
1380 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1381 isa<UndefValue>(Shuffle->getOperand(1)) &&
1382 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1383 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1384 // Find constant C2 that has property:
1385 // shuffle(C2, ShMask) = C1
1386 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1387 // reorder is not possible.
1388 SmallVector<Constant*, 16> C2M(VWidth,
1389 UndefValue::get(C1->getType()->getScalarType()));
1390 bool MayChange = true;
1391 for (unsigned I = 0; I < VWidth; ++I) {
1392 if (ShMask[I] >= 0) {
1393 assert(ShMask[I] < (int)VWidth);
1394 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1398 C2M[ShMask[I]] = C1->getAggregateElement(I);
1402 Constant *C2 = ConstantVector::get(C2M);
1403 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1404 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
1405 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
1406 return Builder->CreateShuffleVector(NewBO,
1407 UndefValue::get(Inst.getType()), Shuffle->getMask());
1414 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1415 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1418 SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, &TLI, &DT, &AC))
1419 return replaceInstUsesWith(GEP, V);
1421 Value *PtrOp = GEP.getOperand(0);
1423 // Eliminate unneeded casts for indices, and replace indices which displace
1424 // by multiples of a zero size type with zero.
1425 bool MadeChange = false;
1427 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
1429 gep_type_iterator GTI = gep_type_begin(GEP);
1430 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1432 // Skip indices into struct types.
1436 // Index type should have the same width as IntPtr
1437 Type *IndexTy = (*I)->getType();
1438 Type *NewIndexType = IndexTy->isVectorTy() ?
1439 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1441 // If the element type has zero size then any index over it is equivalent
1442 // to an index of zero, so replace it with zero if it is not zero already.
1443 Type *EltTy = GTI.getIndexedType();
1444 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
1445 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1446 *I = Constant::getNullValue(NewIndexType);
1450 if (IndexTy != NewIndexType) {
1451 // If we are using a wider index than needed for this platform, shrink
1452 // it to what we need. If narrower, sign-extend it to what we need.
1453 // This explicit cast can make subsequent optimizations more obvious.
1454 *I = Builder->CreateIntCast(*I, NewIndexType, true);
1461 // Check to see if the inputs to the PHI node are getelementptr instructions.
1462 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1463 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1467 // Don't fold a GEP into itself through a PHI node. This can only happen
1468 // through the back-edge of a loop. Folding a GEP into itself means that
1469 // the value of the previous iteration needs to be stored in the meantime,
1470 // thus requiring an additional register variable to be live, but not
1471 // actually achieving anything (the GEP still needs to be executed once per
1478 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1479 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1480 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1483 // As for Op1 above, don't try to fold a GEP into itself.
1487 // Keep track of the type as we walk the GEP.
1488 Type *CurTy = nullptr;
1490 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1491 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1494 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1496 // We have not seen any differences yet in the GEPs feeding the
1497 // PHI yet, so we record this one if it is allowed to be a
1500 // The first two arguments can vary for any GEP, the rest have to be
1501 // static for struct slots
1502 if (J > 1 && CurTy->isStructTy())
1507 // The GEP is different by more than one input. While this could be
1508 // extended to support GEPs that vary by more than one variable it
1509 // doesn't make sense since it greatly increases the complexity and
1510 // would result in an R+R+R addressing mode which no backend
1511 // directly supports and would need to be broken into several
1512 // simpler instructions anyway.
1517 // Sink down a layer of the type for the next iteration.
1520 CurTy = Op1->getSourceElementType();
1521 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1522 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1530 // If not all GEPs are identical we'll have to create a new PHI node.
1531 // Check that the old PHI node has only one use so that it will get
1533 if (DI != -1 && !PN->hasOneUse())
1536 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
1538 // All the GEPs feeding the PHI are identical. Clone one down into our
1539 // BB so that it can be merged with the current GEP.
1540 GEP.getParent()->getInstList().insert(
1541 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1543 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1544 // into the current block so it can be merged, and create a new PHI to
1548 IRBuilderBase::InsertPointGuard Guard(*Builder);
1549 Builder->SetInsertPoint(PN);
1550 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1551 PN->getNumOperands());
1554 for (auto &I : PN->operands())
1555 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1556 PN->getIncomingBlock(I));
1558 NewGEP->setOperand(DI, NewPN);
1559 GEP.getParent()->getInstList().insert(
1560 GEP.getParent()->getFirstInsertionPt(), NewGEP);
1561 NewGEP->setOperand(DI, NewPN);
1564 GEP.setOperand(0, NewGEP);
1568 // Combine Indices - If the source pointer to this getelementptr instruction
1569 // is a getelementptr instruction, combine the indices of the two
1570 // getelementptr instructions into a single instruction.
1572 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1573 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1576 // Note that if our source is a gep chain itself then we wait for that
1577 // chain to be resolved before we perform this transformation. This
1578 // avoids us creating a TON of code in some cases.
1579 if (GEPOperator *SrcGEP =
1580 dyn_cast<GEPOperator>(Src->getOperand(0)))
1581 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1582 return nullptr; // Wait until our source is folded to completion.
1584 SmallVector<Value*, 8> Indices;
1586 // Find out whether the last index in the source GEP is a sequential idx.
1587 bool EndsWithSequential = false;
1588 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1590 EndsWithSequential = I.isSequential();
1592 // Can we combine the two pointer arithmetics offsets?
1593 if (EndsWithSequential) {
1594 // Replace: gep (gep %P, long B), long A, ...
1595 // With: T = long A+B; gep %P, T, ...
1597 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1598 Value *GO1 = GEP.getOperand(1);
1600 // If they aren't the same type, then the input hasn't been processed
1601 // by the loop above yet (which canonicalizes sequential index types to
1602 // intptr_t). Just avoid transforming this until the input has been
1604 if (SO1->getType() != GO1->getType())
1607 Value* Sum = SimplifyAddInst(GO1, SO1, false, false, DL, &TLI, &DT, &AC);
1608 // Only do the combine when we are sure the cost after the
1609 // merge is never more than that before the merge.
1613 // Update the GEP in place if possible.
1614 if (Src->getNumOperands() == 2) {
1615 GEP.setOperand(0, Src->getOperand(0));
1616 GEP.setOperand(1, Sum);
1619 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1620 Indices.push_back(Sum);
1621 Indices.append(GEP.op_begin()+2, GEP.op_end());
1622 } else if (isa<Constant>(*GEP.idx_begin()) &&
1623 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1624 Src->getNumOperands() != 1) {
1625 // Otherwise we can do the fold if the first index of the GEP is a zero
1626 Indices.append(Src->op_begin()+1, Src->op_end());
1627 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1630 if (!Indices.empty())
1631 return GEP.isInBounds() && Src->isInBounds()
1632 ? GetElementPtrInst::CreateInBounds(
1633 Src->getSourceElementType(), Src->getOperand(0), Indices,
1635 : GetElementPtrInst::Create(Src->getSourceElementType(),
1636 Src->getOperand(0), Indices,
1640 if (GEP.getNumIndices() == 1) {
1641 unsigned AS = GEP.getPointerAddressSpace();
1642 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
1643 DL.getPointerSizeInBits(AS)) {
1644 Type *Ty = GEP.getSourceElementType();
1645 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
1647 bool Matched = false;
1650 if (TyAllocSize == 1) {
1651 V = GEP.getOperand(1);
1653 } else if (match(GEP.getOperand(1),
1654 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1655 if (TyAllocSize == 1ULL << C)
1657 } else if (match(GEP.getOperand(1),
1658 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1659 if (TyAllocSize == C)
1664 // Canonicalize (gep i8* X, -(ptrtoint Y))
1665 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1666 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1667 // pointer arithmetic.
1668 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1669 Operator *Index = cast<Operator>(V);
1670 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1671 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1672 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1674 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1677 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1678 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1679 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1686 // We do not handle pointer-vector geps here.
1687 if (GEP.getType()->isVectorTy())
1690 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1691 Value *StrippedPtr = PtrOp->stripPointerCasts();
1692 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
1694 if (StrippedPtr != PtrOp) {
1695 bool HasZeroPointerIndex = false;
1696 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1697 HasZeroPointerIndex = C->isZero();
1699 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1700 // into : GEP [10 x i8]* X, i32 0, ...
1702 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1703 // into : GEP i8* X, ...
1705 // This occurs when the program declares an array extern like "int X[];"
1706 if (HasZeroPointerIndex) {
1707 if (ArrayType *CATy =
1708 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
1709 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1710 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1711 // -> GEP i8* X, ...
1712 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1713 GetElementPtrInst *Res = GetElementPtrInst::Create(
1714 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
1715 Res->setIsInBounds(GEP.isInBounds());
1716 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1718 // Insert Res, and create an addrspacecast.
1720 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1722 // %0 = GEP i8 addrspace(1)* X, ...
1723 // addrspacecast i8 addrspace(1)* %0 to i8*
1724 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
1727 if (ArrayType *XATy =
1728 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1729 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1730 if (CATy->getElementType() == XATy->getElementType()) {
1731 // -> GEP [10 x i8]* X, i32 0, ...
1732 // At this point, we know that the cast source type is a pointer
1733 // to an array of the same type as the destination pointer
1734 // array. Because the array type is never stepped over (there
1735 // is a leading zero) we can fold the cast into this GEP.
1736 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1737 GEP.setOperand(0, StrippedPtr);
1738 GEP.setSourceElementType(XATy);
1741 // Cannot replace the base pointer directly because StrippedPtr's
1742 // address space is different. Instead, create a new GEP followed by
1743 // an addrspacecast.
1745 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1748 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1749 // addrspacecast i8 addrspace(1)* %0 to i8*
1750 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
1751 Value *NewGEP = GEP.isInBounds()
1752 ? Builder->CreateInBoundsGEP(
1753 nullptr, StrippedPtr, Idx, GEP.getName())
1754 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1756 return new AddrSpaceCastInst(NewGEP, GEP.getType());
1760 } else if (GEP.getNumOperands() == 2) {
1761 // Transform things like:
1762 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1763 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1764 Type *SrcElTy = StrippedPtrTy->getElementType();
1765 Type *ResElTy = GEP.getSourceElementType();
1766 if (SrcElTy->isArrayTy() &&
1767 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1768 DL.getTypeAllocSize(ResElTy)) {
1769 Type *IdxType = DL.getIntPtrType(GEP.getType());
1770 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
1773 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1775 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
1777 // V and GEP are both pointer types --> BitCast
1778 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1782 // Transform things like:
1783 // %V = mul i64 %N, 4
1784 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1785 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1786 if (ResElTy->isSized() && SrcElTy->isSized()) {
1787 // Check that changing the type amounts to dividing the index by a scale
1789 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1790 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
1791 if (ResSize && SrcSize % ResSize == 0) {
1792 Value *Idx = GEP.getOperand(1);
1793 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1794 uint64_t Scale = SrcSize / ResSize;
1796 // Earlier transforms ensure that the index has type IntPtrType, which
1797 // considerably simplifies the logic by eliminating implicit casts.
1798 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1799 "Index not cast to pointer width?");
1802 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1803 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1804 // If the multiplication NewIdx * Scale may overflow then the new
1805 // GEP may not be "inbounds".
1807 GEP.isInBounds() && NSW
1808 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
1810 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1813 // The NewGEP must be pointer typed, so must the old one -> BitCast
1814 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1820 // Similarly, transform things like:
1821 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1822 // (where tmp = 8*tmp2) into:
1823 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1824 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
1825 // Check that changing to the array element type amounts to dividing the
1826 // index by a scale factor.
1827 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1828 uint64_t ArrayEltSize =
1829 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
1830 if (ResSize && ArrayEltSize % ResSize == 0) {
1831 Value *Idx = GEP.getOperand(1);
1832 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1833 uint64_t Scale = ArrayEltSize / ResSize;
1835 // Earlier transforms ensure that the index has type IntPtrType, which
1836 // considerably simplifies the logic by eliminating implicit casts.
1837 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
1838 "Index not cast to pointer width?");
1841 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1842 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1843 // If the multiplication NewIdx * Scale may overflow then the new
1844 // GEP may not be "inbounds".
1846 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1849 Value *NewGEP = GEP.isInBounds() && NSW
1850 ? Builder->CreateInBoundsGEP(
1851 SrcElTy, StrippedPtr, Off, GEP.getName())
1852 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1854 // The NewGEP must be pointer typed, so must the old one -> BitCast
1855 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1863 // addrspacecast between types is canonicalized as a bitcast, then an
1864 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1865 // through the addrspacecast.
1866 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1867 // X = bitcast A addrspace(1)* to B addrspace(1)*
1868 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1869 // Z = gep Y, <...constant indices...>
1870 // Into an addrspacecasted GEP of the struct.
1871 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1875 /// See if we can simplify:
1876 /// X = bitcast A* to B*
1877 /// Y = gep X, <...constant indices...>
1878 /// into a gep of the original struct. This is important for SROA and alias
1879 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1880 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1881 Value *Operand = BCI->getOperand(0);
1882 PointerType *OpType = cast<PointerType>(Operand->getType());
1883 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
1884 APInt Offset(OffsetBits, 0);
1885 if (!isa<BitCastInst>(Operand) &&
1886 GEP.accumulateConstantOffset(DL, Offset)) {
1888 // If this GEP instruction doesn't move the pointer, just replace the GEP
1889 // with a bitcast of the real input to the dest type.
1891 // If the bitcast is of an allocation, and the allocation will be
1892 // converted to match the type of the cast, don't touch this.
1893 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
1894 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1895 if (Instruction *I = visitBitCast(*BCI)) {
1898 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
1899 replaceInstUsesWith(*BCI, I);
1905 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1906 return new AddrSpaceCastInst(Operand, GEP.getType());
1907 return new BitCastInst(Operand, GEP.getType());
1910 // Otherwise, if the offset is non-zero, we need to find out if there is a
1911 // field at Offset in 'A's type. If so, we can pull the cast through the
1913 SmallVector<Value*, 8> NewIndices;
1914 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
1917 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1918 : Builder->CreateGEP(nullptr, Operand, NewIndices);
1920 if (NGEP->getType() == GEP.getType())
1921 return replaceInstUsesWith(GEP, NGEP);
1922 NGEP->takeName(&GEP);
1924 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1925 return new AddrSpaceCastInst(NGEP, GEP.getType());
1926 return new BitCastInst(NGEP, GEP.getType());
1931 if (!GEP.isInBounds()) {
1933 DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1934 APInt BasePtrOffset(PtrWidth, 0);
1935 Value *UnderlyingPtrOp =
1936 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1938 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1939 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1940 BasePtrOffset.isNonNegative()) {
1941 APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1942 if (BasePtrOffset.ule(AllocSize)) {
1943 return GetElementPtrInst::CreateInBounds(
1944 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1953 static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1955 if (isa<ConstantPointerNull>(V))
1957 if (auto *LI = dyn_cast<LoadInst>(V))
1958 return isa<GlobalVariable>(LI->getPointerOperand());
1959 // Two distinct allocations will never be equal.
1960 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1961 // through bitcasts of V can cause
1962 // the result statement below to be true, even when AI and V (ex:
1963 // i8* ->i32* ->i8* of AI) are the same allocations.
1964 return isAllocLikeFn(V, TLI) && V != AI;
1968 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1969 const TargetLibraryInfo *TLI) {
1970 SmallVector<Instruction*, 4> Worklist;
1971 Worklist.push_back(AI);
1974 Instruction *PI = Worklist.pop_back_val();
1975 for (User *U : PI->users()) {
1976 Instruction *I = cast<Instruction>(U);
1977 switch (I->getOpcode()) {
1979 // Give up the moment we see something we can't handle.
1982 case Instruction::BitCast:
1983 case Instruction::GetElementPtr:
1984 Users.emplace_back(I);
1985 Worklist.push_back(I);
1988 case Instruction::ICmp: {
1989 ICmpInst *ICI = cast<ICmpInst>(I);
1990 // We can fold eq/ne comparisons with null to false/true, respectively.
1991 // We also fold comparisons in some conditions provided the alloc has
1992 // not escaped (see isNeverEqualToUnescapedAlloc).
1993 if (!ICI->isEquality())
1995 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
1996 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
1998 Users.emplace_back(I);
2002 case Instruction::Call:
2003 // Ignore no-op and store intrinsics.
2004 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2005 switch (II->getIntrinsicID()) {
2009 case Intrinsic::memmove:
2010 case Intrinsic::memcpy:
2011 case Intrinsic::memset: {
2012 MemIntrinsic *MI = cast<MemIntrinsic>(II);
2013 if (MI->isVolatile() || MI->getRawDest() != PI)
2017 case Intrinsic::dbg_declare:
2018 case Intrinsic::dbg_value:
2019 case Intrinsic::invariant_start:
2020 case Intrinsic::invariant_end:
2021 case Intrinsic::lifetime_start:
2022 case Intrinsic::lifetime_end:
2023 case Intrinsic::objectsize:
2024 Users.emplace_back(I);
2029 if (isFreeCall(I, TLI)) {
2030 Users.emplace_back(I);
2035 case Instruction::Store: {
2036 StoreInst *SI = cast<StoreInst>(I);
2037 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2039 Users.emplace_back(I);
2043 llvm_unreachable("missing a return?");
2045 } while (!Worklist.empty());
2049 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
2050 // If we have a malloc call which is only used in any amount of comparisons
2051 // to null and free calls, delete the calls and replace the comparisons with
2052 // true or false as appropriate.
2053 SmallVector<WeakVH, 64> Users;
2054 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
2055 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2056 // Lowering all @llvm.objectsize calls first because they may
2057 // use a bitcast/GEP of the alloca we are removing.
2061 Instruction *I = cast<Instruction>(&*Users[i]);
2063 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2064 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2065 ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2066 /*MustSucceed=*/true);
2067 replaceInstUsesWith(*I, Result);
2068 eraseInstFromFunction(*I);
2069 Users[i] = nullptr; // Skip examining in the next loop.
2073 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2077 Instruction *I = cast<Instruction>(&*Users[i]);
2079 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
2080 replaceInstUsesWith(*C,
2081 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2082 C->isFalseWhenEqual()));
2083 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
2084 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
2086 eraseInstFromFunction(*I);
2089 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
2090 // Replace invoke with a NOP intrinsic to maintain the original CFG
2091 Module *M = II->getModule();
2092 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2093 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
2094 None, "", II->getParent());
2096 return eraseInstFromFunction(MI);
2101 /// \brief Move the call to free before a NULL test.
2103 /// Check if this free is accessed after its argument has been test
2104 /// against NULL (property 0).
2105 /// If yes, it is legal to move this call in its predecessor block.
2107 /// The move is performed only if the block containing the call to free
2108 /// will be removed, i.e.:
2109 /// 1. it has only one predecessor P, and P has two successors
2110 /// 2. it contains the call and an unconditional branch
2111 /// 3. its successor is the same as its predecessor's successor
2113 /// The profitability is out-of concern here and this function should
2114 /// be called only if the caller knows this transformation would be
2115 /// profitable (e.g., for code size).
2116 static Instruction *
2117 tryToMoveFreeBeforeNullTest(CallInst &FI) {
2118 Value *Op = FI.getArgOperand(0);
2119 BasicBlock *FreeInstrBB = FI.getParent();
2120 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2122 // Validate part of constraint #1: Only one predecessor
2123 // FIXME: We can extend the number of predecessor, but in that case, we
2124 // would duplicate the call to free in each predecessor and it may
2125 // not be profitable even for code size.
2129 // Validate constraint #2: Does this block contains only the call to
2130 // free and an unconditional branch?
2131 // FIXME: We could check if we can speculate everything in the
2132 // predecessor block
2133 if (FreeInstrBB->size() != 2)
2136 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
2139 // Validate the rest of constraint #1 by matching on the pred branch.
2140 TerminatorInst *TI = PredBB->getTerminator();
2141 BasicBlock *TrueBB, *FalseBB;
2142 ICmpInst::Predicate Pred;
2143 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
2145 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
2148 // Validate constraint #3: Ensure the null case just falls through.
2149 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
2151 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2152 "Broken CFG: missing edge from predecessor to successor");
2159 Instruction *InstCombiner::visitFree(CallInst &FI) {
2160 Value *Op = FI.getArgOperand(0);
2162 // free undef -> unreachable.
2163 if (isa<UndefValue>(Op)) {
2164 // Insert a new store to null because we cannot modify the CFG here.
2165 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2166 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
2167 return eraseInstFromFunction(FI);
2170 // If we have 'free null' delete the instruction. This can happen in stl code
2171 // when lots of inlining happens.
2172 if (isa<ConstantPointerNull>(Op))
2173 return eraseInstFromFunction(FI);
2175 // If we optimize for code size, try to move the call to free before the null
2176 // test so that simplify cfg can remove the empty block and dead code
2177 // elimination the branch. I.e., helps to turn something like:
2178 // if (foo) free(foo);
2182 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2188 Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2189 if (RI.getNumOperands() == 0) // ret void
2192 Value *ResultOp = RI.getOperand(0);
2193 Type *VTy = ResultOp->getType();
2194 if (!VTy->isIntegerTy())
2197 // There might be assume intrinsics dominating this return that completely
2198 // determine the value. If so, constant fold it.
2199 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2200 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2201 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2202 if ((KnownZero|KnownOne).isAllOnesValue())
2203 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2208 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2209 // Change br (not X), label True, label False to: br X, label False, True
2211 BasicBlock *TrueDest;
2212 BasicBlock *FalseDest;
2213 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
2214 !isa<Constant>(X)) {
2215 // Swap Destinations and condition...
2217 BI.swapSuccessors();
2221 // If the condition is irrelevant, remove the use so that other
2222 // transforms on the condition become more effective.
2223 if (BI.isConditional() &&
2224 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2225 !isa<UndefValue>(BI.getCondition())) {
2226 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2230 // Canonicalize fcmp_one -> fcmp_oeq
2231 FCmpInst::Predicate FPred; Value *Y;
2232 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
2233 TrueDest, FalseDest)) &&
2234 BI.getCondition()->hasOneUse())
2235 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2236 FPred == FCmpInst::FCMP_OGE) {
2237 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2238 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
2240 // Swap Destinations and condition.
2241 BI.swapSuccessors();
2246 // Canonicalize icmp_ne -> icmp_eq
2247 ICmpInst::Predicate IPred;
2248 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
2249 TrueDest, FalseDest)) &&
2250 BI.getCondition()->hasOneUse())
2251 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2252 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2253 IPred == ICmpInst::ICMP_SGE) {
2254 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2255 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2256 // Swap Destinations and condition.
2257 BI.swapSuccessors();
2265 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2266 Value *Cond = SI.getCondition();
2268 ConstantInt *AddRHS;
2269 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2270 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2271 for (auto Case : SI.cases()) {
2272 Constant *NewCase = ConstantExpr::getSub(Case.getCaseValue(), AddRHS);
2273 assert(isa<ConstantInt>(NewCase) &&
2274 "Result of expression should be constant");
2275 Case.setValue(cast<ConstantInt>(NewCase));
2277 SI.setCondition(Op0);
2281 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2282 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2283 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
2284 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2285 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2287 // Compute the number of leading bits we can ignore.
2288 // TODO: A better way to determine this would use ComputeNumSignBits().
2289 for (auto &C : SI.cases()) {
2290 LeadingKnownZeros = std::min(
2291 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2292 LeadingKnownOnes = std::min(
2293 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2296 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2298 // Shrink the condition operand if the new type is smaller than the old type.
2299 // This may produce a non-standard type for the switch, but that's ok because
2300 // the backend should extend back to a legal type for the target.
2301 if (NewWidth > 0 && NewWidth < BitWidth) {
2302 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2303 Builder->SetInsertPoint(&SI);
2304 Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
2305 SI.setCondition(NewCond);
2307 for (auto Case : SI.cases()) {
2308 APInt TruncatedCase = Case.getCaseValue()->getValue().trunc(NewWidth);
2309 Case.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2317 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
2318 Value *Agg = EV.getAggregateOperand();
2320 if (!EV.hasIndices())
2321 return replaceInstUsesWith(EV, Agg);
2324 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, &TLI, &DT, &AC))
2325 return replaceInstUsesWith(EV, V);
2327 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2328 // We're extracting from an insertvalue instruction, compare the indices
2329 const unsigned *exti, *exte, *insi, *inse;
2330 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2331 exte = EV.idx_end(), inse = IV->idx_end();
2332 exti != exte && insi != inse;
2335 // The insert and extract both reference distinctly different elements.
2336 // This means the extract is not influenced by the insert, and we can
2337 // replace the aggregate operand of the extract with the aggregate
2338 // operand of the insert. i.e., replace
2339 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2340 // %E = extractvalue { i32, { i32 } } %I, 0
2342 // %E = extractvalue { i32, { i32 } } %A, 0
2343 return ExtractValueInst::Create(IV->getAggregateOperand(),
2346 if (exti == exte && insi == inse)
2347 // Both iterators are at the end: Index lists are identical. Replace
2348 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2349 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2351 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
2353 // The extract list is a prefix of the insert list. i.e. replace
2354 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2355 // %E = extractvalue { i32, { i32 } } %I, 1
2357 // %X = extractvalue { i32, { i32 } } %A, 1
2358 // %E = insertvalue { i32 } %X, i32 42, 0
2359 // by switching the order of the insert and extract (though the
2360 // insertvalue should be left in, since it may have other uses).
2361 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
2363 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
2364 makeArrayRef(insi, inse));
2367 // The insert list is a prefix of the extract list
2368 // We can simply remove the common indices from the extract and make it
2369 // operate on the inserted value instead of the insertvalue result.
2371 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2372 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2374 // %E extractvalue { i32 } { i32 42 }, 0
2375 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
2376 makeArrayRef(exti, exte));
2378 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2379 // We're extracting from an intrinsic, see if we're the only user, which
2380 // allows us to simplify multiple result intrinsics to simpler things that
2381 // just get one value.
2382 if (II->hasOneUse()) {
2383 // Check if we're grabbing the overflow bit or the result of a 'with
2384 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2385 // and replace it with a traditional binary instruction.
2386 switch (II->getIntrinsicID()) {
2387 case Intrinsic::uadd_with_overflow:
2388 case Intrinsic::sadd_with_overflow:
2389 if (*EV.idx_begin() == 0) { // Normal result.
2390 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2391 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2392 eraseInstFromFunction(*II);
2393 return BinaryOperator::CreateAdd(LHS, RHS);
2396 // If the normal result of the add is dead, and the RHS is a constant,
2397 // we can transform this into a range comparison.
2398 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
2399 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2400 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2401 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2402 ConstantExpr::getNot(CI));
2404 case Intrinsic::usub_with_overflow:
2405 case Intrinsic::ssub_with_overflow:
2406 if (*EV.idx_begin() == 0) { // Normal result.
2407 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2408 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2409 eraseInstFromFunction(*II);
2410 return BinaryOperator::CreateSub(LHS, RHS);
2413 case Intrinsic::umul_with_overflow:
2414 case Intrinsic::smul_with_overflow:
2415 if (*EV.idx_begin() == 0) { // Normal result.
2416 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
2417 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2418 eraseInstFromFunction(*II);
2419 return BinaryOperator::CreateMul(LHS, RHS);
2427 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2428 // If the (non-volatile) load only has one use, we can rewrite this to a
2429 // load from a GEP. This reduces the size of the load. If a load is used
2430 // only by extractvalue instructions then this either must have been
2431 // optimized before, or it is a struct with padding, in which case we
2432 // don't want to do the transformation as it loses padding knowledge.
2433 if (L->isSimple() && L->hasOneUse()) {
2434 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2435 SmallVector<Value*, 4> Indices;
2436 // Prefix an i32 0 since we need the first element.
2437 Indices.push_back(Builder->getInt32(0));
2438 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2440 Indices.push_back(Builder->getInt32(*I));
2442 // We need to insert these at the location of the old load, not at that of
2443 // the extractvalue.
2444 Builder->SetInsertPoint(L);
2445 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2446 L->getPointerOperand(), Indices);
2447 // Returning the load directly will cause the main loop to insert it in
2448 // the wrong spot, so use replaceInstUsesWith().
2449 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2451 // We could simplify extracts from other values. Note that nested extracts may
2452 // already be simplified implicitly by the above: extract (extract (insert) )
2453 // will be translated into extract ( insert ( extract ) ) first and then just
2454 // the value inserted, if appropriate. Similarly for extracts from single-use
2455 // loads: extract (extract (load)) will be translated to extract (load (gep))
2456 // and if again single-use then via load (gep (gep)) to load (gep).
2457 // However, double extracts from e.g. function arguments or return values
2458 // aren't handled yet.
2462 /// Return 'true' if the given typeinfo will match anything.
2463 static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
2464 switch (Personality) {
2465 case EHPersonality::GNU_C:
2466 case EHPersonality::GNU_C_SjLj:
2467 case EHPersonality::Rust:
2468 // The GCC C EH and Rust personality only exists to support cleanups, so
2469 // it's not clear what the semantics of catch clauses are.
2471 case EHPersonality::Unknown:
2473 case EHPersonality::GNU_Ada:
2474 // While __gnat_all_others_value will match any Ada exception, it doesn't
2475 // match foreign exceptions (or didn't, before gcc-4.7).
2477 case EHPersonality::GNU_CXX:
2478 case EHPersonality::GNU_CXX_SjLj:
2479 case EHPersonality::GNU_ObjC:
2480 case EHPersonality::MSVC_X86SEH:
2481 case EHPersonality::MSVC_Win64SEH:
2482 case EHPersonality::MSVC_CXX:
2483 case EHPersonality::CoreCLR:
2484 return TypeInfo->isNullValue();
2486 llvm_unreachable("invalid enum");
2489 static bool shorter_filter(const Value *LHS, const Value *RHS) {
2491 cast<ArrayType>(LHS->getType())->getNumElements()
2493 cast<ArrayType>(RHS->getType())->getNumElements();
2496 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2497 // The logic here should be correct for any real-world personality function.
2498 // However if that turns out not to be true, the offending logic can always
2499 // be conditioned on the personality function, like the catch-all logic is.
2500 EHPersonality Personality =
2501 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
2503 // Simplify the list of clauses, eg by removing repeated catch clauses
2504 // (these are often created by inlining).
2505 bool MakeNewInstruction = false; // If true, recreate using the following:
2506 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
2507 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2509 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2510 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2511 bool isLastClause = i + 1 == e;
2512 if (LI.isCatch(i)) {
2514 Constant *CatchClause = LI.getClause(i);
2515 Constant *TypeInfo = CatchClause->stripPointerCasts();
2517 // If we already saw this clause, there is no point in having a second
2519 if (AlreadyCaught.insert(TypeInfo).second) {
2520 // This catch clause was not already seen.
2521 NewClauses.push_back(CatchClause);
2523 // Repeated catch clause - drop the redundant copy.
2524 MakeNewInstruction = true;
2527 // If this is a catch-all then there is no point in keeping any following
2528 // clauses or marking the landingpad as having a cleanup.
2529 if (isCatchAll(Personality, TypeInfo)) {
2531 MakeNewInstruction = true;
2532 CleanupFlag = false;
2536 // A filter clause. If any of the filter elements were already caught
2537 // then they can be dropped from the filter. It is tempting to try to
2538 // exploit the filter further by saying that any typeinfo that does not
2539 // occur in the filter can't be caught later (and thus can be dropped).
2540 // However this would be wrong, since typeinfos can match without being
2541 // equal (for example if one represents a C++ class, and the other some
2542 // class derived from it).
2543 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
2544 Constant *FilterClause = LI.getClause(i);
2545 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2546 unsigned NumTypeInfos = FilterType->getNumElements();
2548 // An empty filter catches everything, so there is no point in keeping any
2549 // following clauses or marking the landingpad as having a cleanup. By
2550 // dealing with this case here the following code is made a bit simpler.
2551 if (!NumTypeInfos) {
2552 NewClauses.push_back(FilterClause);
2554 MakeNewInstruction = true;
2555 CleanupFlag = false;
2559 bool MakeNewFilter = false; // If true, make a new filter.
2560 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2561 if (isa<ConstantAggregateZero>(FilterClause)) {
2562 // Not an empty filter - it contains at least one null typeinfo.
2563 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2564 Constant *TypeInfo =
2565 Constant::getNullValue(FilterType->getElementType());
2566 // If this typeinfo is a catch-all then the filter can never match.
2567 if (isCatchAll(Personality, TypeInfo)) {
2568 // Throw the filter away.
2569 MakeNewInstruction = true;
2573 // There is no point in having multiple copies of this typeinfo, so
2574 // discard all but the first copy if there is more than one.
2575 NewFilterElts.push_back(TypeInfo);
2576 if (NumTypeInfos > 1)
2577 MakeNewFilter = true;
2579 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2580 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2581 NewFilterElts.reserve(NumTypeInfos);
2583 // Remove any filter elements that were already caught or that already
2584 // occurred in the filter. While there, see if any of the elements are
2585 // catch-alls. If so, the filter can be discarded.
2586 bool SawCatchAll = false;
2587 for (unsigned j = 0; j != NumTypeInfos; ++j) {
2588 Constant *Elt = Filter->getOperand(j);
2589 Constant *TypeInfo = Elt->stripPointerCasts();
2590 if (isCatchAll(Personality, TypeInfo)) {
2591 // This element is a catch-all. Bail out, noting this fact.
2596 // Even if we've seen a type in a catch clause, we don't want to
2597 // remove it from the filter. An unexpected type handler may be
2598 // set up for a call site which throws an exception of the same
2599 // type caught. In order for the exception thrown by the unexpected
2600 // handler to propagate correctly, the filter must be correctly
2601 // described for the call site.
2605 // void unexpected() { throw 1;}
2606 // void foo() throw (int) {
2607 // std::set_unexpected(unexpected);
2610 // } catch (int i) {}
2613 // There is no point in having multiple copies of the same typeinfo in
2614 // a filter, so only add it if we didn't already.
2615 if (SeenInFilter.insert(TypeInfo).second)
2616 NewFilterElts.push_back(cast<Constant>(Elt));
2618 // A filter containing a catch-all cannot match anything by definition.
2620 // Throw the filter away.
2621 MakeNewInstruction = true;
2625 // If we dropped something from the filter, make a new one.
2626 if (NewFilterElts.size() < NumTypeInfos)
2627 MakeNewFilter = true;
2629 if (MakeNewFilter) {
2630 FilterType = ArrayType::get(FilterType->getElementType(),
2631 NewFilterElts.size());
2632 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2633 MakeNewInstruction = true;
2636 NewClauses.push_back(FilterClause);
2638 // If the new filter is empty then it will catch everything so there is
2639 // no point in keeping any following clauses or marking the landingpad
2640 // as having a cleanup. The case of the original filter being empty was
2641 // already handled above.
2642 if (MakeNewFilter && !NewFilterElts.size()) {
2643 assert(MakeNewInstruction && "New filter but not a new instruction!");
2644 CleanupFlag = false;
2650 // If several filters occur in a row then reorder them so that the shortest
2651 // filters come first (those with the smallest number of elements). This is
2652 // advantageous because shorter filters are more likely to match, speeding up
2653 // unwinding, but mostly because it increases the effectiveness of the other
2654 // filter optimizations below.
2655 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2657 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2658 for (j = i; j != e; ++j)
2659 if (!isa<ArrayType>(NewClauses[j]->getType()))
2662 // Check whether the filters are already sorted by length. We need to know
2663 // if sorting them is actually going to do anything so that we only make a
2664 // new landingpad instruction if it does.
2665 for (unsigned k = i; k + 1 < j; ++k)
2666 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2667 // Not sorted, so sort the filters now. Doing an unstable sort would be
2668 // correct too but reordering filters pointlessly might confuse users.
2669 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2671 MakeNewInstruction = true;
2675 // Look for the next batch of filters.
2679 // If typeinfos matched if and only if equal, then the elements of a filter L
2680 // that occurs later than a filter F could be replaced by the intersection of
2681 // the elements of F and L. In reality two typeinfos can match without being
2682 // equal (for example if one represents a C++ class, and the other some class
2683 // derived from it) so it would be wrong to perform this transform in general.
2684 // However the transform is correct and useful if F is a subset of L. In that
2685 // case L can be replaced by F, and thus removed altogether since repeating a
2686 // filter is pointless. So here we look at all pairs of filters F and L where
2687 // L follows F in the list of clauses, and remove L if every element of F is
2688 // an element of L. This can occur when inlining C++ functions with exception
2690 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2691 // Examine each filter in turn.
2692 Value *Filter = NewClauses[i];
2693 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2695 // Not a filter - skip it.
2697 unsigned FElts = FTy->getNumElements();
2698 // Examine each filter following this one. Doing this backwards means that
2699 // we don't have to worry about filters disappearing under us when removed.
2700 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2701 Value *LFilter = NewClauses[j];
2702 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2704 // Not a filter - skip it.
2706 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2707 // an element of LFilter, then discard LFilter.
2708 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
2709 // If Filter is empty then it is a subset of LFilter.
2712 NewClauses.erase(J);
2713 MakeNewInstruction = true;
2714 // Move on to the next filter.
2717 unsigned LElts = LTy->getNumElements();
2718 // If Filter is longer than LFilter then it cannot be a subset of it.
2720 // Move on to the next filter.
2722 // At this point we know that LFilter has at least one element.
2723 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2724 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2725 // already know that Filter is not longer than LFilter).
2726 if (isa<ConstantAggregateZero>(Filter)) {
2727 assert(FElts <= LElts && "Should have handled this case earlier!");
2729 NewClauses.erase(J);
2730 MakeNewInstruction = true;
2732 // Move on to the next filter.
2735 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2736 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2737 // Since Filter is non-empty and contains only zeros, it is a subset of
2738 // LFilter iff LFilter contains a zero.
2739 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2740 for (unsigned l = 0; l != LElts; ++l)
2741 if (LArray->getOperand(l)->isNullValue()) {
2742 // LFilter contains a zero - discard it.
2743 NewClauses.erase(J);
2744 MakeNewInstruction = true;
2747 // Move on to the next filter.
2750 // At this point we know that both filters are ConstantArrays. Loop over
2751 // operands to see whether every element of Filter is also an element of
2752 // LFilter. Since filters tend to be short this is probably faster than
2753 // using a method that scales nicely.
2754 ConstantArray *FArray = cast<ConstantArray>(Filter);
2755 bool AllFound = true;
2756 for (unsigned f = 0; f != FElts; ++f) {
2757 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2759 for (unsigned l = 0; l != LElts; ++l) {
2760 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2761 if (LTypeInfo == FTypeInfo) {
2771 NewClauses.erase(J);
2772 MakeNewInstruction = true;
2774 // Move on to the next filter.
2778 // If we changed any of the clauses, replace the old landingpad instruction
2780 if (MakeNewInstruction) {
2781 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2783 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2784 NLI->addClause(NewClauses[i]);
2785 // A landing pad with no clauses must have the cleanup flag set. It is
2786 // theoretically possible, though highly unlikely, that we eliminated all
2787 // clauses. If so, force the cleanup flag to true.
2788 if (NewClauses.empty())
2790 NLI->setCleanup(CleanupFlag);
2794 // Even if none of the clauses changed, we may nonetheless have understood
2795 // that the cleanup flag is pointless. Clear it if so.
2796 if (LI.isCleanup() != CleanupFlag) {
2797 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2798 LI.setCleanup(CleanupFlag);
2805 /// Try to move the specified instruction from its current block into the
2806 /// beginning of DestBlock, which can only happen if it's safe to move the
2807 /// instruction past all of the instructions between it and the end of its
2809 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2810 assert(I->hasOneUse() && "Invariants didn't hold!");
2812 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2813 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
2814 isa<TerminatorInst>(I))
2817 // Do not sink alloca instructions out of the entry block.
2818 if (isa<AllocaInst>(I) && I->getParent() ==
2819 &DestBlock->getParent()->getEntryBlock())
2822 // Do not sink into catchswitch blocks.
2823 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2826 // Do not sink convergent call instructions.
2827 if (auto *CI = dyn_cast<CallInst>(I)) {
2828 if (CI->isConvergent())
2831 // We can only sink load instructions if there is nothing between the load and
2832 // the end of block that could change the value.
2833 if (I->mayReadFromMemory()) {
2834 for (BasicBlock::iterator Scan = I->getIterator(),
2835 E = I->getParent()->end();
2837 if (Scan->mayWriteToMemory())
2841 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2842 I->moveBefore(&*InsertPos);
2847 bool InstCombiner::run() {
2848 while (!Worklist.isEmpty()) {
2849 Instruction *I = Worklist.RemoveOne();
2850 if (I == nullptr) continue; // skip null values.
2852 // Check to see if we can DCE the instruction.
2853 if (isInstructionTriviallyDead(I, &TLI)) {
2854 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
2855 eraseInstFromFunction(*I);
2857 MadeIRChange = true;
2861 // Instruction isn't dead, see if we can constant propagate it.
2862 if (!I->use_empty() &&
2863 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
2864 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
2865 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2867 // Add operands to the worklist.
2868 replaceInstUsesWith(*I, C);
2870 if (isInstructionTriviallyDead(I, &TLI))
2871 eraseInstFromFunction(*I);
2872 MadeIRChange = true;
2877 // In general, it is possible for computeKnownBits to determine all bits in
2878 // a value even when the operands are not all constants.
2879 Type *Ty = I->getType();
2880 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2881 unsigned BitWidth = Ty->getScalarSizeInBits();
2882 APInt KnownZero(BitWidth, 0);
2883 APInt KnownOne(BitWidth, 0);
2884 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2885 if ((KnownZero | KnownOne).isAllOnesValue()) {
2886 Constant *C = ConstantInt::get(Ty, KnownOne);
2887 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2888 " from: " << *I << '\n');
2890 // Add operands to the worklist.
2891 replaceInstUsesWith(*I, C);
2893 if (isInstructionTriviallyDead(I, &TLI))
2894 eraseInstFromFunction(*I);
2895 MadeIRChange = true;
2900 // See if we can trivially sink this instruction to a successor basic block.
2901 if (I->hasOneUse()) {
2902 BasicBlock *BB = I->getParent();
2903 Instruction *UserInst = cast<Instruction>(*I->user_begin());
2904 BasicBlock *UserParent;
2906 // Get the block the use occurs in.
2907 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2908 UserParent = PN->getIncomingBlock(*I->use_begin());
2910 UserParent = UserInst->getParent();
2912 if (UserParent != BB) {
2913 bool UserIsSuccessor = false;
2914 // See if the user is one of our successors.
2915 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2916 if (*SI == UserParent) {
2917 UserIsSuccessor = true;
2921 // If the user is one of our immediate successors, and if that successor
2922 // only has us as a predecessors (we'd have to split the critical edge
2923 // otherwise), we can keep going.
2924 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
2925 // Okay, the CFG is simple enough, try to sink this instruction.
2926 if (TryToSinkInstruction(I, UserParent)) {
2927 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
2928 MadeIRChange = true;
2929 // We'll add uses of the sunk instruction below, but since sinking
2930 // can expose opportunities for it's *operands* add them to the
2932 for (Use &U : I->operands())
2933 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2940 // Now that we have an instruction, try combining it to simplify it.
2941 Builder->SetInsertPoint(I);
2942 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2947 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2948 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
2950 if (Instruction *Result = visit(*I)) {
2952 // Should we replace the old instruction with a new one?
2954 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
2955 << " New = " << *Result << '\n');
2957 if (I->getDebugLoc())
2958 Result->setDebugLoc(I->getDebugLoc());
2959 // Everything uses the new instruction now.
2960 I->replaceAllUsesWith(Result);
2962 // Move the name to the new instruction first.
2963 Result->takeName(I);
2965 // Push the new instruction and any users onto the worklist.
2966 Worklist.AddUsersToWorkList(*Result);
2967 Worklist.Add(Result);
2969 // Insert the new instruction into the basic block...
2970 BasicBlock *InstParent = I->getParent();
2971 BasicBlock::iterator InsertPos = I->getIterator();
2973 // If we replace a PHI with something that isn't a PHI, fix up the
2975 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2976 InsertPos = InstParent->getFirstInsertionPt();
2978 InstParent->getInstList().insert(InsertPos, Result);
2980 eraseInstFromFunction(*I);
2982 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
2983 << " New = " << *I << '\n');
2985 // If the instruction was modified, it's possible that it is now dead.
2986 // if so, remove it.
2987 if (isInstructionTriviallyDead(I, &TLI)) {
2988 eraseInstFromFunction(*I);
2990 Worklist.AddUsersToWorkList(*I);
2994 MadeIRChange = true;
2999 return MadeIRChange;
3002 /// Walk the function in depth-first order, adding all reachable code to the
3005 /// This has a couple of tricks to make the code faster and more powerful. In
3006 /// particular, we constant fold and DCE instructions as we go, to avoid adding
3007 /// them to the worklist (this significantly speeds up instcombine on code where
3008 /// many instructions are dead or constant). Additionally, if we find a branch
3009 /// whose condition is a known constant, we only visit the reachable successors.
3011 static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
3012 SmallPtrSetImpl<BasicBlock *> &Visited,
3013 InstCombineWorklist &ICWorklist,
3014 const TargetLibraryInfo *TLI) {
3015 bool MadeIRChange = false;
3016 SmallVector<BasicBlock*, 256> Worklist;
3017 Worklist.push_back(BB);
3019 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
3020 DenseMap<Constant *, Constant *> FoldedConstants;
3023 BB = Worklist.pop_back_val();
3025 // We have now visited this block! If we've already been here, ignore it.
3026 if (!Visited.insert(BB).second)
3029 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3030 Instruction *Inst = &*BBI++;
3032 // DCE instruction if trivially dead.
3033 if (isInstructionTriviallyDead(Inst, TLI)) {
3035 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3036 Inst->eraseFromParent();
3040 // ConstantProp instruction if trivially constant.
3041 if (!Inst->use_empty() &&
3042 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
3043 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3044 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3046 Inst->replaceAllUsesWith(C);
3048 if (isInstructionTriviallyDead(Inst, TLI))
3049 Inst->eraseFromParent();
3053 // See if we can constant fold its operands.
3054 for (Use &U : Inst->operands()) {
3055 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
3058 auto *C = cast<Constant>(U);
3059 Constant *&FoldRes = FoldedConstants[C];
3061 FoldRes = ConstantFoldConstant(C, DL, TLI);
3066 DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3067 << "\n Old = " << *C
3068 << "\n New = " << *FoldRes << '\n');
3070 MadeIRChange = true;
3074 InstrsForInstCombineWorklist.push_back(Inst);
3077 // Recursively visit successors. If this is a branch or switch on a
3078 // constant, only visit the reachable successor.
3079 TerminatorInst *TI = BB->getTerminator();
3080 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3081 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3082 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3083 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3084 Worklist.push_back(ReachableBB);
3087 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3088 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3089 Worklist.push_back(SI->findCaseValue(Cond)->getCaseSuccessor());
3094 for (BasicBlock *SuccBB : TI->successors())
3095 Worklist.push_back(SuccBB);
3096 } while (!Worklist.empty());
3098 // Once we've found all of the instructions to add to instcombine's worklist,
3099 // add them in reverse order. This way instcombine will visit from the top
3100 // of the function down. This jives well with the way that it adds all uses
3101 // of instructions to the worklist after doing a transformation, thus avoiding
3102 // some N^2 behavior in pathological cases.
3103 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
3105 return MadeIRChange;
3108 /// \brief Populate the IC worklist from a function, and prune any dead basic
3109 /// blocks discovered in the process.
3111 /// This also does basic constant propagation and other forward fixing to make
3112 /// the combiner itself run much faster.
3113 static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
3114 TargetLibraryInfo *TLI,
3115 InstCombineWorklist &ICWorklist) {
3116 bool MadeIRChange = false;
3118 // Do a depth-first traversal of the function, populate the worklist with
3119 // the reachable instructions. Ignore blocks that are not reachable. Keep
3120 // track of which blocks we visit.
3121 SmallPtrSet<BasicBlock *, 32> Visited;
3123 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
3125 // Do a quick scan over the function. If we find any blocks that are
3126 // unreachable, remove any instructions inside of them. This prevents
3127 // the instcombine code from having to deal with some bad special cases.
3128 for (BasicBlock &BB : F) {
3129 if (Visited.count(&BB))
3132 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
3133 MadeIRChange |= NumDeadInstInBB > 0;
3134 NumDeadInst += NumDeadInstInBB;
3137 return MadeIRChange;
3141 combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
3142 AliasAnalysis *AA, AssumptionCache &AC,
3143 TargetLibraryInfo &TLI, DominatorTree &DT,
3144 bool ExpensiveCombines = true,
3145 LoopInfo *LI = nullptr) {
3146 auto &DL = F.getParent()->getDataLayout();
3147 ExpensiveCombines |= EnableExpensiveCombines;
3149 /// Builder - This is an IRBuilder that automatically inserts new
3150 /// instructions into the worklist when they are created.
3151 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3152 F.getContext(), TargetFolder(DL),
3153 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3156 using namespace llvm::PatternMatch;
3157 if (match(I, m_Intrinsic<Intrinsic::assume>()))
3158 AC.registerAssumption(cast<CallInst>(I));
3161 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3163 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3165 // Iterate while there is work to do.
3169 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3170 << F.getName() << "\n");
3172 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
3174 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
3175 AA, AC, TLI, DT, DL, LI);
3176 IC.MaxArraySizeForCombine = MaxArraySize;
3177 Changed |= IC.run();
3183 return DbgDeclaresChanged || Iteration > 1;
3186 PreservedAnalyses InstCombinePass::run(Function &F,
3187 FunctionAnalysisManager &AM) {
3188 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3189 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3190 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
3192 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
3194 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3195 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3196 ExpensiveCombines, LI))
3197 // No changes, all analyses are preserved.
3198 return PreservedAnalyses::all();
3200 // Mark all the analyses that instcombine updates as preserved.
3201 PreservedAnalyses PA;
3202 PA.preserveSet<CFGAnalyses>();
3203 PA.preserve<AAManager>();
3204 PA.preserve<GlobalsAA>();
3208 void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3209 AU.setPreservesCFG();
3210 AU.addRequired<AAResultsWrapperPass>();
3211 AU.addRequired<AssumptionCacheTracker>();
3212 AU.addRequired<TargetLibraryInfoWrapperPass>();
3213 AU.addRequired<DominatorTreeWrapperPass>();
3214 AU.addPreserved<DominatorTreeWrapperPass>();
3215 AU.addPreserved<AAResultsWrapperPass>();
3216 AU.addPreserved<BasicAAWrapperPass>();
3217 AU.addPreserved<GlobalsAAWrapperPass>();
3220 bool InstructionCombiningPass::runOnFunction(Function &F) {
3221 if (skipFunction(F))
3224 // Required analyses.
3225 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
3226 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
3227 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3228 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3230 // Optional analyses.
3231 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3232 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3234 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3235 ExpensiveCombines, LI);
3238 char InstructionCombiningPass::ID = 0;
3239 INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3240 "Combine redundant instructions", false, false)
3241 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3242 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3243 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3244 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3245 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
3246 INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3247 "Combine redundant instructions", false, false)
3249 // Initialization Routines
3250 void llvm::initializeInstCombine(PassRegistry &Registry) {
3251 initializeInstructionCombiningPassPass(Registry);
3254 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3255 initializeInstructionCombiningPassPass(*unwrap(R));
3258 FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3259 return new InstructionCombiningPass(ExpensiveCombines);