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/IntrinsicInst.h"
40 #include "llvm/Analysis/ConstantFolding.h"
41 #include "llvm/Analysis/InstructionSimplify.h"
42 #include "llvm/Analysis/MemoryBuiltins.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/PatternMatch.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm-c/Initialization.h"
55 using namespace llvm::PatternMatch;
57 STATISTIC(NumCombined , "Number of insts combined");
58 STATISTIC(NumConstProp, "Number of constant folds");
59 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
60 STATISTIC(NumSunkInst , "Number of instructions sunk");
61 STATISTIC(NumExpand, "Number of expansions");
62 STATISTIC(NumFactor , "Number of factorizations");
63 STATISTIC(NumReassoc , "Number of reassociations");
65 // Initialization Routines
66 void llvm::initializeInstCombine(PassRegistry &Registry) {
67 initializeInstCombinerPass(Registry);
70 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
71 initializeInstCombine(*unwrap(R));
74 char InstCombiner::ID = 0;
75 INITIALIZE_PASS(InstCombiner, "instcombine",
76 "Combine redundant instructions", false, false)
78 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addPreservedID(LCSSAID);
84 /// ShouldChangeType - Return true if it is desirable to convert a computation
85 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
86 /// type for example, or from a smaller to a larger illegal type.
87 bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
88 assert(From->isIntegerTy() && To->isIntegerTy());
90 // If we don't have TD, we don't know if the source/dest are legal.
91 if (!TD) return false;
93 unsigned FromWidth = From->getPrimitiveSizeInBits();
94 unsigned ToWidth = To->getPrimitiveSizeInBits();
95 bool FromLegal = TD->isLegalInteger(FromWidth);
96 bool ToLegal = TD->isLegalInteger(ToWidth);
98 // If this is a legal integer from type, and the result would be an illegal
99 // type, don't do the transformation.
100 if (FromLegal && !ToLegal)
103 // Otherwise, if both are illegal, do not increase the size of the result. We
104 // do allow things like i160 -> i64, but not i64 -> i160.
105 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
112 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
113 /// operators which are associative or commutative:
115 // Commutative operators:
117 // 1. Order operands such that they are listed from right (least complex) to
118 // left (most complex). This puts constants before unary operators before
121 // Associative operators:
123 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
124 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
126 // Associative and commutative operators:
128 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
129 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
130 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
131 // if C1 and C2 are constants.
133 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
134 Instruction::BinaryOps Opcode = I.getOpcode();
135 bool Changed = false;
138 // Order operands such that they are listed from right (least complex) to
139 // left (most complex). This puts constants before unary operators before
141 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
142 getComplexity(I.getOperand(1)))
143 Changed = !I.swapOperands();
145 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
146 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
148 if (I.isAssociative()) {
149 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
150 if (Op0 && Op0->getOpcode() == Opcode) {
151 Value *A = Op0->getOperand(0);
152 Value *B = Op0->getOperand(1);
153 Value *C = I.getOperand(1);
155 // Does "B op C" simplify?
156 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
157 // It simplifies to V. Form "A op V".
166 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
167 if (Op1 && Op1->getOpcode() == Opcode) {
168 Value *A = I.getOperand(0);
169 Value *B = Op1->getOperand(0);
170 Value *C = Op1->getOperand(1);
172 // Does "A op B" simplify?
173 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
174 // It simplifies to V. Form "V op C".
184 if (I.isAssociative() && I.isCommutative()) {
185 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
186 if (Op0 && Op0->getOpcode() == Opcode) {
187 Value *A = Op0->getOperand(0);
188 Value *B = Op0->getOperand(1);
189 Value *C = I.getOperand(1);
191 // Does "C op A" simplify?
192 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
193 // It simplifies to V. Form "V op B".
202 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
203 if (Op1 && Op1->getOpcode() == Opcode) {
204 Value *A = I.getOperand(0);
205 Value *B = Op1->getOperand(0);
206 Value *C = Op1->getOperand(1);
208 // Does "C op A" simplify?
209 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
210 // It simplifies to V. Form "B op V".
219 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
220 // if C1 and C2 are constants.
222 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
223 isa<Constant>(Op0->getOperand(1)) &&
224 isa<Constant>(Op1->getOperand(1)) &&
225 Op0->hasOneUse() && Op1->hasOneUse()) {
226 Value *A = Op0->getOperand(0);
227 Constant *C1 = cast<Constant>(Op0->getOperand(1));
228 Value *B = Op1->getOperand(0);
229 Constant *C2 = cast<Constant>(Op1->getOperand(1));
231 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
232 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
235 I.setOperand(0, New);
236 I.setOperand(1, Folded);
242 // No further simplifications.
247 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
248 /// "(X LOp Y) ROp (X LOp Z)".
249 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
250 Instruction::BinaryOps ROp) {
255 case Instruction::And:
256 // And distributes over Or and Xor.
260 case Instruction::Or:
261 case Instruction::Xor:
265 case Instruction::Mul:
266 // Multiplication distributes over addition and subtraction.
270 case Instruction::Add:
271 case Instruction::Sub:
275 case Instruction::Or:
276 // Or distributes over And.
280 case Instruction::And:
286 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
287 /// "(X ROp Z) LOp (Y ROp Z)".
288 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
289 Instruction::BinaryOps ROp) {
290 if (Instruction::isCommutative(ROp))
291 return LeftDistributesOverRight(ROp, LOp);
292 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
293 // but this requires knowing that the addition does not overflow and other
298 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
299 /// which some other binary operation distributes over either by factorizing
300 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
301 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
302 /// a win). Returns the simplified value, or null if it didn't simplify.
303 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
304 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
305 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
306 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
307 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
310 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
311 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
313 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
314 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
315 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
317 // Does "X op' Y" always equal "Y op' X"?
318 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
320 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
321 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
322 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
323 // commutative case, "(A op' B) op (C op' A)"?
324 if (A == C || (InnerCommutative && A == D)) {
327 // Consider forming "A op' (B op D)".
328 // If "B op D" simplifies then it can be formed with no cost.
329 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
330 // If "B op D" doesn't simplify then only go on if both of the existing
331 // operations "A op' B" and "C op' D" will be zapped as no longer used.
332 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
333 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
336 V = Builder->CreateBinOp(InnerOpcode, A, V);
342 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
343 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
344 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
345 // commutative case, "(A op' B) op (B op' D)"?
346 if (B == D || (InnerCommutative && B == C)) {
349 // Consider forming "(A op C) op' B".
350 // If "A op C" simplifies then it can be formed with no cost.
351 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
352 // If "A op C" doesn't simplify then only go on if both of the existing
353 // operations "A op' B" and "C op' D" will be zapped as no longer used.
354 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
355 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
358 V = Builder->CreateBinOp(InnerOpcode, V, B);
366 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
367 // The instruction has the form "(A op' B) op C". See if expanding it out
368 // to "(A op C) op' (B op C)" results in simplifications.
369 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
370 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
372 // Do "A op C" and "B op C" both simplify?
373 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
374 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
375 // They do! Return "L op' R".
377 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
378 if ((L == A && R == B) ||
379 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
381 // Otherwise return "L op' R" if it simplifies.
382 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
384 // Otherwise, create a new instruction.
385 C = Builder->CreateBinOp(InnerOpcode, L, R);
391 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
392 // The instruction has the form "A op (B op' C)". See if expanding it out
393 // to "(A op B) op' (A op C)" results in simplifications.
394 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
395 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
397 // Do "A op B" and "A op C" both simplify?
398 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
399 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
400 // They do! Return "L op' R".
402 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
403 if ((L == B && R == C) ||
404 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
406 // Otherwise return "L op' R" if it simplifies.
407 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
409 // Otherwise, create a new instruction.
410 A = Builder->CreateBinOp(InnerOpcode, L, R);
419 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
420 // if the LHS is a constant zero (which is the 'negate' form).
422 Value *InstCombiner::dyn_castNegVal(Value *V) const {
423 if (BinaryOperator::isNeg(V))
424 return BinaryOperator::getNegArgument(V);
426 // Constants can be considered to be negated values if they can be folded.
427 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
428 return ConstantExpr::getNeg(C);
430 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
431 if (C->getType()->getElementType()->isIntegerTy())
432 return ConstantExpr::getNeg(C);
437 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
438 // instruction if the LHS is a constant negative zero (which is the 'negate'
441 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
442 if (BinaryOperator::isFNeg(V))
443 return BinaryOperator::getFNegArgument(V);
445 // Constants can be considered to be negated values if they can be folded.
446 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
447 return ConstantExpr::getFNeg(C);
449 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
450 if (C->getType()->getElementType()->isFloatingPointTy())
451 return ConstantExpr::getFNeg(C);
456 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
458 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
459 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
462 // Figure out if the constant is the left or the right argument.
463 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
464 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
466 if (Constant *SOC = dyn_cast<Constant>(SO)) {
468 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
469 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
472 Value *Op0 = SO, *Op1 = ConstOperand;
476 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
477 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
478 SO->getName()+".op");
479 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
480 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
481 SO->getName()+".cmp");
482 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
483 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
484 SO->getName()+".cmp");
485 llvm_unreachable("Unknown binary instruction type!");
488 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
489 // constant as the other operand, try to fold the binary operator into the
490 // select arguments. This also works for Cast instructions, which obviously do
491 // not have a second operand.
492 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
493 // Don't modify shared select instructions
494 if (!SI->hasOneUse()) return 0;
495 Value *TV = SI->getOperand(1);
496 Value *FV = SI->getOperand(2);
498 if (isa<Constant>(TV) || isa<Constant>(FV)) {
499 // Bool selects with constant operands can be folded to logical ops.
500 if (SI->getType()->isIntegerTy(1)) return 0;
502 // If it's a bitcast involving vectors, make sure it has the same number of
503 // elements on both sides.
504 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
505 const VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
506 const VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
508 // Verify that either both or neither are vectors.
509 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
510 // If vectors, verify that they have the same number of elements.
511 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
515 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
516 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
518 return SelectInst::Create(SI->getCondition(),
519 SelectTrueVal, SelectFalseVal);
525 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
526 /// has a PHI node as operand #0, see if we can fold the instruction into the
527 /// PHI (which is only possible if all operands to the PHI are constants).
529 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
530 PHINode *PN = cast<PHINode>(I.getOperand(0));
531 unsigned NumPHIValues = PN->getNumIncomingValues();
532 if (NumPHIValues == 0)
535 // We normally only transform phis with a single use. However, if a PHI has
536 // multiple uses and they are all the same operation, we can fold *all* of the
537 // uses into the PHI.
538 if (!PN->hasOneUse()) {
539 // Walk the use list for the instruction, comparing them to I.
540 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
542 Instruction *User = cast<Instruction>(*UI);
543 if (User != &I && !I.isIdenticalTo(User))
546 // Otherwise, we can replace *all* users with the new PHI we form.
549 // Check to see if all of the operands of the PHI are simple constants
550 // (constantint/constantfp/undef). If there is one non-constant value,
551 // remember the BB it is in. If there is more than one or if *it* is a PHI,
552 // bail out. We don't do arbitrary constant expressions here because moving
553 // their computation can be expensive without a cost model.
554 BasicBlock *NonConstBB = 0;
555 for (unsigned i = 0; i != NumPHIValues; ++i) {
556 Value *InVal = PN->getIncomingValue(i);
557 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
560 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
561 if (NonConstBB) return 0; // More than one non-const value.
563 NonConstBB = PN->getIncomingBlock(i);
565 // If the InVal is an invoke at the end of the pred block, then we can't
566 // insert a computation after it without breaking the edge.
567 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
568 if (II->getParent() == NonConstBB)
571 // If the incoming non-constant value is in I's block, we will remove one
572 // instruction, but insert another equivalent one, leading to infinite
574 if (NonConstBB == I.getParent())
578 // If there is exactly one non-constant value, we can insert a copy of the
579 // operation in that block. However, if this is a critical edge, we would be
580 // inserting the computation one some other paths (e.g. inside a loop). Only
581 // do this if the pred block is unconditionally branching into the phi block.
582 if (NonConstBB != 0) {
583 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
584 if (!BI || !BI->isUnconditional()) return 0;
587 // Okay, we can do the transformation: create the new PHI node.
588 PHINode *NewPN = PHINode::Create(I.getType(), "");
589 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
590 InsertNewInstBefore(NewPN, *PN);
593 // If we are going to have to insert a new computation, do so right before the
594 // predecessors terminator.
596 Builder->SetInsertPoint(NonConstBB->getTerminator());
598 // Next, add all of the operands to the PHI.
599 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
600 // We only currently try to fold the condition of a select when it is a phi,
601 // not the true/false values.
602 Value *TrueV = SI->getTrueValue();
603 Value *FalseV = SI->getFalseValue();
604 BasicBlock *PhiTransBB = PN->getParent();
605 for (unsigned i = 0; i != NumPHIValues; ++i) {
606 BasicBlock *ThisBB = PN->getIncomingBlock(i);
607 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
608 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
610 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
611 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
613 InV = Builder->CreateSelect(PN->getIncomingValue(i),
614 TrueVInPred, FalseVInPred, "phitmp");
615 NewPN->addIncoming(InV, ThisBB);
617 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
618 Constant *C = cast<Constant>(I.getOperand(1));
619 for (unsigned i = 0; i != NumPHIValues; ++i) {
621 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
622 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
623 else if (isa<ICmpInst>(CI))
624 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
627 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
629 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
631 } else if (I.getNumOperands() == 2) {
632 Constant *C = cast<Constant>(I.getOperand(1));
633 for (unsigned i = 0; i != NumPHIValues; ++i) {
635 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
636 InV = ConstantExpr::get(I.getOpcode(), InC, C);
638 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
639 PN->getIncomingValue(i), C, "phitmp");
640 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
643 CastInst *CI = cast<CastInst>(&I);
644 const Type *RetTy = CI->getType();
645 for (unsigned i = 0; i != NumPHIValues; ++i) {
647 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
648 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
650 InV = Builder->CreateCast(CI->getOpcode(),
651 PN->getIncomingValue(i), I.getType(), "phitmp");
652 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
656 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
658 Instruction *User = cast<Instruction>(*UI++);
659 if (User == &I) continue;
660 ReplaceInstUsesWith(*User, NewPN);
661 EraseInstFromFunction(*User);
663 return ReplaceInstUsesWith(I, NewPN);
666 /// FindElementAtOffset - Given a type and a constant offset, determine whether
667 /// or not there is a sequence of GEP indices into the type that will land us at
668 /// the specified offset. If so, fill them into NewIndices and return the
669 /// resultant element type, otherwise return null.
670 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
671 SmallVectorImpl<Value*> &NewIndices) {
673 if (!Ty->isSized()) return 0;
675 // Start with the index over the outer type. Note that the type size
676 // might be zero (even if the offset isn't zero) if the indexed type
677 // is something like [0 x {int, int}]
678 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
679 int64_t FirstIdx = 0;
680 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
681 FirstIdx = Offset/TySize;
682 Offset -= FirstIdx*TySize;
684 // Handle hosts where % returns negative instead of values [0..TySize).
690 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
693 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
695 // Index into the types. If we fail, set OrigBase to null.
697 // Indexing into tail padding between struct/array elements.
698 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
701 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
702 const StructLayout *SL = TD->getStructLayout(STy);
703 assert(Offset < (int64_t)SL->getSizeInBytes() &&
704 "Offset must stay within the indexed type");
706 unsigned Elt = SL->getElementContainingOffset(Offset);
707 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
710 Offset -= SL->getElementOffset(Elt);
711 Ty = STy->getElementType(Elt);
712 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
713 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
714 assert(EltSize && "Cannot index into a zero-sized array");
715 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
717 Ty = AT->getElementType();
719 // Otherwise, we can't index into the middle of this atomic type, bail.
729 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
730 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
732 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
733 return ReplaceInstUsesWith(GEP, V);
735 Value *PtrOp = GEP.getOperand(0);
737 // Eliminate unneeded casts for indices, and replace indices which displace
738 // by multiples of a zero size type with zero.
740 bool MadeChange = false;
741 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
743 gep_type_iterator GTI = gep_type_begin(GEP);
744 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
745 I != E; ++I, ++GTI) {
746 // Skip indices into struct types.
747 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
748 if (!SeqTy) continue;
750 // If the element type has zero size then any index over it is equivalent
751 // to an index of zero, so replace it with zero if it is not zero already.
752 if (SeqTy->getElementType()->isSized() &&
753 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
754 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
755 *I = Constant::getNullValue(IntPtrTy);
759 if ((*I)->getType() != IntPtrTy) {
760 // If we are using a wider index than needed for this platform, shrink
761 // it to what we need. If narrower, sign-extend it to what we need.
762 // This explicit cast can make subsequent optimizations more obvious.
763 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
767 if (MadeChange) return &GEP;
770 // Combine Indices - If the source pointer to this getelementptr instruction
771 // is a getelementptr instruction, combine the indices of the two
772 // getelementptr instructions into a single instruction.
774 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
775 // Note that if our source is a gep chain itself that we wait for that
776 // chain to be resolved before we perform this transformation. This
777 // avoids us creating a TON of code in some cases.
779 if (GetElementPtrInst *SrcGEP =
780 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
781 if (SrcGEP->getNumOperands() == 2)
782 return 0; // Wait until our source is folded to completion.
784 SmallVector<Value*, 8> Indices;
786 // Find out whether the last index in the source GEP is a sequential idx.
787 bool EndsWithSequential = false;
788 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
790 EndsWithSequential = !(*I)->isStructTy();
792 // Can we combine the two pointer arithmetics offsets?
793 if (EndsWithSequential) {
794 // Replace: gep (gep %P, long B), long A, ...
795 // With: T = long A+B; gep %P, T, ...
798 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
799 Value *GO1 = GEP.getOperand(1);
800 if (SO1 == Constant::getNullValue(SO1->getType())) {
802 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
805 // If they aren't the same type, then the input hasn't been processed
806 // by the loop above yet (which canonicalizes sequential index types to
807 // intptr_t). Just avoid transforming this until the input has been
809 if (SO1->getType() != GO1->getType())
811 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
814 // Update the GEP in place if possible.
815 if (Src->getNumOperands() == 2) {
816 GEP.setOperand(0, Src->getOperand(0));
817 GEP.setOperand(1, Sum);
820 Indices.append(Src->op_begin()+1, Src->op_end()-1);
821 Indices.push_back(Sum);
822 Indices.append(GEP.op_begin()+2, GEP.op_end());
823 } else if (isa<Constant>(*GEP.idx_begin()) &&
824 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
825 Src->getNumOperands() != 1) {
826 // Otherwise we can do the fold if the first index of the GEP is a zero
827 Indices.append(Src->op_begin()+1, Src->op_end());
828 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
831 if (!Indices.empty())
832 return (GEP.isInBounds() && Src->isInBounds()) ?
833 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
834 Indices.end(), GEP.getName()) :
835 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
836 Indices.end(), GEP.getName());
839 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
840 Value *StrippedPtr = PtrOp->stripPointerCasts();
841 if (StrippedPtr != PtrOp) {
842 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
844 bool HasZeroPointerIndex = false;
845 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
846 HasZeroPointerIndex = C->isZero();
848 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
849 // into : GEP [10 x i8]* X, i32 0, ...
851 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
852 // into : GEP i8* X, ...
854 // This occurs when the program declares an array extern like "int X[];"
855 if (HasZeroPointerIndex) {
856 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
857 if (const ArrayType *CATy =
858 dyn_cast<ArrayType>(CPTy->getElementType())) {
859 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
860 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
862 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
863 GetElementPtrInst *Res =
864 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
865 Idx.end(), GEP.getName());
866 Res->setIsInBounds(GEP.isInBounds());
870 if (const ArrayType *XATy =
871 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
872 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
873 if (CATy->getElementType() == XATy->getElementType()) {
874 // -> GEP [10 x i8]* X, i32 0, ...
875 // At this point, we know that the cast source type is a pointer
876 // to an array of the same type as the destination pointer
877 // array. Because the array type is never stepped over (there
878 // is a leading zero) we can fold the cast into this GEP.
879 GEP.setOperand(0, StrippedPtr);
884 } else if (GEP.getNumOperands() == 2) {
885 // Transform things like:
886 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
887 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
888 const Type *SrcElTy = StrippedPtrTy->getElementType();
889 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
890 if (TD && SrcElTy->isArrayTy() &&
891 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
892 TD->getTypeAllocSize(ResElTy)) {
894 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
895 Idx[1] = GEP.getOperand(1);
896 Value *NewGEP = GEP.isInBounds() ?
897 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
898 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
899 // V and GEP are both pointer types --> BitCast
900 return new BitCastInst(NewGEP, GEP.getType());
903 // Transform things like:
904 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
905 // (where tmp = 8*tmp2) into:
906 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
908 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
909 uint64_t ArrayEltSize =
910 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
912 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
913 // allow either a mul, shift, or constant here.
915 ConstantInt *Scale = 0;
916 if (ArrayEltSize == 1) {
917 NewIdx = GEP.getOperand(1);
918 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
919 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
920 NewIdx = ConstantInt::get(CI->getType(), 1);
922 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
923 if (Inst->getOpcode() == Instruction::Shl &&
924 isa<ConstantInt>(Inst->getOperand(1))) {
925 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
926 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
927 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
929 NewIdx = Inst->getOperand(0);
930 } else if (Inst->getOpcode() == Instruction::Mul &&
931 isa<ConstantInt>(Inst->getOperand(1))) {
932 Scale = cast<ConstantInt>(Inst->getOperand(1));
933 NewIdx = Inst->getOperand(0);
937 // If the index will be to exactly the right offset with the scale taken
938 // out, perform the transformation. Note, we don't know whether Scale is
939 // signed or not. We'll use unsigned version of division/modulo
940 // operation after making sure Scale doesn't have the sign bit set.
941 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
942 Scale->getZExtValue() % ArrayEltSize == 0) {
943 Scale = ConstantInt::get(Scale->getType(),
944 Scale->getZExtValue() / ArrayEltSize);
945 if (Scale->getZExtValue() != 1) {
946 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
948 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
951 // Insert the new GEP instruction.
953 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
955 Value *NewGEP = GEP.isInBounds() ?
956 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
957 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
958 // The NewGEP must be pointer typed, so must the old one -> BitCast
959 return new BitCastInst(NewGEP, GEP.getType());
965 /// See if we can simplify:
966 /// X = bitcast A* to B*
967 /// Y = gep X, <...constant indices...>
968 /// into a gep of the original struct. This is important for SROA and alias
969 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
970 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
972 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
973 // Determine how much the GEP moves the pointer. We are guaranteed to get
974 // a constant back from EmitGEPOffset.
975 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
976 int64_t Offset = OffsetV->getSExtValue();
978 // If this GEP instruction doesn't move the pointer, just replace the GEP
979 // with a bitcast of the real input to the dest type.
981 // If the bitcast is of an allocation, and the allocation will be
982 // converted to match the type of the cast, don't touch this.
983 if (isa<AllocaInst>(BCI->getOperand(0)) ||
984 isMalloc(BCI->getOperand(0))) {
985 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
986 if (Instruction *I = visitBitCast(*BCI)) {
989 BCI->getParent()->getInstList().insert(BCI, I);
990 ReplaceInstUsesWith(*BCI, I);
995 return new BitCastInst(BCI->getOperand(0), GEP.getType());
998 // Otherwise, if the offset is non-zero, we need to find out if there is a
999 // field at Offset in 'A's type. If so, we can pull the cast through the
1001 SmallVector<Value*, 8> NewIndices;
1003 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1004 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
1005 Value *NGEP = GEP.isInBounds() ?
1006 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
1008 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
1011 if (NGEP->getType() == GEP.getType())
1012 return ReplaceInstUsesWith(GEP, NGEP);
1013 NGEP->takeName(&GEP);
1014 return new BitCastInst(NGEP, GEP.getType());
1024 static bool IsOnlyNullComparedAndFreed(const Value &V) {
1025 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
1027 const User *U = *UI;
1030 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
1031 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
1038 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1039 // If we have a malloc call which is only used in any amount of comparisons
1040 // to null and free calls, delete the calls and replace the comparisons with
1041 // true or false as appropriate.
1042 if (IsOnlyNullComparedAndFreed(MI)) {
1043 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
1045 // We can assume that every remaining use is a free call or an icmp eq/ne
1046 // to null, so the cast is safe.
1047 Instruction *I = cast<Instruction>(*UI);
1049 // Early increment here, as we're about to get rid of the user.
1052 if (isFreeCall(I)) {
1053 EraseInstFromFunction(*cast<CallInst>(I));
1056 // Again, the cast is safe.
1057 ICmpInst *C = cast<ICmpInst>(I);
1058 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
1059 C->isFalseWhenEqual()));
1060 EraseInstFromFunction(*C);
1062 return EraseInstFromFunction(MI);
1069 Instruction *InstCombiner::visitFree(CallInst &FI) {
1070 Value *Op = FI.getArgOperand(0);
1072 // free undef -> unreachable.
1073 if (isa<UndefValue>(Op)) {
1074 // Insert a new store to null because we cannot modify the CFG here.
1075 new StoreInst(ConstantInt::getTrue(FI.getContext()),
1076 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
1077 return EraseInstFromFunction(FI);
1080 // If we have 'free null' delete the instruction. This can happen in stl code
1081 // when lots of inlining happens.
1082 if (isa<ConstantPointerNull>(Op))
1083 return EraseInstFromFunction(FI);
1090 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1091 // Change br (not X), label True, label False to: br X, label False, True
1093 BasicBlock *TrueDest;
1094 BasicBlock *FalseDest;
1095 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1096 !isa<Constant>(X)) {
1097 // Swap Destinations and condition...
1099 BI.setSuccessor(0, FalseDest);
1100 BI.setSuccessor(1, TrueDest);
1104 // Cannonicalize fcmp_one -> fcmp_oeq
1105 FCmpInst::Predicate FPred; Value *Y;
1106 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1107 TrueDest, FalseDest)) &&
1108 BI.getCondition()->hasOneUse())
1109 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1110 FPred == FCmpInst::FCMP_OGE) {
1111 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1112 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1114 // Swap Destinations and condition.
1115 BI.setSuccessor(0, FalseDest);
1116 BI.setSuccessor(1, TrueDest);
1121 // Cannonicalize icmp_ne -> icmp_eq
1122 ICmpInst::Predicate IPred;
1123 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1124 TrueDest, FalseDest)) &&
1125 BI.getCondition()->hasOneUse())
1126 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1127 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1128 IPred == ICmpInst::ICMP_SGE) {
1129 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1130 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1131 // Swap Destinations and condition.
1132 BI.setSuccessor(0, FalseDest);
1133 BI.setSuccessor(1, TrueDest);
1141 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1142 Value *Cond = SI.getCondition();
1143 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1144 if (I->getOpcode() == Instruction::Add)
1145 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1146 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1147 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
1149 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
1151 SI.setOperand(0, I->getOperand(0));
1159 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1160 Value *Agg = EV.getAggregateOperand();
1162 if (!EV.hasIndices())
1163 return ReplaceInstUsesWith(EV, Agg);
1165 if (Constant *C = dyn_cast<Constant>(Agg)) {
1166 if (isa<UndefValue>(C))
1167 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1169 if (isa<ConstantAggregateZero>(C))
1170 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1172 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1173 // Extract the element indexed by the first index out of the constant
1174 Value *V = C->getOperand(*EV.idx_begin());
1175 if (EV.getNumIndices() > 1)
1176 // Extract the remaining indices out of the constant indexed by the
1178 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1180 return ReplaceInstUsesWith(EV, V);
1182 return 0; // Can't handle other constants
1184 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1185 // We're extracting from an insertvalue instruction, compare the indices
1186 const unsigned *exti, *exte, *insi, *inse;
1187 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1188 exte = EV.idx_end(), inse = IV->idx_end();
1189 exti != exte && insi != inse;
1192 // The insert and extract both reference distinctly different elements.
1193 // This means the extract is not influenced by the insert, and we can
1194 // replace the aggregate operand of the extract with the aggregate
1195 // operand of the insert. i.e., replace
1196 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1197 // %E = extractvalue { i32, { i32 } } %I, 0
1199 // %E = extractvalue { i32, { i32 } } %A, 0
1200 return ExtractValueInst::Create(IV->getAggregateOperand(),
1201 EV.idx_begin(), EV.idx_end());
1203 if (exti == exte && insi == inse)
1204 // Both iterators are at the end: Index lists are identical. Replace
1205 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1206 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1208 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1210 // The extract list is a prefix of the insert list. i.e. replace
1211 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1212 // %E = extractvalue { i32, { i32 } } %I, 1
1214 // %X = extractvalue { i32, { i32 } } %A, 1
1215 // %E = insertvalue { i32 } %X, i32 42, 0
1216 // by switching the order of the insert and extract (though the
1217 // insertvalue should be left in, since it may have other uses).
1218 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1219 EV.idx_begin(), EV.idx_end());
1220 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1224 // The insert list is a prefix of the extract list
1225 // We can simply remove the common indices from the extract and make it
1226 // operate on the inserted value instead of the insertvalue result.
1228 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1229 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1231 // %E extractvalue { i32 } { i32 42 }, 0
1232 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1235 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1236 // We're extracting from an intrinsic, see if we're the only user, which
1237 // allows us to simplify multiple result intrinsics to simpler things that
1238 // just get one value.
1239 if (II->hasOneUse()) {
1240 // Check if we're grabbing the overflow bit or the result of a 'with
1241 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1242 // and replace it with a traditional binary instruction.
1243 switch (II->getIntrinsicID()) {
1244 case Intrinsic::uadd_with_overflow:
1245 case Intrinsic::sadd_with_overflow:
1246 if (*EV.idx_begin() == 0) { // Normal result.
1247 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1248 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1249 EraseInstFromFunction(*II);
1250 return BinaryOperator::CreateAdd(LHS, RHS);
1253 // If the normal result of the add is dead, and the RHS is a constant,
1254 // we can transform this into a range comparison.
1255 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1256 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1257 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1258 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1259 ConstantExpr::getNot(CI));
1261 case Intrinsic::usub_with_overflow:
1262 case Intrinsic::ssub_with_overflow:
1263 if (*EV.idx_begin() == 0) { // Normal result.
1264 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1265 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1266 EraseInstFromFunction(*II);
1267 return BinaryOperator::CreateSub(LHS, RHS);
1270 case Intrinsic::umul_with_overflow:
1271 case Intrinsic::smul_with_overflow:
1272 if (*EV.idx_begin() == 0) { // Normal result.
1273 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1274 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1275 EraseInstFromFunction(*II);
1276 return BinaryOperator::CreateMul(LHS, RHS);
1284 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1285 // If the (non-volatile) load only has one use, we can rewrite this to a
1286 // load from a GEP. This reduces the size of the load.
1287 // FIXME: If a load is used only by extractvalue instructions then this
1288 // could be done regardless of having multiple uses.
1289 if (!L->isVolatile() && L->hasOneUse()) {
1290 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1291 SmallVector<Value*, 4> Indices;
1292 // Prefix an i32 0 since we need the first element.
1293 Indices.push_back(Builder->getInt32(0));
1294 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1296 Indices.push_back(Builder->getInt32(*I));
1298 // We need to insert these at the location of the old load, not at that of
1299 // the extractvalue.
1300 Builder->SetInsertPoint(L->getParent(), L);
1301 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(),
1302 Indices.begin(), Indices.end());
1303 // Returning the load directly will cause the main loop to insert it in
1304 // the wrong spot, so use ReplaceInstUsesWith().
1305 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1307 // We could simplify extracts from other values. Note that nested extracts may
1308 // already be simplified implicitly by the above: extract (extract (insert) )
1309 // will be translated into extract ( insert ( extract ) ) first and then just
1310 // the value inserted, if appropriate. Similarly for extracts from single-use
1311 // loads: extract (extract (load)) will be translated to extract (load (gep))
1312 // and if again single-use then via load (gep (gep)) to load (gep).
1313 // However, double extracts from e.g. function arguments or return values
1314 // aren't handled yet.
1321 /// TryToSinkInstruction - Try to move the specified instruction from its
1322 /// current block into the beginning of DestBlock, which can only happen if it's
1323 /// safe to move the instruction past all of the instructions between it and the
1324 /// end of its block.
1325 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1326 assert(I->hasOneUse() && "Invariants didn't hold!");
1328 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1329 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1332 // Do not sink alloca instructions out of the entry block.
1333 if (isa<AllocaInst>(I) && I->getParent() ==
1334 &DestBlock->getParent()->getEntryBlock())
1337 // We can only sink load instructions if there is nothing between the load and
1338 // the end of block that could change the value.
1339 if (I->mayReadFromMemory()) {
1340 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1342 if (Scan->mayWriteToMemory())
1346 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1348 I->moveBefore(InsertPos);
1354 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1355 /// all reachable code to the worklist.
1357 /// This has a couple of tricks to make the code faster and more powerful. In
1358 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1359 /// them to the worklist (this significantly speeds up instcombine on code where
1360 /// many instructions are dead or constant). Additionally, if we find a branch
1361 /// whose condition is a known constant, we only visit the reachable successors.
1363 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1364 SmallPtrSet<BasicBlock*, 64> &Visited,
1366 const TargetData *TD) {
1367 bool MadeIRChange = false;
1368 SmallVector<BasicBlock*, 256> Worklist;
1369 Worklist.push_back(BB);
1371 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1372 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1375 BB = Worklist.pop_back_val();
1377 // We have now visited this block! If we've already been here, ignore it.
1378 if (!Visited.insert(BB)) continue;
1380 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1381 Instruction *Inst = BBI++;
1383 // DCE instruction if trivially dead.
1384 if (isInstructionTriviallyDead(Inst)) {
1386 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1387 Inst->eraseFromParent();
1391 // ConstantProp instruction if trivially constant.
1392 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1393 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1394 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1396 Inst->replaceAllUsesWith(C);
1398 Inst->eraseFromParent();
1403 // See if we can constant fold its operands.
1404 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1406 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1407 if (CE == 0) continue;
1409 // If we already folded this constant, don't try again.
1410 if (!FoldedConstants.insert(CE))
1413 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
1414 if (NewC && NewC != CE) {
1416 MadeIRChange = true;
1421 InstrsForInstCombineWorklist.push_back(Inst);
1424 // Recursively visit successors. If this is a branch or switch on a
1425 // constant, only visit the reachable successor.
1426 TerminatorInst *TI = BB->getTerminator();
1427 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1428 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1429 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1430 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1431 Worklist.push_back(ReachableBB);
1434 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1435 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1436 // See if this is an explicit destination.
1437 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1438 if (SI->getCaseValue(i) == Cond) {
1439 BasicBlock *ReachableBB = SI->getSuccessor(i);
1440 Worklist.push_back(ReachableBB);
1444 // Otherwise it is the default destination.
1445 Worklist.push_back(SI->getSuccessor(0));
1450 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1451 Worklist.push_back(TI->getSuccessor(i));
1452 } while (!Worklist.empty());
1454 // Once we've found all of the instructions to add to instcombine's worklist,
1455 // add them in reverse order. This way instcombine will visit from the top
1456 // of the function down. This jives well with the way that it adds all uses
1457 // of instructions to the worklist after doing a transformation, thus avoiding
1458 // some N^2 behavior in pathological cases.
1459 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1460 InstrsForInstCombineWorklist.size());
1462 return MadeIRChange;
1465 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1466 MadeIRChange = false;
1468 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1469 << F.getNameStr() << "\n");
1472 // Do a depth-first traversal of the function, populate the worklist with
1473 // the reachable instructions. Ignore blocks that are not reachable. Keep
1474 // track of which blocks we visit.
1475 SmallPtrSet<BasicBlock*, 64> Visited;
1476 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1478 // Do a quick scan over the function. If we find any blocks that are
1479 // unreachable, remove any instructions inside of them. This prevents
1480 // the instcombine code from having to deal with some bad special cases.
1481 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1482 if (!Visited.count(BB)) {
1483 Instruction *Term = BB->getTerminator();
1484 while (Term != BB->begin()) { // Remove instrs bottom-up
1485 BasicBlock::iterator I = Term; --I;
1487 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1488 // A debug intrinsic shouldn't force another iteration if we weren't
1489 // going to do one without it.
1490 if (!isa<DbgInfoIntrinsic>(I)) {
1492 MadeIRChange = true;
1495 // If I is not void type then replaceAllUsesWith undef.
1496 // This allows ValueHandlers and custom metadata to adjust itself.
1497 if (!I->getType()->isVoidTy())
1498 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1499 I->eraseFromParent();
1504 while (!Worklist.isEmpty()) {
1505 Instruction *I = Worklist.RemoveOne();
1506 if (I == 0) continue; // skip null values.
1508 // Check to see if we can DCE the instruction.
1509 if (isInstructionTriviallyDead(I)) {
1510 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1511 EraseInstFromFunction(*I);
1513 MadeIRChange = true;
1517 // Instruction isn't dead, see if we can constant propagate it.
1518 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1519 if (Constant *C = ConstantFoldInstruction(I, TD)) {
1520 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1522 // Add operands to the worklist.
1523 ReplaceInstUsesWith(*I, C);
1525 EraseInstFromFunction(*I);
1526 MadeIRChange = true;
1530 // See if we can trivially sink this instruction to a successor basic block.
1531 if (I->hasOneUse()) {
1532 BasicBlock *BB = I->getParent();
1533 Instruction *UserInst = cast<Instruction>(I->use_back());
1534 BasicBlock *UserParent;
1536 // Get the block the use occurs in.
1537 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1538 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1540 UserParent = UserInst->getParent();
1542 if (UserParent != BB) {
1543 bool UserIsSuccessor = false;
1544 // See if the user is one of our successors.
1545 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1546 if (*SI == UserParent) {
1547 UserIsSuccessor = true;
1551 // If the user is one of our immediate successors, and if that successor
1552 // only has us as a predecessors (we'd have to split the critical edge
1553 // otherwise), we can keep going.
1554 if (UserIsSuccessor && UserParent->getSinglePredecessor())
1555 // Okay, the CFG is simple enough, try to sink this instruction.
1556 MadeIRChange |= TryToSinkInstruction(I, UserParent);
1560 // Now that we have an instruction, try combining it to simplify it.
1561 Builder->SetInsertPoint(I->getParent(), I);
1566 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1567 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1569 if (Instruction *Result = visit(*I)) {
1571 // Should we replace the old instruction with a new one?
1573 DEBUG(errs() << "IC: Old = " << *I << '\n'
1574 << " New = " << *Result << '\n');
1576 // Everything uses the new instruction now.
1577 I->replaceAllUsesWith(Result);
1579 // Push the new instruction and any users onto the worklist.
1580 Worklist.Add(Result);
1581 Worklist.AddUsersToWorkList(*Result);
1583 // Move the name to the new instruction first.
1584 Result->takeName(I);
1586 // Insert the new instruction into the basic block...
1587 BasicBlock *InstParent = I->getParent();
1588 BasicBlock::iterator InsertPos = I;
1590 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1591 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1594 InstParent->getInstList().insert(InsertPos, Result);
1596 EraseInstFromFunction(*I);
1599 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1600 << " New = " << *I << '\n');
1603 // If the instruction was modified, it's possible that it is now dead.
1604 // if so, remove it.
1605 if (isInstructionTriviallyDead(I)) {
1606 EraseInstFromFunction(*I);
1609 Worklist.AddUsersToWorkList(*I);
1612 MadeIRChange = true;
1617 return MadeIRChange;
1621 bool InstCombiner::runOnFunction(Function &F) {
1622 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1623 TD = getAnalysisIfAvailable<TargetData>();
1626 /// Builder - This is an IRBuilder that automatically inserts new
1627 /// instructions into the worklist when they are created.
1628 IRBuilder<true, TargetFolder, InstCombineIRInserter>
1629 TheBuilder(F.getContext(), TargetFolder(TD),
1630 InstCombineIRInserter(Worklist));
1631 Builder = &TheBuilder;
1633 bool EverMadeChange = false;
1635 // Iterate while there is work to do.
1636 unsigned Iteration = 0;
1637 while (DoOneIteration(F, Iteration++))
1638 EverMadeChange = true;
1641 return EverMadeChange;
1644 FunctionPass *llvm::createInstructionCombiningPass() {
1645 return new InstCombiner();