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 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "InstCombine.h"
39 #include "llvm-c/Initialization.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/ValueHandle.h"
54 #include "llvm/Target/TargetLibraryInfo.h"
55 #include "llvm/Transforms/Utils/Local.h"
56 #include "llvm/Wrap.h"
60 using namespace llvm::PatternMatch;
62 STATISTIC(NumCombined , "Number of insts combined");
63 STATISTIC(NumConstProp, "Number of constant folds");
64 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
65 STATISTIC(NumSunkInst , "Number of instructions sunk");
66 STATISTIC(NumExpand, "Number of expansions");
67 STATISTIC(NumFactor , "Number of factorizations");
68 STATISTIC(NumReassoc , "Number of reassociations");
70 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
72 cl::desc("Enable unsafe double to float "
73 "shrinking for math lib calls"));
75 // Initialization Routines
76 void llvm::initializeInstCombine(PassRegistry &Registry) {
77 initializeInstCombinerPass(Registry);
80 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
81 initializeInstCombine(*unwrap(R));
84 char InstCombiner::ID = 0;
85 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
86 "Combine redundant instructions", false, false)
87 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
88 INITIALIZE_PASS_END(InstCombiner, "instcombine",
89 "Combine redundant instructions", false, false)
91 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
93 AU.addRequired<TargetLibraryInfo>();
97 Value *InstCombiner::EmitGEPOffset(User *GEP) {
98 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
101 /// ShouldChangeType - Return true if it is desirable to convert a computation
102 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
103 /// type for example, or from a smaller to a larger illegal type.
104 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
105 assert(From->isIntegerTy() && To->isIntegerTy());
107 // If we don't have TD, we don't know if the source/dest are legal.
108 if (!TD) return false;
110 unsigned FromWidth = From->getPrimitiveSizeInBits();
111 unsigned ToWidth = To->getPrimitiveSizeInBits();
112 bool FromLegal = TD->isLegalInteger(FromWidth);
113 bool ToLegal = TD->isLegalInteger(ToWidth);
115 // If this is a legal integer from type, and the result would be an illegal
116 // type, don't do the transformation.
117 if (FromLegal && !ToLegal)
120 // Otherwise, if both are illegal, do not increase the size of the result. We
121 // do allow things like i160 -> i64, but not i64 -> i160.
122 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
128 // Return true, if No Signed Wrap should be maintained for I.
129 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
130 // where both B and C should be ConstantInts, results in a constant that does
131 // not overflow. This function only handles the Add and Sub opcodes. For
132 // all other opcodes, the function conservatively returns false.
133 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
134 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
135 if (!OBO || !OBO->hasNoSignedWrap()) {
139 // We reason about Add and Sub Only.
140 Instruction::BinaryOps Opcode = I.getOpcode();
141 if (Opcode != Instruction::Add &&
142 Opcode != Instruction::Sub) {
146 ConstantInt *CB = dyn_cast<ConstantInt>(B);
147 ConstantInt *CC = dyn_cast<ConstantInt>(C);
153 const APInt &BVal = CB->getValue();
154 const APInt &CVal = CC->getValue();
155 bool Overflow = false;
157 if (Opcode == Instruction::Add) {
158 BVal.sadd_ov(CVal, Overflow);
160 BVal.ssub_ov(CVal, Overflow);
166 /// Conservatively clears subclassOptionalData after a reassociation or
167 /// commutation. We preserve fast-math flags when applicable as they can be
169 static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
170 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
172 I.clearSubclassOptionalData();
176 FastMathFlags FMF = I.getFastMathFlags();
177 I.clearSubclassOptionalData();
178 I.setFastMathFlags(FMF);
181 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
182 /// operators which are associative or commutative:
184 // Commutative operators:
186 // 1. Order operands such that they are listed from right (least complex) to
187 // left (most complex). This puts constants before unary operators before
190 // Associative operators:
192 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
193 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
195 // Associative and commutative operators:
197 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
198 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
199 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
200 // if C1 and C2 are constants.
202 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
203 Instruction::BinaryOps Opcode = I.getOpcode();
204 bool Changed = false;
207 // Order operands such that they are listed from right (least complex) to
208 // left (most complex). This puts constants before unary operators before
210 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
211 getComplexity(I.getOperand(1)))
212 Changed = !I.swapOperands();
214 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
215 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
217 if (I.isAssociative()) {
218 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
219 if (Op0 && Op0->getOpcode() == Opcode) {
220 Value *A = Op0->getOperand(0);
221 Value *B = Op0->getOperand(1);
222 Value *C = I.getOperand(1);
224 // Does "B op C" simplify?
225 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
226 // It simplifies to V. Form "A op V".
229 // Conservatively clear the optional flags, since they may not be
230 // preserved by the reassociation.
231 if (MaintainNoSignedWrap(I, B, C) &&
232 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
233 // Note: this is only valid because SimplifyBinOp doesn't look at
234 // the operands to Op0.
235 I.clearSubclassOptionalData();
236 I.setHasNoSignedWrap(true);
238 ClearSubclassDataAfterReassociation(I);
247 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
248 if (Op1 && Op1->getOpcode() == Opcode) {
249 Value *A = I.getOperand(0);
250 Value *B = Op1->getOperand(0);
251 Value *C = Op1->getOperand(1);
253 // Does "A op B" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
255 // It simplifies to V. Form "V op C".
258 // Conservatively clear the optional flags, since they may not be
259 // preserved by the reassociation.
260 ClearSubclassDataAfterReassociation(I);
268 if (I.isAssociative() && I.isCommutative()) {
269 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
270 if (Op0 && Op0->getOpcode() == Opcode) {
271 Value *A = Op0->getOperand(0);
272 Value *B = Op0->getOperand(1);
273 Value *C = I.getOperand(1);
275 // Does "C op A" simplify?
276 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
277 // It simplifies to V. Form "V op B".
280 // Conservatively clear the optional flags, since they may not be
281 // preserved by the reassociation.
282 ClearSubclassDataAfterReassociation(I);
289 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
290 if (Op1 && Op1->getOpcode() == Opcode) {
291 Value *A = I.getOperand(0);
292 Value *B = Op1->getOperand(0);
293 Value *C = Op1->getOperand(1);
295 // Does "C op A" simplify?
296 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
297 // It simplifies to V. Form "B op V".
300 // Conservatively clear the optional flags, since they may not be
301 // preserved by the reassociation.
302 ClearSubclassDataAfterReassociation(I);
309 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
310 // if C1 and C2 are constants.
312 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
313 isa<Constant>(Op0->getOperand(1)) &&
314 isa<Constant>(Op1->getOperand(1)) &&
315 Op0->hasOneUse() && Op1->hasOneUse()) {
316 Value *A = Op0->getOperand(0);
317 Constant *C1 = cast<Constant>(Op0->getOperand(1));
318 Value *B = Op1->getOperand(0);
319 Constant *C2 = cast<Constant>(Op1->getOperand(1));
321 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
322 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
323 InsertNewInstWith(New, I);
325 I.setOperand(0, New);
326 I.setOperand(1, Folded);
327 // Conservatively clear the optional flags, since they may not be
328 // preserved by the reassociation.
329 ClearSubclassDataAfterReassociation(I);
336 // No further simplifications.
341 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
342 /// "(X LOp Y) ROp (X LOp Z)".
343 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
344 Instruction::BinaryOps ROp) {
349 case Instruction::And:
350 // And distributes over Or and Xor.
354 case Instruction::Or:
355 case Instruction::Xor:
359 case Instruction::Mul:
360 // Multiplication distributes over addition and subtraction.
364 case Instruction::Add:
365 case Instruction::Sub:
369 case Instruction::Or:
370 // Or distributes over And.
374 case Instruction::And:
380 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
381 /// "(X ROp Z) LOp (Y ROp Z)".
382 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
383 Instruction::BinaryOps ROp) {
384 if (Instruction::isCommutative(ROp))
385 return LeftDistributesOverRight(ROp, LOp);
386 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
387 // but this requires knowing that the addition does not overflow and other
392 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
393 /// which some other binary operation distributes over either by factorizing
394 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
395 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
396 /// a win). Returns the simplified value, or null if it didn't simplify.
397 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
398 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
399 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
400 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
401 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
404 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
405 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
407 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
408 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
409 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
411 // Does "X op' Y" always equal "Y op' X"?
412 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
414 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
415 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
416 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
417 // commutative case, "(A op' B) op (C op' A)"?
418 if (A == C || (InnerCommutative && A == D)) {
421 // Consider forming "A op' (B op D)".
422 // If "B op D" simplifies then it can be formed with no cost.
423 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
424 // If "B op D" doesn't simplify then only go on if both of the existing
425 // operations "A op' B" and "C op' D" will be zapped as no longer used.
426 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
427 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
430 V = Builder->CreateBinOp(InnerOpcode, A, V);
436 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
437 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
438 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
439 // commutative case, "(A op' B) op (B op' D)"?
440 if (B == D || (InnerCommutative && B == C)) {
443 // Consider forming "(A op C) op' B".
444 // If "A op C" simplifies then it can be formed with no cost.
445 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
446 // If "A op C" doesn't simplify then only go on if both of the existing
447 // operations "A op' B" and "C op' D" will be zapped as no longer used.
448 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
449 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
452 V = Builder->CreateBinOp(InnerOpcode, V, B);
460 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
461 // The instruction has the form "(A op' B) op C". See if expanding it out
462 // to "(A op C) op' (B op C)" results in simplifications.
463 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
464 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
466 // Do "A op C" and "B op C" both simplify?
467 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
468 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
469 // They do! Return "L op' R".
471 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
472 if ((L == A && R == B) ||
473 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
475 // Otherwise return "L op' R" if it simplifies.
476 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
478 // Otherwise, create a new instruction.
479 C = Builder->CreateBinOp(InnerOpcode, L, R);
485 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
486 // The instruction has the form "A op (B op' C)". See if expanding it out
487 // to "(A op B) op' (A op C)" results in simplifications.
488 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
489 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
491 // Do "A op B" and "A op C" both simplify?
492 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
493 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
494 // They do! Return "L op' R".
496 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
497 if ((L == B && R == C) ||
498 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
500 // Otherwise return "L op' R" if it simplifies.
501 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
503 // Otherwise, create a new instruction.
504 A = Builder->CreateBinOp(InnerOpcode, L, R);
513 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
514 // if the LHS is a constant zero (which is the 'negate' form).
516 Value *InstCombiner::dyn_castNegVal(Value *V) const {
517 if (BinaryOperator::isNeg(V))
518 return BinaryOperator::getNegArgument(V);
520 // Constants can be considered to be negated values if they can be folded.
521 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
522 return ConstantExpr::getNeg(C);
524 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
525 if (C->getType()->getElementType()->isIntegerTy())
526 return ConstantExpr::getNeg(C);
531 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
532 // instruction if the LHS is a constant negative zero (which is the 'negate'
535 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
536 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
537 return BinaryOperator::getFNegArgument(V);
539 // Constants can be considered to be negated values if they can be folded.
540 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
541 return ConstantExpr::getFNeg(C);
543 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
544 if (C->getType()->getElementType()->isFloatingPointTy())
545 return ConstantExpr::getFNeg(C);
550 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
552 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
553 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
556 // Figure out if the constant is the left or the right argument.
557 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
558 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
560 if (Constant *SOC = dyn_cast<Constant>(SO)) {
562 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
563 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
566 Value *Op0 = SO, *Op1 = ConstOperand;
570 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
571 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
572 SO->getName()+".op");
573 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
574 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
575 SO->getName()+".cmp");
576 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
577 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
578 SO->getName()+".cmp");
579 llvm_unreachable("Unknown binary instruction type!");
582 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
583 // constant as the other operand, try to fold the binary operator into the
584 // select arguments. This also works for Cast instructions, which obviously do
585 // not have a second operand.
586 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
587 // Don't modify shared select instructions
588 if (!SI->hasOneUse()) return 0;
589 Value *TV = SI->getOperand(1);
590 Value *FV = SI->getOperand(2);
592 if (isa<Constant>(TV) || isa<Constant>(FV)) {
593 // Bool selects with constant operands can be folded to logical ops.
594 if (SI->getType()->isIntegerTy(1)) return 0;
596 // If it's a bitcast involving vectors, make sure it has the same number of
597 // elements on both sides.
598 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
599 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
600 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
602 // Verify that either both or neither are vectors.
603 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
604 // If vectors, verify that they have the same number of elements.
605 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
609 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
610 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
612 return SelectInst::Create(SI->getCondition(),
613 SelectTrueVal, SelectFalseVal);
619 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
620 /// has a PHI node as operand #0, see if we can fold the instruction into the
621 /// PHI (which is only possible if all operands to the PHI are constants).
623 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
624 PHINode *PN = cast<PHINode>(I.getOperand(0));
625 unsigned NumPHIValues = PN->getNumIncomingValues();
626 if (NumPHIValues == 0)
629 // We normally only transform phis with a single use. However, if a PHI has
630 // multiple uses and they are all the same operation, we can fold *all* of the
631 // uses into the PHI.
632 if (!PN->hasOneUse()) {
633 // Walk the use list for the instruction, comparing them to I.
634 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
636 Instruction *User = cast<Instruction>(*UI);
637 if (User != &I && !I.isIdenticalTo(User))
640 // Otherwise, we can replace *all* users with the new PHI we form.
643 // Check to see if all of the operands of the PHI are simple constants
644 // (constantint/constantfp/undef). If there is one non-constant value,
645 // remember the BB it is in. If there is more than one or if *it* is a PHI,
646 // bail out. We don't do arbitrary constant expressions here because moving
647 // their computation can be expensive without a cost model.
648 BasicBlock *NonConstBB = 0;
649 for (unsigned i = 0; i != NumPHIValues; ++i) {
650 Value *InVal = PN->getIncomingValue(i);
651 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
654 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
655 if (NonConstBB) return 0; // More than one non-const value.
657 NonConstBB = PN->getIncomingBlock(i);
659 // If the InVal is an invoke at the end of the pred block, then we can't
660 // insert a computation after it without breaking the edge.
661 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
662 if (II->getParent() == NonConstBB)
665 // If the incoming non-constant value is in I's block, we will remove one
666 // instruction, but insert another equivalent one, leading to infinite
668 if (NonConstBB == I.getParent())
672 // If there is exactly one non-constant value, we can insert a copy of the
673 // operation in that block. However, if this is a critical edge, we would be
674 // inserting the computation one some other paths (e.g. inside a loop). Only
675 // do this if the pred block is unconditionally branching into the phi block.
676 if (NonConstBB != 0) {
677 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
678 if (!BI || !BI->isUnconditional()) return 0;
681 // Okay, we can do the transformation: create the new PHI node.
682 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
683 InsertNewInstBefore(NewPN, *PN);
686 // If we are going to have to insert a new computation, do so right before the
687 // predecessors terminator.
689 Builder->SetInsertPoint(NonConstBB->getTerminator());
691 // Next, add all of the operands to the PHI.
692 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
693 // We only currently try to fold the condition of a select when it is a phi,
694 // not the true/false values.
695 Value *TrueV = SI->getTrueValue();
696 Value *FalseV = SI->getFalseValue();
697 BasicBlock *PhiTransBB = PN->getParent();
698 for (unsigned i = 0; i != NumPHIValues; ++i) {
699 BasicBlock *ThisBB = PN->getIncomingBlock(i);
700 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
701 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
703 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
704 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
706 InV = Builder->CreateSelect(PN->getIncomingValue(i),
707 TrueVInPred, FalseVInPred, "phitmp");
708 NewPN->addIncoming(InV, ThisBB);
710 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
711 Constant *C = cast<Constant>(I.getOperand(1));
712 for (unsigned i = 0; i != NumPHIValues; ++i) {
714 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
715 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
716 else if (isa<ICmpInst>(CI))
717 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
720 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
722 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
724 } else if (I.getNumOperands() == 2) {
725 Constant *C = cast<Constant>(I.getOperand(1));
726 for (unsigned i = 0; i != NumPHIValues; ++i) {
728 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
729 InV = ConstantExpr::get(I.getOpcode(), InC, C);
731 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
732 PN->getIncomingValue(i), C, "phitmp");
733 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
736 CastInst *CI = cast<CastInst>(&I);
737 Type *RetTy = CI->getType();
738 for (unsigned i = 0; i != NumPHIValues; ++i) {
740 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
741 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
743 InV = Builder->CreateCast(CI->getOpcode(),
744 PN->getIncomingValue(i), I.getType(), "phitmp");
745 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
749 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
751 Instruction *User = cast<Instruction>(*UI++);
752 if (User == &I) continue;
753 ReplaceInstUsesWith(*User, NewPN);
754 EraseInstFromFunction(*User);
756 return ReplaceInstUsesWith(I, NewPN);
759 /// FindElementAtOffset - Given a type and a constant offset, determine whether
760 /// or not there is a sequence of GEP indices into the type that will land us at
761 /// the specified offset. If so, fill them into NewIndices and return the
762 /// resultant element type, otherwise return null.
763 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
764 SmallVectorImpl<Value*> &NewIndices) {
766 if (!Ty->isSized()) return 0;
768 // Start with the index over the outer type. Note that the type size
769 // might be zero (even if the offset isn't zero) if the indexed type
770 // is something like [0 x {int, int}]
771 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
772 int64_t FirstIdx = 0;
773 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
774 FirstIdx = Offset/TySize;
775 Offset -= FirstIdx*TySize;
777 // Handle hosts where % returns negative instead of values [0..TySize).
783 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
786 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
788 // Index into the types. If we fail, set OrigBase to null.
790 // Indexing into tail padding between struct/array elements.
791 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
794 if (StructType *STy = dyn_cast<StructType>(Ty)) {
795 const StructLayout *SL = TD->getStructLayout(STy);
796 assert(Offset < (int64_t)SL->getSizeInBytes() &&
797 "Offset must stay within the indexed type");
799 unsigned Elt = SL->getElementContainingOffset(Offset);
800 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
803 Offset -= SL->getElementOffset(Elt);
804 Ty = STy->getElementType(Elt);
805 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
806 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
807 assert(EltSize && "Cannot index into a zero-sized array");
808 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
810 Ty = AT->getElementType();
812 // Otherwise, we can't index into the middle of this atomic type, bail.
820 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
821 // If this GEP has only 0 indices, it is the same pointer as
822 // Src. If Src is not a trivial GEP too, don't combine
824 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
830 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
831 /// the multiplication is known not to overflow then NoSignedWrap is set.
832 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
833 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
834 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
835 Scale.getBitWidth() && "Scale not compatible with value!");
837 // If Val is zero or Scale is one then Val = Val * Scale.
838 if (match(Val, m_Zero()) || Scale == 1) {
843 // If Scale is zero then it does not divide Val.
844 if (Scale.isMinValue())
847 // Look through chains of multiplications, searching for a constant that is
848 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
849 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
850 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
853 // Val = M1 * X || Analysis starts here and works down
854 // M1 = M2 * Y || Doesn't descend into terms with more
855 // M2 = Z * 4 \/ than one use
857 // Then to modify a term at the bottom:
860 // M1 = Z * Y || Replaced M2 with Z
862 // Then to work back up correcting nsw flags.
864 // Op - the term we are currently analyzing. Starts at Val then drills down.
865 // Replaced with its descaled value before exiting from the drill down loop.
868 // Parent - initially null, but after drilling down notes where Op came from.
869 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
870 // 0'th operand of Val.
871 std::pair<Instruction*, unsigned> Parent;
873 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
874 // levels that doesn't overflow.
875 bool RequireNoSignedWrap = false;
877 // logScale - log base 2 of the scale. Negative if not a power of 2.
878 int32_t logScale = Scale.exactLogBase2();
880 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
882 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
883 // If Op is a constant divisible by Scale then descale to the quotient.
884 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
885 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
886 if (!Remainder.isMinValue())
887 // Not divisible by Scale.
889 // Replace with the quotient in the parent.
890 Op = ConstantInt::get(CI->getType(), Quotient);
895 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
897 if (BO->getOpcode() == Instruction::Mul) {
899 NoSignedWrap = BO->hasNoSignedWrap();
900 if (RequireNoSignedWrap && !NoSignedWrap)
903 // There are three cases for multiplication: multiplication by exactly
904 // the scale, multiplication by a constant different to the scale, and
905 // multiplication by something else.
906 Value *LHS = BO->getOperand(0);
907 Value *RHS = BO->getOperand(1);
909 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
910 // Multiplication by a constant.
911 if (CI->getValue() == Scale) {
912 // Multiplication by exactly the scale, replace the multiplication
913 // by its left-hand side in the parent.
918 // Otherwise drill down into the constant.
919 if (!Op->hasOneUse())
922 Parent = std::make_pair(BO, 1);
926 // Multiplication by something else. Drill down into the left-hand side
927 // since that's where the reassociate pass puts the good stuff.
928 if (!Op->hasOneUse())
931 Parent = std::make_pair(BO, 0);
935 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
936 isa<ConstantInt>(BO->getOperand(1))) {
937 // Multiplication by a power of 2.
938 NoSignedWrap = BO->hasNoSignedWrap();
939 if (RequireNoSignedWrap && !NoSignedWrap)
942 Value *LHS = BO->getOperand(0);
943 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
944 getLimitedValue(Scale.getBitWidth());
947 if (Amt == logScale) {
948 // Multiplication by exactly the scale, replace the multiplication
949 // by its left-hand side in the parent.
953 if (Amt < logScale || !Op->hasOneUse())
956 // Multiplication by more than the scale. Reduce the multiplying amount
957 // by the scale in the parent.
958 Parent = std::make_pair(BO, 1);
959 Op = ConstantInt::get(BO->getType(), Amt - logScale);
964 if (!Op->hasOneUse())
967 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
968 if (Cast->getOpcode() == Instruction::SExt) {
969 // Op is sign-extended from a smaller type, descale in the smaller type.
970 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
971 APInt SmallScale = Scale.trunc(SmallSize);
972 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
973 // descale Op as (sext Y) * Scale. In order to have
974 // sext (Y * SmallScale) = (sext Y) * Scale
975 // some conditions need to hold however: SmallScale must sign-extend to
976 // Scale and the multiplication Y * SmallScale should not overflow.
977 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
978 // SmallScale does not sign-extend to Scale.
980 assert(SmallScale.exactLogBase2() == logScale);
981 // Require that Y * SmallScale must not overflow.
982 RequireNoSignedWrap = true;
984 // Drill down through the cast.
985 Parent = std::make_pair(Cast, 0);
990 if (Cast->getOpcode() == Instruction::Trunc) {
991 // Op is truncated from a larger type, descale in the larger type.
992 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
993 // trunc (Y * sext Scale) = (trunc Y) * Scale
994 // always holds. However (trunc Y) * Scale may overflow even if
995 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
996 // from this point up in the expression (see later).
997 if (RequireNoSignedWrap)
1000 // Drill down through the cast.
1001 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1002 Parent = std::make_pair(Cast, 0);
1003 Scale = Scale.sext(LargeSize);
1004 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1006 assert(Scale.exactLogBase2() == logScale);
1011 // Unsupported expression, bail out.
1015 // We know that we can successfully descale, so from here on we can safely
1016 // modify the IR. Op holds the descaled version of the deepest term in the
1017 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1021 // The expression only had one term.
1024 // Rewrite the parent using the descaled version of its operand.
1025 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1026 assert(Op != Parent.first->getOperand(Parent.second) &&
1027 "Descaling was a no-op?");
1028 Parent.first->setOperand(Parent.second, Op);
1029 Worklist.Add(Parent.first);
1031 // Now work back up the expression correcting nsw flags. The logic is based
1032 // on the following observation: if X * Y is known not to overflow as a signed
1033 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1034 // then X * Z will not overflow as a signed multiplication either. As we work
1035 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1036 // current level has strictly smaller absolute value than the original.
1037 Instruction *Ancestor = Parent.first;
1039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1040 // If the multiplication wasn't nsw then we can't say anything about the
1041 // value of the descaled multiplication, and we have to clear nsw flags
1042 // from this point on up.
1043 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1044 NoSignedWrap &= OpNoSignedWrap;
1045 if (NoSignedWrap != OpNoSignedWrap) {
1046 BO->setHasNoSignedWrap(NoSignedWrap);
1047 Worklist.Add(Ancestor);
1049 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1050 // The fact that the descaled input to the trunc has smaller absolute
1051 // value than the original input doesn't tell us anything useful about
1052 // the absolute values of the truncations.
1053 NoSignedWrap = false;
1055 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1056 "Failed to keep proper track of nsw flags while drilling down?");
1058 if (Ancestor == Val)
1059 // Got to the top, all done!
1062 // Move up one level in the expression.
1063 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1064 Ancestor = Ancestor->use_back();
1068 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1069 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1071 if (Value *V = SimplifyGEPInst(Ops, TD))
1072 return ReplaceInstUsesWith(GEP, V);
1074 Value *PtrOp = GEP.getOperand(0);
1076 // Eliminate unneeded casts for indices, and replace indices which displace
1077 // by multiples of a zero size type with zero.
1079 bool MadeChange = false;
1080 Type *IntPtrTy = TD->getIntPtrType(GEP.getPointerOperandType());
1082 gep_type_iterator GTI = gep_type_begin(GEP);
1083 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1084 I != E; ++I, ++GTI) {
1085 // Skip indices into struct types.
1086 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1087 if (!SeqTy) continue;
1089 // If the element type has zero size then any index over it is equivalent
1090 // to an index of zero, so replace it with zero if it is not zero already.
1091 if (SeqTy->getElementType()->isSized() &&
1092 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
1093 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1094 *I = Constant::getNullValue(IntPtrTy);
1098 Type *IndexTy = (*I)->getType();
1099 if (IndexTy != IntPtrTy) {
1100 // If we are using a wider index than needed for this platform, shrink
1101 // it to what we need. If narrower, sign-extend it to what we need.
1102 // This explicit cast can make subsequent optimizations more obvious.
1103 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1107 if (MadeChange) return &GEP;
1110 // Combine Indices - If the source pointer to this getelementptr instruction
1111 // is a getelementptr instruction, combine the indices of the two
1112 // getelementptr instructions into a single instruction.
1114 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1115 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1118 // Note that if our source is a gep chain itself then we wait for that
1119 // chain to be resolved before we perform this transformation. This
1120 // avoids us creating a TON of code in some cases.
1121 if (GEPOperator *SrcGEP =
1122 dyn_cast<GEPOperator>(Src->getOperand(0)))
1123 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1124 return 0; // Wait until our source is folded to completion.
1126 SmallVector<Value*, 8> Indices;
1128 // Find out whether the last index in the source GEP is a sequential idx.
1129 bool EndsWithSequential = false;
1130 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1132 EndsWithSequential = !(*I)->isStructTy();
1134 // Can we combine the two pointer arithmetics offsets?
1135 if (EndsWithSequential) {
1136 // Replace: gep (gep %P, long B), long A, ...
1137 // With: T = long A+B; gep %P, T, ...
1140 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1141 Value *GO1 = GEP.getOperand(1);
1142 if (SO1 == Constant::getNullValue(SO1->getType())) {
1144 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1147 // If they aren't the same type, then the input hasn't been processed
1148 // by the loop above yet (which canonicalizes sequential index types to
1149 // intptr_t). Just avoid transforming this until the input has been
1151 if (SO1->getType() != GO1->getType())
1153 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1156 // Update the GEP in place if possible.
1157 if (Src->getNumOperands() == 2) {
1158 GEP.setOperand(0, Src->getOperand(0));
1159 GEP.setOperand(1, Sum);
1162 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1163 Indices.push_back(Sum);
1164 Indices.append(GEP.op_begin()+2, GEP.op_end());
1165 } else if (isa<Constant>(*GEP.idx_begin()) &&
1166 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1167 Src->getNumOperands() != 1) {
1168 // Otherwise we can do the fold if the first index of the GEP is a zero
1169 Indices.append(Src->op_begin()+1, Src->op_end());
1170 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1173 if (!Indices.empty())
1174 return (GEP.isInBounds() && Src->isInBounds()) ?
1175 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1177 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1180 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1181 Value *StrippedPtr = PtrOp->stripPointerCasts();
1182 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1184 // We do not handle pointer-vector geps here.
1188 if (StrippedPtr != PtrOp &&
1189 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1191 bool HasZeroPointerIndex = false;
1192 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1193 HasZeroPointerIndex = C->isZero();
1195 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1196 // into : GEP [10 x i8]* X, i32 0, ...
1198 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1199 // into : GEP i8* X, ...
1201 // This occurs when the program declares an array extern like "int X[];"
1202 if (HasZeroPointerIndex) {
1203 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1204 if (ArrayType *CATy =
1205 dyn_cast<ArrayType>(CPTy->getElementType())) {
1206 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1207 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1208 // -> GEP i8* X, ...
1209 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1210 GetElementPtrInst *Res =
1211 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1212 Res->setIsInBounds(GEP.isInBounds());
1216 if (ArrayType *XATy =
1217 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1218 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1219 if (CATy->getElementType() == XATy->getElementType()) {
1220 // -> GEP [10 x i8]* X, i32 0, ...
1221 // At this point, we know that the cast source type is a pointer
1222 // to an array of the same type as the destination pointer
1223 // array. Because the array type is never stepped over (there
1224 // is a leading zero) we can fold the cast into this GEP.
1225 GEP.setOperand(0, StrippedPtr);
1230 } else if (GEP.getNumOperands() == 2) {
1231 // Transform things like:
1232 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1233 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1234 Type *SrcElTy = StrippedPtrTy->getElementType();
1235 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
1236 if (TD && SrcElTy->isArrayTy() &&
1237 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
1238 TD->getTypeAllocSize(ResElTy)) {
1240 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1241 Idx[1] = GEP.getOperand(1);
1242 Value *NewGEP = GEP.isInBounds() ?
1243 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1244 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1245 // V and GEP are both pointer types --> BitCast
1246 return new BitCastInst(NewGEP, GEP.getType());
1249 // Transform things like:
1250 // %V = mul i64 %N, 4
1251 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1252 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1253 if (TD && ResElTy->isSized() && SrcElTy->isSized()) {
1254 // Check that changing the type amounts to dividing the index by a scale
1256 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1257 uint64_t SrcSize = TD->getTypeAllocSize(SrcElTy);
1258 if (ResSize && SrcSize % ResSize == 0) {
1259 Value *Idx = GEP.getOperand(1);
1260 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1261 uint64_t Scale = SrcSize / ResSize;
1263 // Earlier transforms ensure that the index has type IntPtrType, which
1264 // considerably simplifies the logic by eliminating implicit casts.
1265 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1266 "Index not cast to pointer width?");
1269 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1270 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1271 // If the multiplication NewIdx * Scale may overflow then the new
1272 // GEP may not be "inbounds".
1273 Value *NewGEP = GEP.isInBounds() && NSW ?
1274 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1275 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1276 // The NewGEP must be pointer typed, so must the old one -> BitCast
1277 return new BitCastInst(NewGEP, GEP.getType());
1282 // Similarly, transform things like:
1283 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1284 // (where tmp = 8*tmp2) into:
1285 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1286 if (TD && ResElTy->isSized() && SrcElTy->isSized() &&
1287 SrcElTy->isArrayTy()) {
1288 // Check that changing to the array element type amounts to dividing the
1289 // index by a scale factor.
1290 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1291 uint64_t ArrayEltSize =
1292 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
1293 if (ResSize && ArrayEltSize % ResSize == 0) {
1294 Value *Idx = GEP.getOperand(1);
1295 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1296 uint64_t Scale = ArrayEltSize / ResSize;
1298 // Earlier transforms ensure that the index has type IntPtrType, which
1299 // considerably simplifies the logic by eliminating implicit casts.
1300 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1301 "Index not cast to pointer width?");
1304 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1305 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1306 // If the multiplication NewIdx * Scale may overflow then the new
1307 // GEP may not be "inbounds".
1309 Off[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1311 Value *NewGEP = GEP.isInBounds() && NSW ?
1312 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1313 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1314 // The NewGEP must be pointer typed, so must the old one -> BitCast
1315 return new BitCastInst(NewGEP, GEP.getType());
1322 /// See if we can simplify:
1323 /// X = bitcast A* to B*
1324 /// Y = gep X, <...constant indices...>
1325 /// into a gep of the original struct. This is important for SROA and alias
1326 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1327 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1328 APInt Offset(TD ? TD->getPointerSizeInBits() : 1, 0);
1330 !isa<BitCastInst>(BCI->getOperand(0)) &&
1331 GEP.accumulateConstantOffset(*TD, Offset) &&
1332 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1334 // If this GEP instruction doesn't move the pointer, just replace the GEP
1335 // with a bitcast of the real input to the dest type.
1337 // If the bitcast is of an allocation, and the allocation will be
1338 // converted to match the type of the cast, don't touch this.
1339 if (isa<AllocaInst>(BCI->getOperand(0)) ||
1340 isAllocationFn(BCI->getOperand(0), TLI)) {
1341 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1342 if (Instruction *I = visitBitCast(*BCI)) {
1345 BCI->getParent()->getInstList().insert(BCI, I);
1346 ReplaceInstUsesWith(*BCI, I);
1351 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1354 // Otherwise, if the offset is non-zero, we need to find out if there is a
1355 // field at Offset in 'A's type. If so, we can pull the cast through the
1357 SmallVector<Value*, 8> NewIndices;
1359 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1360 if (FindElementAtOffset(InTy, Offset.getSExtValue(), NewIndices)) {
1361 Value *NGEP = GEP.isInBounds() ?
1362 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1363 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1365 if (NGEP->getType() == GEP.getType())
1366 return ReplaceInstUsesWith(GEP, NGEP);
1367 NGEP->takeName(&GEP);
1368 return new BitCastInst(NGEP, GEP.getType());
1379 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1380 const TargetLibraryInfo *TLI) {
1381 SmallVector<Instruction*, 4> Worklist;
1382 Worklist.push_back(AI);
1385 Instruction *PI = Worklist.pop_back_val();
1386 for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end(); UI != UE;
1388 Instruction *I = cast<Instruction>(*UI);
1389 switch (I->getOpcode()) {
1391 // Give up the moment we see something we can't handle.
1394 case Instruction::BitCast:
1395 case Instruction::GetElementPtr:
1397 Worklist.push_back(I);
1400 case Instruction::ICmp: {
1401 ICmpInst *ICI = cast<ICmpInst>(I);
1402 // We can fold eq/ne comparisons with null to false/true, respectively.
1403 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1409 case Instruction::Call:
1410 // Ignore no-op and store intrinsics.
1411 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1412 switch (II->getIntrinsicID()) {
1416 case Intrinsic::memmove:
1417 case Intrinsic::memcpy:
1418 case Intrinsic::memset: {
1419 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1420 if (MI->isVolatile() || MI->getRawDest() != PI)
1424 case Intrinsic::dbg_declare:
1425 case Intrinsic::dbg_value:
1426 case Intrinsic::invariant_start:
1427 case Intrinsic::invariant_end:
1428 case Intrinsic::lifetime_start:
1429 case Intrinsic::lifetime_end:
1430 case Intrinsic::objectsize:
1436 if (isFreeCall(I, TLI)) {
1442 case Instruction::Store: {
1443 StoreInst *SI = cast<StoreInst>(I);
1444 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1450 llvm_unreachable("missing a return?");
1452 } while (!Worklist.empty());
1456 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1457 // If we have a malloc call which is only used in any amount of comparisons
1458 // to null and free calls, delete the calls and replace the comparisons with
1459 // true or false as appropriate.
1460 SmallVector<WeakVH, 64> Users;
1461 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1462 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1463 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1466 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1467 ReplaceInstUsesWith(*C,
1468 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1469 C->isFalseWhenEqual()));
1470 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1471 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1472 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1473 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1474 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1475 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1476 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1479 EraseInstFromFunction(*I);
1482 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1483 // Replace invoke with a NOP intrinsic to maintain the original CFG
1484 Module *M = II->getParent()->getParent()->getParent();
1485 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1486 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1487 ArrayRef<Value *>(), "", II->getParent());
1489 return EraseInstFromFunction(MI);
1494 /// \brief Move the call to free before a NULL test.
1496 /// Check if this free is accessed after its argument has been test
1497 /// against NULL (property 0).
1498 /// If yes, it is legal to move this call in its predecessor block.
1500 /// The move is performed only if the block containing the call to free
1501 /// will be removed, i.e.:
1502 /// 1. it has only one predecessor P, and P has two successors
1503 /// 2. it contains the call and an unconditional branch
1504 /// 3. its successor is the same as its predecessor's successor
1506 /// The profitability is out-of concern here and this function should
1507 /// be called only if the caller knows this transformation would be
1508 /// profitable (e.g., for code size).
1509 static Instruction *
1510 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1511 Value *Op = FI.getArgOperand(0);
1512 BasicBlock *FreeInstrBB = FI.getParent();
1513 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1515 // Validate part of constraint #1: Only one predecessor
1516 // FIXME: We can extend the number of predecessor, but in that case, we
1517 // would duplicate the call to free in each predecessor and it may
1518 // not be profitable even for code size.
1522 // Validate constraint #2: Does this block contains only the call to
1523 // free and an unconditional branch?
1524 // FIXME: We could check if we can speculate everything in the
1525 // predecessor block
1526 if (FreeInstrBB->size() != 2)
1529 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1532 // Validate the rest of constraint #1 by matching on the pred branch.
1533 TerminatorInst *TI = PredBB->getTerminator();
1534 BasicBlock *TrueBB, *FalseBB;
1535 ICmpInst::Predicate Pred;
1536 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1538 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1541 // Validate constraint #3: Ensure the null case just falls through.
1542 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1544 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1545 "Broken CFG: missing edge from predecessor to successor");
1552 Instruction *InstCombiner::visitFree(CallInst &FI) {
1553 Value *Op = FI.getArgOperand(0);
1555 // free undef -> unreachable.
1556 if (isa<UndefValue>(Op)) {
1557 // Insert a new store to null because we cannot modify the CFG here.
1558 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1559 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1560 return EraseInstFromFunction(FI);
1563 // If we have 'free null' delete the instruction. This can happen in stl code
1564 // when lots of inlining happens.
1565 if (isa<ConstantPointerNull>(Op))
1566 return EraseInstFromFunction(FI);
1568 // If we optimize for code size, try to move the call to free before the null
1569 // test so that simplify cfg can remove the empty block and dead code
1570 // elimination the branch. I.e., helps to turn something like:
1571 // if (foo) free(foo);
1575 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1583 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1584 // Change br (not X), label True, label False to: br X, label False, True
1586 BasicBlock *TrueDest;
1587 BasicBlock *FalseDest;
1588 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1589 !isa<Constant>(X)) {
1590 // Swap Destinations and condition...
1592 BI.swapSuccessors();
1596 // Cannonicalize fcmp_one -> fcmp_oeq
1597 FCmpInst::Predicate FPred; Value *Y;
1598 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1599 TrueDest, FalseDest)) &&
1600 BI.getCondition()->hasOneUse())
1601 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1602 FPred == FCmpInst::FCMP_OGE) {
1603 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1604 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1606 // Swap Destinations and condition.
1607 BI.swapSuccessors();
1612 // Cannonicalize icmp_ne -> icmp_eq
1613 ICmpInst::Predicate IPred;
1614 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1615 TrueDest, FalseDest)) &&
1616 BI.getCondition()->hasOneUse())
1617 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1618 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1619 IPred == ICmpInst::ICMP_SGE) {
1620 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1621 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1622 // Swap Destinations and condition.
1623 BI.swapSuccessors();
1631 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1632 Value *Cond = SI.getCondition();
1633 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1634 if (I->getOpcode() == Instruction::Add)
1635 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1636 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1637 // Skip the first item since that's the default case.
1638 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1640 ConstantInt* CaseVal = i.getCaseValue();
1641 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1643 assert(isa<ConstantInt>(NewCaseVal) &&
1644 "Result of expression should be constant");
1645 i.setValue(cast<ConstantInt>(NewCaseVal));
1647 SI.setCondition(I->getOperand(0));
1655 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1656 Value *Agg = EV.getAggregateOperand();
1658 if (!EV.hasIndices())
1659 return ReplaceInstUsesWith(EV, Agg);
1661 if (Constant *C = dyn_cast<Constant>(Agg)) {
1662 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1663 if (EV.getNumIndices() == 0)
1664 return ReplaceInstUsesWith(EV, C2);
1665 // Extract the remaining indices out of the constant indexed by the
1667 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
1669 return 0; // Can't handle other constants
1672 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1673 // We're extracting from an insertvalue instruction, compare the indices
1674 const unsigned *exti, *exte, *insi, *inse;
1675 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1676 exte = EV.idx_end(), inse = IV->idx_end();
1677 exti != exte && insi != inse;
1680 // The insert and extract both reference distinctly different elements.
1681 // This means the extract is not influenced by the insert, and we can
1682 // replace the aggregate operand of the extract with the aggregate
1683 // operand of the insert. i.e., replace
1684 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1685 // %E = extractvalue { i32, { i32 } } %I, 0
1687 // %E = extractvalue { i32, { i32 } } %A, 0
1688 return ExtractValueInst::Create(IV->getAggregateOperand(),
1691 if (exti == exte && insi == inse)
1692 // Both iterators are at the end: Index lists are identical. Replace
1693 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1694 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1696 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1698 // The extract list is a prefix of the insert list. i.e. replace
1699 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1700 // %E = extractvalue { i32, { i32 } } %I, 1
1702 // %X = extractvalue { i32, { i32 } } %A, 1
1703 // %E = insertvalue { i32 } %X, i32 42, 0
1704 // by switching the order of the insert and extract (though the
1705 // insertvalue should be left in, since it may have other uses).
1706 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1708 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1709 makeArrayRef(insi, inse));
1712 // The insert list is a prefix of the extract list
1713 // We can simply remove the common indices from the extract and make it
1714 // operate on the inserted value instead of the insertvalue result.
1716 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1717 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1719 // %E extractvalue { i32 } { i32 42 }, 0
1720 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1721 makeArrayRef(exti, exte));
1723 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1724 // We're extracting from an intrinsic, see if we're the only user, which
1725 // allows us to simplify multiple result intrinsics to simpler things that
1726 // just get one value.
1727 if (II->hasOneUse()) {
1728 // Check if we're grabbing the overflow bit or the result of a 'with
1729 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1730 // and replace it with a traditional binary instruction.
1731 switch (II->getIntrinsicID()) {
1732 case Intrinsic::uadd_with_overflow:
1733 case Intrinsic::sadd_with_overflow:
1734 if (*EV.idx_begin() == 0) { // Normal result.
1735 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1736 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1737 EraseInstFromFunction(*II);
1738 return BinaryOperator::CreateAdd(LHS, RHS);
1741 // If the normal result of the add is dead, and the RHS is a constant,
1742 // we can transform this into a range comparison.
1743 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1744 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1745 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1746 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1747 ConstantExpr::getNot(CI));
1749 case Intrinsic::usub_with_overflow:
1750 case Intrinsic::ssub_with_overflow:
1751 if (*EV.idx_begin() == 0) { // Normal result.
1752 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1753 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1754 EraseInstFromFunction(*II);
1755 return BinaryOperator::CreateSub(LHS, RHS);
1758 case Intrinsic::umul_with_overflow:
1759 case Intrinsic::smul_with_overflow:
1760 if (*EV.idx_begin() == 0) { // Normal result.
1761 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1762 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1763 EraseInstFromFunction(*II);
1764 return BinaryOperator::CreateMul(LHS, RHS);
1772 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1773 // If the (non-volatile) load only has one use, we can rewrite this to a
1774 // load from a GEP. This reduces the size of the load.
1775 // FIXME: If a load is used only by extractvalue instructions then this
1776 // could be done regardless of having multiple uses.
1777 if (L->isSimple() && L->hasOneUse()) {
1778 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1779 SmallVector<Value*, 4> Indices;
1780 // Prefix an i32 0 since we need the first element.
1781 Indices.push_back(Builder->getInt32(0));
1782 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1784 Indices.push_back(Builder->getInt32(*I));
1786 // We need to insert these at the location of the old load, not at that of
1787 // the extractvalue.
1788 Builder->SetInsertPoint(L->getParent(), L);
1789 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1790 // Returning the load directly will cause the main loop to insert it in
1791 // the wrong spot, so use ReplaceInstUsesWith().
1792 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1794 // We could simplify extracts from other values. Note that nested extracts may
1795 // already be simplified implicitly by the above: extract (extract (insert) )
1796 // will be translated into extract ( insert ( extract ) ) first and then just
1797 // the value inserted, if appropriate. Similarly for extracts from single-use
1798 // loads: extract (extract (load)) will be translated to extract (load (gep))
1799 // and if again single-use then via load (gep (gep)) to load (gep).
1800 // However, double extracts from e.g. function arguments or return values
1801 // aren't handled yet.
1805 enum Personality_Type {
1806 Unknown_Personality,
1807 GNU_Ada_Personality,
1808 GNU_CXX_Personality,
1809 GNU_ObjC_Personality
1812 /// RecognizePersonality - See if the given exception handling personality
1813 /// function is one that we understand. If so, return a description of it;
1814 /// otherwise return Unknown_Personality.
1815 static Personality_Type RecognizePersonality(Value *Pers) {
1816 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1818 return Unknown_Personality;
1819 return StringSwitch<Personality_Type>(F->getName())
1820 .Case("__gnat_eh_personality", GNU_Ada_Personality)
1821 .Case("__gxx_personality_v0", GNU_CXX_Personality)
1822 .Case("__objc_personality_v0", GNU_ObjC_Personality)
1823 .Default(Unknown_Personality);
1826 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
1827 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1828 switch (Personality) {
1829 case Unknown_Personality:
1831 case GNU_Ada_Personality:
1832 // While __gnat_all_others_value will match any Ada exception, it doesn't
1833 // match foreign exceptions (or didn't, before gcc-4.7).
1835 case GNU_CXX_Personality:
1836 case GNU_ObjC_Personality:
1837 return TypeInfo->isNullValue();
1839 llvm_unreachable("Unknown personality!");
1842 static bool shorter_filter(const Value *LHS, const Value *RHS) {
1844 cast<ArrayType>(LHS->getType())->getNumElements()
1846 cast<ArrayType>(RHS->getType())->getNumElements();
1849 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1850 // The logic here should be correct for any real-world personality function.
1851 // However if that turns out not to be true, the offending logic can always
1852 // be conditioned on the personality function, like the catch-all logic is.
1853 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1855 // Simplify the list of clauses, eg by removing repeated catch clauses
1856 // (these are often created by inlining).
1857 bool MakeNewInstruction = false; // If true, recreate using the following:
1858 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1859 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
1861 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1862 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1863 bool isLastClause = i + 1 == e;
1864 if (LI.isCatch(i)) {
1866 Value *CatchClause = LI.getClause(i);
1867 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1869 // If we already saw this clause, there is no point in having a second
1871 if (AlreadyCaught.insert(TypeInfo)) {
1872 // This catch clause was not already seen.
1873 NewClauses.push_back(CatchClause);
1875 // Repeated catch clause - drop the redundant copy.
1876 MakeNewInstruction = true;
1879 // If this is a catch-all then there is no point in keeping any following
1880 // clauses or marking the landingpad as having a cleanup.
1881 if (isCatchAll(Personality, TypeInfo)) {
1883 MakeNewInstruction = true;
1884 CleanupFlag = false;
1888 // A filter clause. If any of the filter elements were already caught
1889 // then they can be dropped from the filter. It is tempting to try to
1890 // exploit the filter further by saying that any typeinfo that does not
1891 // occur in the filter can't be caught later (and thus can be dropped).
1892 // However this would be wrong, since typeinfos can match without being
1893 // equal (for example if one represents a C++ class, and the other some
1894 // class derived from it).
1895 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1896 Value *FilterClause = LI.getClause(i);
1897 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1898 unsigned NumTypeInfos = FilterType->getNumElements();
1900 // An empty filter catches everything, so there is no point in keeping any
1901 // following clauses or marking the landingpad as having a cleanup. By
1902 // dealing with this case here the following code is made a bit simpler.
1903 if (!NumTypeInfos) {
1904 NewClauses.push_back(FilterClause);
1906 MakeNewInstruction = true;
1907 CleanupFlag = false;
1911 bool MakeNewFilter = false; // If true, make a new filter.
1912 SmallVector<Constant *, 16> NewFilterElts; // New elements.
1913 if (isa<ConstantAggregateZero>(FilterClause)) {
1914 // Not an empty filter - it contains at least one null typeinfo.
1915 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1916 Constant *TypeInfo =
1917 Constant::getNullValue(FilterType->getElementType());
1918 // If this typeinfo is a catch-all then the filter can never match.
1919 if (isCatchAll(Personality, TypeInfo)) {
1920 // Throw the filter away.
1921 MakeNewInstruction = true;
1925 // There is no point in having multiple copies of this typeinfo, so
1926 // discard all but the first copy if there is more than one.
1927 NewFilterElts.push_back(TypeInfo);
1928 if (NumTypeInfos > 1)
1929 MakeNewFilter = true;
1931 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1932 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1933 NewFilterElts.reserve(NumTypeInfos);
1935 // Remove any filter elements that were already caught or that already
1936 // occurred in the filter. While there, see if any of the elements are
1937 // catch-alls. If so, the filter can be discarded.
1938 bool SawCatchAll = false;
1939 for (unsigned j = 0; j != NumTypeInfos; ++j) {
1940 Value *Elt = Filter->getOperand(j);
1941 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1942 if (isCatchAll(Personality, TypeInfo)) {
1943 // This element is a catch-all. Bail out, noting this fact.
1947 if (AlreadyCaught.count(TypeInfo))
1948 // Already caught by an earlier clause, so having it in the filter
1951 // There is no point in having multiple copies of the same typeinfo in
1952 // a filter, so only add it if we didn't already.
1953 if (SeenInFilter.insert(TypeInfo))
1954 NewFilterElts.push_back(cast<Constant>(Elt));
1956 // A filter containing a catch-all cannot match anything by definition.
1958 // Throw the filter away.
1959 MakeNewInstruction = true;
1963 // If we dropped something from the filter, make a new one.
1964 if (NewFilterElts.size() < NumTypeInfos)
1965 MakeNewFilter = true;
1967 if (MakeNewFilter) {
1968 FilterType = ArrayType::get(FilterType->getElementType(),
1969 NewFilterElts.size());
1970 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1971 MakeNewInstruction = true;
1974 NewClauses.push_back(FilterClause);
1976 // If the new filter is empty then it will catch everything so there is
1977 // no point in keeping any following clauses or marking the landingpad
1978 // as having a cleanup. The case of the original filter being empty was
1979 // already handled above.
1980 if (MakeNewFilter && !NewFilterElts.size()) {
1981 assert(MakeNewInstruction && "New filter but not a new instruction!");
1982 CleanupFlag = false;
1988 // If several filters occur in a row then reorder them so that the shortest
1989 // filters come first (those with the smallest number of elements). This is
1990 // advantageous because shorter filters are more likely to match, speeding up
1991 // unwinding, but mostly because it increases the effectiveness of the other
1992 // filter optimizations below.
1993 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1995 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1996 for (j = i; j != e; ++j)
1997 if (!isa<ArrayType>(NewClauses[j]->getType()))
2000 // Check whether the filters are already sorted by length. We need to know
2001 // if sorting them is actually going to do anything so that we only make a
2002 // new landingpad instruction if it does.
2003 for (unsigned k = i; k + 1 < j; ++k)
2004 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2005 // Not sorted, so sort the filters now. Doing an unstable sort would be
2006 // correct too but reordering filters pointlessly might confuse users.
2007 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2009 MakeNewInstruction = true;
2013 // Look for the next batch of filters.
2017 // If typeinfos matched if and only if equal, then the elements of a filter L
2018 // that occurs later than a filter F could be replaced by the intersection of
2019 // the elements of F and L. In reality two typeinfos can match without being
2020 // equal (for example if one represents a C++ class, and the other some class
2021 // derived from it) so it would be wrong to perform this transform in general.
2022 // However the transform is correct and useful if F is a subset of L. In that
2023 // case L can be replaced by F, and thus removed altogether since repeating a
2024 // filter is pointless. So here we look at all pairs of filters F and L where
2025 // L follows F in the list of clauses, and remove L if every element of F is
2026 // an element of L. This can occur when inlining C++ functions with exception
2028 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2029 // Examine each filter in turn.
2030 Value *Filter = NewClauses[i];
2031 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2033 // Not a filter - skip it.
2035 unsigned FElts = FTy->getNumElements();
2036 // Examine each filter following this one. Doing this backwards means that
2037 // we don't have to worry about filters disappearing under us when removed.
2038 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2039 Value *LFilter = NewClauses[j];
2040 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2042 // Not a filter - skip it.
2044 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2045 // an element of LFilter, then discard LFilter.
2046 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
2047 // If Filter is empty then it is a subset of LFilter.
2050 NewClauses.erase(J);
2051 MakeNewInstruction = true;
2052 // Move on to the next filter.
2055 unsigned LElts = LTy->getNumElements();
2056 // If Filter is longer than LFilter then it cannot be a subset of it.
2058 // Move on to the next filter.
2060 // At this point we know that LFilter has at least one element.
2061 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2062 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2063 // already know that Filter is not longer than LFilter).
2064 if (isa<ConstantAggregateZero>(Filter)) {
2065 assert(FElts <= LElts && "Should have handled this case earlier!");
2067 NewClauses.erase(J);
2068 MakeNewInstruction = true;
2070 // Move on to the next filter.
2073 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2074 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2075 // Since Filter is non-empty and contains only zeros, it is a subset of
2076 // LFilter iff LFilter contains a zero.
2077 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2078 for (unsigned l = 0; l != LElts; ++l)
2079 if (LArray->getOperand(l)->isNullValue()) {
2080 // LFilter contains a zero - discard it.
2081 NewClauses.erase(J);
2082 MakeNewInstruction = true;
2085 // Move on to the next filter.
2088 // At this point we know that both filters are ConstantArrays. Loop over
2089 // operands to see whether every element of Filter is also an element of
2090 // LFilter. Since filters tend to be short this is probably faster than
2091 // using a method that scales nicely.
2092 ConstantArray *FArray = cast<ConstantArray>(Filter);
2093 bool AllFound = true;
2094 for (unsigned f = 0; f != FElts; ++f) {
2095 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2097 for (unsigned l = 0; l != LElts; ++l) {
2098 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2099 if (LTypeInfo == FTypeInfo) {
2109 NewClauses.erase(J);
2110 MakeNewInstruction = true;
2112 // Move on to the next filter.
2116 // If we changed any of the clauses, replace the old landingpad instruction
2118 if (MakeNewInstruction) {
2119 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2120 LI.getPersonalityFn(),
2122 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2123 NLI->addClause(NewClauses[i]);
2124 // A landing pad with no clauses must have the cleanup flag set. It is
2125 // theoretically possible, though highly unlikely, that we eliminated all
2126 // clauses. If so, force the cleanup flag to true.
2127 if (NewClauses.empty())
2129 NLI->setCleanup(CleanupFlag);
2133 // Even if none of the clauses changed, we may nonetheless have understood
2134 // that the cleanup flag is pointless. Clear it if so.
2135 if (LI.isCleanup() != CleanupFlag) {
2136 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2137 LI.setCleanup(CleanupFlag);
2147 /// TryToSinkInstruction - Try to move the specified instruction from its
2148 /// current block into the beginning of DestBlock, which can only happen if it's
2149 /// safe to move the instruction past all of the instructions between it and the
2150 /// end of its block.
2151 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2152 assert(I->hasOneUse() && "Invariants didn't hold!");
2154 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2155 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2156 isa<TerminatorInst>(I))
2159 // Do not sink alloca instructions out of the entry block.
2160 if (isa<AllocaInst>(I) && I->getParent() ==
2161 &DestBlock->getParent()->getEntryBlock())
2164 // We can only sink load instructions if there is nothing between the load and
2165 // the end of block that could change the value.
2166 if (I->mayReadFromMemory()) {
2167 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2169 if (Scan->mayWriteToMemory())
2173 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2174 I->moveBefore(InsertPos);
2180 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2181 /// all reachable code to the worklist.
2183 /// This has a couple of tricks to make the code faster and more powerful. In
2184 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2185 /// them to the worklist (this significantly speeds up instcombine on code where
2186 /// many instructions are dead or constant). Additionally, if we find a branch
2187 /// whose condition is a known constant, we only visit the reachable successors.
2189 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2190 SmallPtrSet<BasicBlock*, 64> &Visited,
2192 const DataLayout *TD,
2193 const TargetLibraryInfo *TLI) {
2194 bool MadeIRChange = false;
2195 SmallVector<BasicBlock*, 256> Worklist;
2196 Worklist.push_back(BB);
2198 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2199 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2202 BB = Worklist.pop_back_val();
2204 // We have now visited this block! If we've already been here, ignore it.
2205 if (!Visited.insert(BB)) continue;
2207 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2208 Instruction *Inst = BBI++;
2210 // DCE instruction if trivially dead.
2211 if (isInstructionTriviallyDead(Inst, TLI)) {
2213 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
2214 Inst->eraseFromParent();
2218 // ConstantProp instruction if trivially constant.
2219 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2220 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
2221 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
2223 Inst->replaceAllUsesWith(C);
2225 Inst->eraseFromParent();
2230 // See if we can constant fold its operands.
2231 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2233 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2234 if (CE == 0) continue;
2236 Constant*& FoldRes = FoldedConstants[CE];
2238 FoldRes = ConstantFoldConstantExpression(CE, TD, TLI);
2242 if (FoldRes != CE) {
2244 MadeIRChange = true;
2249 InstrsForInstCombineWorklist.push_back(Inst);
2252 // Recursively visit successors. If this is a branch or switch on a
2253 // constant, only visit the reachable successor.
2254 TerminatorInst *TI = BB->getTerminator();
2255 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2256 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2257 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2258 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2259 Worklist.push_back(ReachableBB);
2262 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2263 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2264 // See if this is an explicit destination.
2265 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2267 if (i.getCaseValue() == Cond) {
2268 BasicBlock *ReachableBB = i.getCaseSuccessor();
2269 Worklist.push_back(ReachableBB);
2273 // Otherwise it is the default destination.
2274 Worklist.push_back(SI->getDefaultDest());
2279 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2280 Worklist.push_back(TI->getSuccessor(i));
2281 } while (!Worklist.empty());
2283 // Once we've found all of the instructions to add to instcombine's worklist,
2284 // add them in reverse order. This way instcombine will visit from the top
2285 // of the function down. This jives well with the way that it adds all uses
2286 // of instructions to the worklist after doing a transformation, thus avoiding
2287 // some N^2 behavior in pathological cases.
2288 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2289 InstrsForInstCombineWorklist.size());
2291 return MadeIRChange;
2294 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2295 MadeIRChange = false;
2297 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2298 << F.getName() << "\n");
2301 // Do a depth-first traversal of the function, populate the worklist with
2302 // the reachable instructions. Ignore blocks that are not reachable. Keep
2303 // track of which blocks we visit.
2304 SmallPtrSet<BasicBlock*, 64> Visited;
2305 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
2308 // Do a quick scan over the function. If we find any blocks that are
2309 // unreachable, remove any instructions inside of them. This prevents
2310 // the instcombine code from having to deal with some bad special cases.
2311 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2312 if (Visited.count(BB)) continue;
2314 // Delete the instructions backwards, as it has a reduced likelihood of
2315 // having to update as many def-use and use-def chains.
2316 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2317 while (EndInst != BB->begin()) {
2318 // Delete the next to last instruction.
2319 BasicBlock::iterator I = EndInst;
2320 Instruction *Inst = --I;
2321 if (!Inst->use_empty())
2322 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2323 if (isa<LandingPadInst>(Inst)) {
2327 if (!isa<DbgInfoIntrinsic>(Inst)) {
2329 MadeIRChange = true;
2331 Inst->eraseFromParent();
2336 while (!Worklist.isEmpty()) {
2337 Instruction *I = Worklist.RemoveOne();
2338 if (I == 0) continue; // skip null values.
2340 // Check to see if we can DCE the instruction.
2341 if (isInstructionTriviallyDead(I, TLI)) {
2342 DEBUG(errs() << "IC: DCE: " << *I << '\n');
2343 EraseInstFromFunction(*I);
2345 MadeIRChange = true;
2349 // Instruction isn't dead, see if we can constant propagate it.
2350 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2351 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
2352 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2354 // Add operands to the worklist.
2355 ReplaceInstUsesWith(*I, C);
2357 EraseInstFromFunction(*I);
2358 MadeIRChange = true;
2362 // See if we can trivially sink this instruction to a successor basic block.
2363 if (I->hasOneUse()) {
2364 BasicBlock *BB = I->getParent();
2365 Instruction *UserInst = cast<Instruction>(I->use_back());
2366 BasicBlock *UserParent;
2368 // Get the block the use occurs in.
2369 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2370 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
2372 UserParent = UserInst->getParent();
2374 if (UserParent != BB) {
2375 bool UserIsSuccessor = false;
2376 // See if the user is one of our successors.
2377 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2378 if (*SI == UserParent) {
2379 UserIsSuccessor = true;
2383 // If the user is one of our immediate successors, and if that successor
2384 // only has us as a predecessors (we'd have to split the critical edge
2385 // otherwise), we can keep going.
2386 if (UserIsSuccessor && UserParent->getSinglePredecessor())
2387 // Okay, the CFG is simple enough, try to sink this instruction.
2388 MadeIRChange |= TryToSinkInstruction(I, UserParent);
2392 // Now that we have an instruction, try combining it to simplify it.
2393 Builder->SetInsertPoint(I->getParent(), I);
2394 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2399 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2400 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2402 if (Instruction *Result = visit(*I)) {
2404 // Should we replace the old instruction with a new one?
2406 DEBUG(errs() << "IC: Old = " << *I << '\n'
2407 << " New = " << *Result << '\n');
2409 if (!I->getDebugLoc().isUnknown())
2410 Result->setDebugLoc(I->getDebugLoc());
2411 // Everything uses the new instruction now.
2412 I->replaceAllUsesWith(Result);
2414 // Move the name to the new instruction first.
2415 Result->takeName(I);
2417 // Push the new instruction and any users onto the worklist.
2418 Worklist.Add(Result);
2419 Worklist.AddUsersToWorkList(*Result);
2421 // Insert the new instruction into the basic block...
2422 BasicBlock *InstParent = I->getParent();
2423 BasicBlock::iterator InsertPos = I;
2425 // If we replace a PHI with something that isn't a PHI, fix up the
2427 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2428 InsertPos = InstParent->getFirstInsertionPt();
2430 InstParent->getInstList().insert(InsertPos, Result);
2432 EraseInstFromFunction(*I);
2435 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2436 << " New = " << *I << '\n');
2439 // If the instruction was modified, it's possible that it is now dead.
2440 // if so, remove it.
2441 if (isInstructionTriviallyDead(I, TLI)) {
2442 EraseInstFromFunction(*I);
2445 Worklist.AddUsersToWorkList(*I);
2448 MadeIRChange = true;
2453 return MadeIRChange;
2457 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
2460 InstCombinerLibCallSimplifier(const DataLayout *TD,
2461 const TargetLibraryInfo *TLI,
2463 : LibCallSimplifier(TD, TLI, UnsafeFPShrink) {
2467 /// replaceAllUsesWith - override so that instruction replacement
2468 /// can be defined in terms of the instruction combiner framework.
2469 virtual void replaceAllUsesWith(Instruction *I, Value *With) const {
2470 IC->ReplaceInstUsesWith(*I, With);
2475 bool InstCombiner::runOnFunction(Function &F) {
2476 TD = getAnalysisIfAvailable<DataLayout>();
2477 TLI = &getAnalysis<TargetLibraryInfo>();
2479 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2480 Attribute::MinSize);
2482 /// Builder - This is an IRBuilder that automatically inserts new
2483 /// instructions into the worklist when they are created.
2484 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2485 TheBuilder(F.getContext(), TargetFolder(TD),
2486 InstCombineIRInserter(Worklist));
2487 Builder = &TheBuilder;
2489 InstCombinerLibCallSimplifier TheSimplifier(TD, TLI, this);
2490 Simplifier = &TheSimplifier;
2492 bool EverMadeChange = false;
2494 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2496 EverMadeChange = LowerDbgDeclare(F);
2498 // Iterate while there is work to do.
2499 unsigned Iteration = 0;
2500 while (DoOneIteration(F, Iteration++))
2501 EverMadeChange = true;
2504 return EverMadeChange;
2507 FunctionPass *llvm::createInstructionCombiningPass() {
2508 return new InstCombiner();