blob: 218e7ae2297fa0d0b4dfa87845bbed5b57f861cc [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
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
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
36#define DEBUG_TYPE "instcombine"
37#include "llvm/Transforms/Scalar.h"
Chris Lattner530dd162010-01-04 07:12:23 +000038#include "InstCombine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/IntrinsicInst.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera9333562009-11-09 23:28:39 +000041#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandez28f4d2f2009-10-27 20:05:49 +000042#include "llvm/Analysis/MemoryBuiltins.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6f722bc2010-01-05 07:54:43 +000045#include "llvm/Support/CFG.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include "llvm/Support/Debug.h"
47#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/PatternMatch.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/Statistic.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000052#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053using namespace llvm;
54using namespace llvm::PatternMatch;
55
56STATISTIC(NumCombined , "Number of insts combined");
57STATISTIC(NumConstProp, "Number of constant folds");
58STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059STATISTIC(NumSunkInst , "Number of instructions sunk");
60
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061
Dan Gohman089efff2008-05-13 00:00:25 +000062char InstCombiner::ID = 0;
63static RegisterPass<InstCombiner>
64X("instcombine", "Combine redundant instructions");
65
Chris Lattnerc1cea3f2010-01-04 07:17:19 +000066void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addPreservedID(LCSSAID);
68 AU.setPreservesCFG();
69}
70
71
Chris Lattnerd0011092009-11-10 07:23:37 +000072/// ShouldChangeType - Return true if it is desirable to convert a computation
73/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
74/// type for example, or from a smaller to a larger illegal type.
Chris Lattner54826cd2010-01-04 07:53:58 +000075bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Chris Lattnerd0011092009-11-10 07:23:37 +000076 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
77
78 // If we don't have TD, we don't know if the source/dest are legal.
79 if (!TD) return false;
80
81 unsigned FromWidth = From->getPrimitiveSizeInBits();
82 unsigned ToWidth = To->getPrimitiveSizeInBits();
83 bool FromLegal = TD->isLegalInteger(FromWidth);
84 bool ToLegal = TD->isLegalInteger(ToWidth);
85
86 // If this is a legal integer from type, and the result would be an illegal
87 // type, don't do the transformation.
88 if (FromLegal && !ToLegal)
89 return false;
90
91 // Otherwise, if both are illegal, do not increase the size of the result. We
92 // do allow things like i160 -> i64, but not i64 -> i160.
93 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
94 return false;
95
96 return true;
97}
98
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100// SimplifyCommutative - This performs a few simplifications for commutative
101// operators:
102//
103// 1. Order operands such that they are listed from right (least complex) to
104// left (most complex). This puts constants before unary operators before
105// binary operators.
106//
107// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
108// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
109//
110bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
111 bool Changed = false;
Dan Gohman5d138f92009-08-29 23:39:38 +0000112 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 Changed = !I.swapOperands();
114
115 if (!I.isAssociative()) return Changed;
Chris Lattner1e680352010-01-05 07:04:23 +0000116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 Instruction::BinaryOps Opcode = I.getOpcode();
118 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
119 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
120 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000121 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 cast<Constant>(I.getOperand(1)),
123 cast<Constant>(Op->getOperand(1)));
124 I.setOperand(0, Op->getOperand(0));
125 I.setOperand(1, Folded);
126 return true;
Chris Lattner1e680352010-01-05 07:04:23 +0000127 }
128
129 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
Chris Lattner1e680352010-01-05 07:04:23 +0000131 Op->hasOneUse() && Op1->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 Constant *C1 = cast<Constant>(Op->getOperand(1));
133 Constant *C2 = cast<Constant>(Op1->getOperand(1));
134
135 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson02b48c32009-07-29 18:55:55 +0000136 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000137 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 Op1->getOperand(0),
139 Op1->getName(), &I);
Chris Lattner3183fb62009-08-30 06:13:40 +0000140 Worklist.Add(New);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 I.setOperand(0, New);
142 I.setOperand(1, Folded);
143 return true;
144 }
145 }
146 return Changed;
147}
148
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000149// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
150// if the LHS is a constant zero (which is the 'negate' form).
151//
Chris Lattner63ac8422010-01-04 07:37:31 +0000152Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000153 if (BinaryOperator::isNeg(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 return BinaryOperator::getNegArgument(V);
155
156 // Constants can be considered to be negated values if they can be folded.
157 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000158 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000159
160 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
161 if (C->getType()->getElementType()->isInteger())
Owen Anderson02b48c32009-07-29 18:55:55 +0000162 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000163
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164 return 0;
165}
166
Dan Gohman7ce405e2009-06-04 22:49:04 +0000167// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
168// instruction if the LHS is a constant negative zero (which is the 'negate'
169// form).
170//
Chris Lattner978364f2010-01-05 06:09:35 +0000171Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Anderson76f49252009-07-13 22:18:28 +0000172 if (BinaryOperator::isFNeg(V))
Dan Gohman7ce405e2009-06-04 22:49:04 +0000173 return BinaryOperator::getFNegArgument(V);
174
175 // Constants can be considered to be negated values if they can be folded.
176 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson02b48c32009-07-29 18:55:55 +0000177 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000178
179 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
180 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson02b48c32009-07-29 18:55:55 +0000181 return ConstantExpr::getFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000182
183 return 0;
184}
185
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
187 InstCombiner *IC) {
Chris Lattner78628292009-08-30 19:47:22 +0000188 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattnerd6164c22009-08-30 20:01:10 +0000189 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190
191 // Figure out if the constant is the left or the right argument.
192 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
193 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
194
195 if (Constant *SOC = dyn_cast<Constant>(SO)) {
196 if (ConstIsRHS)
Owen Anderson02b48c32009-07-29 18:55:55 +0000197 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
198 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 }
200
201 Value *Op0 = SO, *Op1 = ConstOperand;
202 if (!ConstIsRHS)
203 std::swap(Op0, Op1);
Chris Lattnerc7694852009-08-30 07:44:24 +0000204
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattnerc7694852009-08-30 07:44:24 +0000206 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
207 SO->getName()+".op");
208 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
209 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
210 SO->getName()+".cmp");
211 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
212 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
213 SO->getName()+".cmp");
214 llvm_unreachable("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215}
216
217// FoldOpIntoSelect - Given an instruction with a select as one operand and a
218// constant as the other operand, try to fold the binary operator into the
219// select arguments. This also works for Cast instructions, which obviously do
220// not have a second operand.
Chris Lattner54826cd2010-01-04 07:53:58 +0000221Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222 // Don't modify shared select instructions
223 if (!SI->hasOneUse()) return 0;
224 Value *TV = SI->getOperand(1);
225 Value *FV = SI->getOperand(2);
226
227 if (isa<Constant>(TV) || isa<Constant>(FV)) {
228 // Bool selects with constant operands can be folded to logical ops.
Chris Lattner03a27b42010-01-04 07:02:48 +0000229 if (SI->getType() == Type::getInt1Ty(SI->getContext())) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230
Chris Lattner54826cd2010-01-04 07:53:58 +0000231 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
232 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233
Gabor Greifd6da1d02008-04-06 20:25:17 +0000234 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
235 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 }
237 return 0;
238}
239
240
Chris Lattnerf7843b72009-09-27 19:57:57 +0000241/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
242/// has a PHI node as operand #0, see if we can fold the instruction into the
243/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner9b61abd2009-09-27 20:46:36 +0000244///
245/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
246/// that would normally be unprofitable because they strongly encourage jump
247/// threading.
248Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
249 bool AllowAggressive) {
250 AllowAggressive = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 PHINode *PN = cast<PHINode>(I.getOperand(0));
252 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner9b61abd2009-09-27 20:46:36 +0000253 if (NumPHIValues == 0 ||
254 // We normally only transform phis with a single use, unless we're trying
255 // hard to make jump threading happen.
256 (!PN->hasOneUse() && !AllowAggressive))
257 return 0;
258
259
Chris Lattnerf7843b72009-09-27 19:57:57 +0000260 // Check to see if all of the operands of the PHI are simple constants
261 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000262 // remember the BB it is in. If there is more than one or if *it* is a PHI,
263 // bail out. We don't do arbitrary constant expressions here because moving
264 // their computation can be expensive without a cost model.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000265 BasicBlock *NonConstBB = 0;
266 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattnerf7843b72009-09-27 19:57:57 +0000267 if (!isa<Constant>(PN->getIncomingValue(i)) ||
268 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 if (NonConstBB) return 0; // More than one non-const value.
270 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
271 NonConstBB = PN->getIncomingBlock(i);
272
273 // If the incoming non-constant value is in I's block, we have an infinite
274 // loop.
275 if (NonConstBB == I.getParent())
276 return 0;
277 }
278
279 // If there is exactly one non-constant value, we can insert a copy of the
280 // operation in that block. However, if this is a critical edge, we would be
281 // inserting the computation one some other paths (e.g. inside a loop). Only
282 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9b61abd2009-09-27 20:46:36 +0000283 if (NonConstBB != 0 && !AllowAggressive) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
285 if (!BI || !BI->isUnconditional()) return 0;
286 }
287
288 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +0000289 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000290 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner3980f9b2009-10-21 23:41:58 +0000291 InsertNewInstBefore(NewPN, *PN);
292 NewPN->takeName(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000293
294 // Next, add all of the operands to the PHI.
Chris Lattnerf7843b72009-09-27 19:57:57 +0000295 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
296 // We only currently try to fold the condition of a select when it is a phi,
297 // not the true/false values.
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000298 Value *TrueV = SI->getTrueValue();
299 Value *FalseV = SI->getFalseValue();
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000300 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerf7843b72009-09-27 19:57:57 +0000301 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000302 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattnerda3ee9c2009-09-28 06:49:44 +0000303 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
304 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000305 Value *InV = 0;
306 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000307 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerf7843b72009-09-27 19:57:57 +0000308 } else {
309 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000310 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
311 FalseVInPred,
Chris Lattnerf7843b72009-09-27 19:57:57 +0000312 "phitmp", NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000313 Worklist.Add(cast<Instruction>(InV));
Chris Lattnerf7843b72009-09-27 19:57:57 +0000314 }
Chris Lattnerff5cd9d2009-09-27 20:18:49 +0000315 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerf7843b72009-09-27 19:57:57 +0000316 }
317 } else if (I.getNumOperands() == 2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318 Constant *C = cast<Constant>(I.getOperand(1));
319 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +0000320 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000321 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
322 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson02b48c32009-07-29 18:55:55 +0000323 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324 else
Owen Anderson02b48c32009-07-29 18:55:55 +0000325 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326 } else {
327 assert(PN->getIncomingBlock(i) == NonConstBB);
328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +0000329 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330 PN->getIncomingValue(i), C, "phitmp",
331 NonConstBB->getTerminator());
332 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohmane6803b82009-08-25 23:17:54 +0000333 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000334 CI->getPredicate(),
335 PN->getIncomingValue(i), C, "phitmp",
336 NonConstBB->getTerminator());
337 else
Edwin Törökbd448e32009-07-14 16:55:14 +0000338 llvm_unreachable("Unknown binop!");
Chris Lattner3980f9b2009-10-21 23:41:58 +0000339
340 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 }
342 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
343 }
344 } else {
345 CastInst *CI = cast<CastInst>(&I);
346 const Type *RetTy = CI->getType();
347 for (unsigned i = 0; i != NumPHIValues; ++i) {
348 Value *InV;
349 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson02b48c32009-07-29 18:55:55 +0000350 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 } else {
352 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +0000353 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000354 I.getType(), "phitmp",
355 NonConstBB->getTerminator());
Chris Lattner3980f9b2009-10-21 23:41:58 +0000356 Worklist.Add(cast<Instruction>(InV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 }
358 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
359 }
360 }
361 return ReplaceInstUsesWith(I, NewPN);
362}
363
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000364/// FindElementAtOffset - Given a type and a constant offset, determine whether
365/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +0000366/// the specified offset. If so, fill them into NewIndices and return the
367/// resultant element type, otherwise return null.
Chris Lattner54826cd2010-01-04 07:53:58 +0000368const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
369 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000370 if (!TD) return 0;
Chris Lattner54dddc72009-01-24 01:00:13 +0000371 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000372
373 // Start with the index over the outer type. Note that the type size
374 // might be zero (even if the offset isn't zero) if the indexed type
375 // is something like [0 x {int, int}]
Chris Lattner03a27b42010-01-04 07:02:48 +0000376 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000377 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000378 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000379 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +0000380 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000381
Chris Lattnerce48c462009-01-11 20:15:20 +0000382 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000383 if (Offset < 0) {
384 --FirstIdx;
385 Offset += TySize;
386 assert(Offset >= 0);
387 }
388 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
389 }
390
Owen Andersoneacb44d2009-07-24 23:12:02 +0000391 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000392
393 // Index into the types. If we fail, set OrigBase to null.
394 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +0000395 // Indexing into tail padding between struct/array elements.
396 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +0000397 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +0000398
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000399 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
400 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +0000401 assert(Offset < (int64_t)SL->getSizeInBytes() &&
402 "Offset must stay within the indexed type");
403
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000404 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner03a27b42010-01-04 07:02:48 +0000405 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
406 Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000407
408 Offset -= SL->getElementOffset(Elt);
409 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +0000410 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000411 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +0000412 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneacb44d2009-07-24 23:12:02 +0000413 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +0000414 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +0000415 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000416 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +0000417 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +0000418 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000419 }
420 }
421
Chris Lattner54dddc72009-01-24 01:00:13 +0000422 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000423}
424
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000426
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5594a482009-11-27 00:29:05 +0000428 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
429
430 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
431 return ReplaceInstUsesWith(GEP, V);
432
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 Value *PtrOp = GEP.getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000434
435 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000436 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000437
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 // Eliminate unneeded casts for indices.
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000439 if (TD) {
440 bool MadeChange = false;
441 unsigned PtrSize = TD->getPointerSizeInBits();
442
443 gep_type_iterator GTI = gep_type_begin(GEP);
444 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
445 I != E; ++I, ++GTI) {
446 if (!isa<SequentialType>(*GTI)) continue;
447
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000449 // to what we need. If narrower, sign-extend it to what we need. This
450 // explicit cast can make subsequent optimizations more obvious.
451 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000452 if (OpBits == PtrSize)
453 continue;
454
Chris Lattnerd6164c22009-08-30 20:01:10 +0000455 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000456 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 }
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000458 if (MadeChange) return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000459 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 // Combine Indices - If the source pointer to this getelementptr instruction
462 // is a getelementptr instruction, combine the indices of the two
463 // getelementptr instructions into a single instruction.
464 //
Dan Gohman17f46f72009-07-28 01:40:03 +0000465 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 // Note that if our source is a gep chain itself that we wait for that
467 // chain to be resolved before we perform this transformation. This
468 // avoids us creating a TON of code in some cases.
469 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000470 if (GetElementPtrInst *SrcGEP =
471 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
472 if (SrcGEP->getNumOperands() == 2)
473 return 0; // Wait until our source is folded to completion.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474
475 SmallVector<Value*, 8> Indices;
476
477 // Find out whether the last index in the source GEP is a sequential idx.
478 bool EndsWithSequential = false;
Chris Lattner1c641fc2009-08-30 05:30:55 +0000479 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
480 I != E; ++I)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 EndsWithSequential = !isa<StructType>(*I);
482
483 // Can we combine the two pointer arithmetics offsets?
484 if (EndsWithSequential) {
485 // Replace: gep (gep %P, long B), long A, ...
486 // With: T = long A+B; gep %P, T, ...
487 //
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000488 Value *Sum;
489 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
490 Value *GO1 = GEP.getOperand(1);
Owen Andersonaac28372009-07-31 20:28:14 +0000491 if (SO1 == Constant::getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000492 Sum = GO1;
Owen Andersonaac28372009-07-31 20:28:14 +0000493 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 Sum = SO1;
495 } else {
Chris Lattner1c641fc2009-08-30 05:30:55 +0000496 // If they aren't the same type, then the input hasn't been processed
497 // by the loop above yet (which canonicalizes sequential index types to
498 // intptr_t). Just avoid transforming this until the input has been
499 // normalized.
500 if (SO1->getType() != GO1->getType())
501 return 0;
Chris Lattnerad7516a2009-08-30 18:50:58 +0000502 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 }
504
Chris Lattner1c641fc2009-08-30 05:30:55 +0000505 // Update the GEP in place if possible.
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000506 if (Src->getNumOperands() == 2) {
507 GEP.setOperand(0, Src->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000508 GEP.setOperand(1, Sum);
509 return &GEP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510 }
Chris Lattner1c641fc2009-08-30 05:30:55 +0000511 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000512 Indices.push_back(Sum);
Chris Lattner1c641fc2009-08-30 05:30:55 +0000513 Indices.append(GEP.op_begin()+2, GEP.op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 } else if (isa<Constant>(*GEP.idx_begin()) &&
515 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000516 Src->getNumOperands() != 1) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner1c641fc2009-08-30 05:30:55 +0000518 Indices.append(Src->op_begin()+1, Src->op_end());
519 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000520 }
521
Dan Gohmanf3a08b82009-09-07 23:54:19 +0000522 if (!Indices.empty())
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000523 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf3a08b82009-09-07 23:54:19 +0000524 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
525 Indices.end(), GEP.getName()) :
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000526 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerc0f553e2009-08-30 04:49:01 +0000527 Indices.end(), GEP.getName());
Chris Lattner95ba1ec2009-08-30 05:00:50 +0000528 }
529
Chris Lattnerc2c8a0a2009-08-30 05:08:50 +0000530 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000531 Value *StrippedPtr = PtrOp->stripPointerCasts();
532 if (StrippedPtr != PtrOp) {
533 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattnerf3a23592009-08-30 20:36:46 +0000534
Chris Lattner5594a482009-11-27 00:29:05 +0000535 bool HasZeroPointerIndex = false;
536 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
537 HasZeroPointerIndex = C->isZero();
538
Chris Lattnerf3a23592009-08-30 20:36:46 +0000539 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
540 // into : GEP [10 x i8]* X, i32 0, ...
541 //
542 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
543 // into : GEP i8* X, ...
544 //
545 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner95ba1ec2009-08-30 05:00:50 +0000546 if (HasZeroPointerIndex) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +0000548 if (const ArrayType *CATy =
549 dyn_cast<ArrayType>(CPTy->getElementType())) {
550 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000551 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +0000552 // -> GEP i8* X, ...
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000553 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
554 GetElementPtrInst *Res =
555 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
556 Idx.end(), GEP.getName());
557 Res->setIsInBounds(GEP.isInBounds());
558 return Res;
Chris Lattnerf3a23592009-08-30 20:36:46 +0000559 }
560
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000561 if (const ArrayType *XATy =
562 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sandscf866e62009-03-02 09:18:21 +0000563 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +0000565 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 // At this point, we know that the cast source type is a pointer
567 // to an array of the same type as the destination pointer
568 // array. Because the array type is never stepped over (there
569 // is a leading zero) we can fold the cast into this GEP.
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000570 GEP.setOperand(0, StrippedPtr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 return &GEP;
572 }
Duncan Sandscf866e62009-03-02 09:18:21 +0000573 }
574 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 } else if (GEP.getNumOperands() == 2) {
576 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000577 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
578 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000579 const Type *SrcElTy = StrippedPtrTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmana80e2712009-07-21 23:21:54 +0000581 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000582 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
583 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +0000584 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +0000585 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +0000586 Idx[1] = GEP.getOperand(1);
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000587 Value *NewGEP = GEP.isInBounds() ?
588 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
589 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 // V and GEP are both pointer types --> BitCast
Chris Lattnerad7516a2009-08-30 18:50:58 +0000591 return new BitCastInst(NewGEP, GEP.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000592 }
593
594 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000595 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000597 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598
Chris Lattner03a27b42010-01-04 07:02:48 +0000599 if (TD && isa<ArrayType>(SrcElTy) &&
600 ResElTy == Type::getInt8Ty(GEP.getContext())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +0000602 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603
604 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
605 // allow either a mul, shift, or constant here.
606 Value *NewIdx = 0;
607 ConstantInt *Scale = 0;
608 if (ArrayEltSize == 1) {
609 NewIdx = GEP.getOperand(1);
Chris Lattner1c641fc2009-08-30 05:30:55 +0000610 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneacb44d2009-07-24 23:12:02 +0000612 NewIdx = ConstantInt::get(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 Scale = CI;
614 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
615 if (Inst->getOpcode() == Instruction::Shl &&
616 isa<ConstantInt>(Inst->getOperand(1))) {
617 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
618 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneacb44d2009-07-24 23:12:02 +0000619 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +0000620 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000621 NewIdx = Inst->getOperand(0);
622 } else if (Inst->getOpcode() == Instruction::Mul &&
623 isa<ConstantInt>(Inst->getOperand(1))) {
624 Scale = cast<ConstantInt>(Inst->getOperand(1));
625 NewIdx = Inst->getOperand(0);
626 }
627 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000628
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000630 // out, perform the transformation. Note, we don't know whether Scale is
631 // signed or not. We'll use unsigned version of division/modulo
632 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +0000633 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000634 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneacb44d2009-07-24 23:12:02 +0000635 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +0000636 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 if (Scale->getZExtValue() != 1) {
Chris Lattnerbf09d632009-08-30 05:56:44 +0000638 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
639 false /*ZExt*/);
Chris Lattnerad7516a2009-08-30 18:50:58 +0000640 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642
643 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +0000644 Value *Idx[2];
Chris Lattner03a27b42010-01-04 07:02:48 +0000645 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greene393be882007-09-04 15:46:09 +0000646 Idx[1] = NewIdx;
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000647 Value *NewGEP = GEP.isInBounds() ?
648 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
649 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 // The NewGEP must be pointer typed, so must the old one -> BitCast
651 return new BitCastInst(NewGEP, GEP.getType());
652 }
653 }
654 }
655 }
Chris Lattner111ea772009-01-09 04:53:57 +0000656
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000657 /// See if we can simplify:
Chris Lattner5119c702009-08-30 05:55:36 +0000658 /// X = bitcast A* to B*
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000659 /// Y = gep X, <...constant indices...>
660 /// into a gep of the original struct. This is important for SROA and alias
661 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +0000662 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmana80e2712009-07-21 23:21:54 +0000663 if (TD &&
664 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000665 // Determine how much the GEP moves the pointer. We are guaranteed to get
666 // a constant back from EmitGEPOffset.
Chris Lattner63ac8422010-01-04 07:37:31 +0000667 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000668 int64_t Offset = OffsetV->getSExtValue();
669
670 // If this GEP instruction doesn't move the pointer, just replace the GEP
671 // with a bitcast of the real input to the dest type.
672 if (Offset == 0) {
673 // If the bitcast is of an allocation, and the allocation will be
674 // converted to match the type of the cast, don't touch this.
Victor Hernandezb1687302009-10-23 21:09:37 +0000675 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez48c3c542009-09-18 22:35:49 +0000676 isMalloc(BCI->getOperand(0))) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000677 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
678 if (Instruction *I = visitBitCast(*BCI)) {
679 if (I != BCI) {
680 I->takeName(BCI);
681 BCI->getParent()->getInstList().insert(BCI, I);
682 ReplaceInstUsesWith(*BCI, I);
683 }
684 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +0000685 }
Chris Lattner111ea772009-01-09 04:53:57 +0000686 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000687 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +0000688 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000689
690 // Otherwise, if the offset is non-zero, we need to find out if there is a
691 // field at Offset in 'A's type. If so, we can pull the cast through the
692 // GEP.
693 SmallVector<Value*, 8> NewIndices;
694 const Type *InTy =
695 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner54826cd2010-01-04 07:53:58 +0000696 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattnerbb32d5e2010-01-05 07:42:10 +0000697 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf3a08b82009-09-07 23:54:19 +0000698 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
699 NewIndices.end()) :
700 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
701 NewIndices.end());
Chris Lattnerad7516a2009-08-30 18:50:58 +0000702
703 if (NGEP->getType() == GEP.getType())
704 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner94ccd5f2009-01-09 05:44:56 +0000705 NGEP->takeName(&GEP);
706 return new BitCastInst(NGEP, GEP.getType());
707 }
Chris Lattner111ea772009-01-09 04:53:57 +0000708 }
709 }
710
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 return 0;
712}
713
Victor Hernandez93946082009-10-24 04:23:03 +0000714Instruction *InstCombiner::visitFree(Instruction &FI) {
715 Value *Op = FI.getOperand(1);
716
717 // free undef -> unreachable.
718 if (isa<UndefValue>(Op)) {
719 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner03a27b42010-01-04 07:02:48 +0000720 new StoreInst(ConstantInt::getTrue(FI.getContext()),
721 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez93946082009-10-24 04:23:03 +0000722 return EraseInstFromFunction(FI);
723 }
724
725 // If we have 'free null' delete the instruction. This can happen in stl code
726 // when lots of inlining happens.
727 if (isa<ConstantPointerNull>(Op))
728 return EraseInstFromFunction(FI);
729
Victor Hernandezf9a7a332009-10-26 23:43:48 +0000730 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman1674ea52009-10-27 00:11:02 +0000731 if (isMalloc(Op)) {
Victor Hernandez93946082009-10-24 04:23:03 +0000732 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
733 if (Op->hasOneUse() && CI->hasOneUse()) {
734 EraseInstFromFunction(FI);
735 EraseInstFromFunction(*CI);
736 return EraseInstFromFunction(*cast<Instruction>(Op));
737 }
738 } else {
739 // Op is a call to malloc
740 if (Op->hasOneUse()) {
741 EraseInstFromFunction(FI);
742 return EraseInstFromFunction(*cast<Instruction>(Op));
743 }
744 }
Dan Gohman1674ea52009-10-27 00:11:02 +0000745 }
Victor Hernandez93946082009-10-24 04:23:03 +0000746
747 return 0;
748}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750
751
752Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
753 // Change br (not X), label True, label False to: br X, label False, True
754 Value *X = 0;
755 BasicBlock *TrueDest;
756 BasicBlock *FalseDest;
Dan Gohmancdff2122009-08-12 16:23:25 +0000757 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000758 !isa<Constant>(X)) {
759 // Swap Destinations and condition...
760 BI.setCondition(X);
761 BI.setSuccessor(0, FalseDest);
762 BI.setSuccessor(1, TrueDest);
763 return &BI;
764 }
765
766 // Cannonicalize fcmp_one -> fcmp_oeq
767 FCmpInst::Predicate FPred; Value *Y;
768 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +0000769 TrueDest, FalseDest)) &&
770 BI.getCondition()->hasOneUse())
771 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
772 FPred == FCmpInst::FCMP_OGE) {
773 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
774 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
775
776 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000777 BI.setSuccessor(0, FalseDest);
778 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +0000779 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780 return &BI;
781 }
782
783 // Cannonicalize icmp_ne -> icmp_eq
784 ICmpInst::Predicate IPred;
785 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner3183fb62009-08-30 06:13:40 +0000786 TrueDest, FalseDest)) &&
787 BI.getCondition()->hasOneUse())
788 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
789 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
790 IPred == ICmpInst::ICMP_SGE) {
791 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
792 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
793 // Swap Destinations and condition.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 BI.setSuccessor(0, FalseDest);
795 BI.setSuccessor(1, TrueDest);
Chris Lattner3183fb62009-08-30 06:13:40 +0000796 Worklist.Add(Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000797 return &BI;
798 }
799
800 return 0;
801}
802
803Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
804 Value *Cond = SI.getCondition();
805 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
806 if (I->getOpcode() == Instruction::Add)
807 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
808 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
809 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +0000810 SI.setOperand(i,
Owen Anderson02b48c32009-07-29 18:55:55 +0000811 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000812 AddRHS));
813 SI.setOperand(0, I->getOperand(0));
Chris Lattner3183fb62009-08-30 06:13:40 +0000814 Worklist.Add(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 return &SI;
816 }
817 }
818 return 0;
819}
820
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000821Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000822 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000823
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000824 if (!EV.hasIndices())
825 return ReplaceInstUsesWith(EV, Agg);
826
827 if (Constant *C = dyn_cast<Constant>(Agg)) {
828 if (isa<UndefValue>(C))
Owen Andersonb99ecca2009-07-30 23:03:37 +0000829 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000830
831 if (isa<ConstantAggregateZero>(C))
Owen Andersonaac28372009-07-31 20:28:14 +0000832 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000833
834 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
835 // Extract the element indexed by the first index out of the constant
836 Value *V = C->getOperand(*EV.idx_begin());
837 if (EV.getNumIndices() > 1)
838 // Extract the remaining indices out of the constant indexed by the
839 // first index
840 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
841 else
842 return ReplaceInstUsesWith(EV, V);
843 }
844 return 0; // Can't handle other constants
845 }
846 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
847 // We're extracting from an insertvalue instruction, compare the indices
848 const unsigned *exti, *exte, *insi, *inse;
849 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
850 exte = EV.idx_end(), inse = IV->idx_end();
851 exti != exte && insi != inse;
852 ++exti, ++insi) {
853 if (*insi != *exti)
854 // The insert and extract both reference distinctly different elements.
855 // This means the extract is not influenced by the insert, and we can
856 // replace the aggregate operand of the extract with the aggregate
857 // operand of the insert. i.e., replace
858 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
859 // %E = extractvalue { i32, { i32 } } %I, 0
860 // with
861 // %E = extractvalue { i32, { i32 } } %A, 0
862 return ExtractValueInst::Create(IV->getAggregateOperand(),
863 EV.idx_begin(), EV.idx_end());
864 }
865 if (exti == exte && insi == inse)
866 // Both iterators are at the end: Index lists are identical. Replace
867 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
868 // %C = extractvalue { i32, { i32 } } %B, 1, 0
869 // with "i32 42"
870 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
871 if (exti == exte) {
872 // The extract list is a prefix of the insert list. i.e. replace
873 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
874 // %E = extractvalue { i32, { i32 } } %I, 1
875 // with
876 // %X = extractvalue { i32, { i32 } } %A, 1
877 // %E = insertvalue { i32 } %X, i32 42, 0
878 // by switching the order of the insert and extract (though the
879 // insertvalue should be left in, since it may have other uses).
Chris Lattnerad7516a2009-08-30 18:50:58 +0000880 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
881 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000882 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
883 insi, inse);
884 }
885 if (insi == inse)
886 // The insert list is a prefix of the extract list
887 // We can simply remove the common indices from the extract and make it
888 // operate on the inserted value instead of the insertvalue result.
889 // i.e., replace
890 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
891 // %E = extractvalue { i32, { i32 } } %I, 1, 0
892 // with
893 // %E extractvalue { i32 } { i32 42 }, 0
894 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
895 exti, exte);
896 }
Chris Lattner69a70752009-11-09 07:07:56 +0000897 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
898 // We're extracting from an intrinsic, see if we're the only user, which
899 // allows us to simplify multiple result intrinsics to simpler things that
900 // just get one value..
901 if (II->hasOneUse()) {
902 // Check if we're grabbing the overflow bit or the result of a 'with
903 // overflow' intrinsic. If it's the latter we can remove the intrinsic
904 // and replace it with a traditional binary instruction.
905 switch (II->getIntrinsicID()) {
906 case Intrinsic::uadd_with_overflow:
907 case Intrinsic::sadd_with_overflow:
908 if (*EV.idx_begin() == 0) { // Normal result.
909 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
910 II->replaceAllUsesWith(UndefValue::get(II->getType()));
911 EraseInstFromFunction(*II);
912 return BinaryOperator::CreateAdd(LHS, RHS);
913 }
914 break;
915 case Intrinsic::usub_with_overflow:
916 case Intrinsic::ssub_with_overflow:
917 if (*EV.idx_begin() == 0) { // Normal result.
918 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
919 II->replaceAllUsesWith(UndefValue::get(II->getType()));
920 EraseInstFromFunction(*II);
921 return BinaryOperator::CreateSub(LHS, RHS);
922 }
923 break;
924 case Intrinsic::umul_with_overflow:
925 case Intrinsic::smul_with_overflow:
926 if (*EV.idx_begin() == 0) { // Normal result.
927 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
928 II->replaceAllUsesWith(UndefValue::get(II->getType()));
929 EraseInstFromFunction(*II);
930 return BinaryOperator::CreateMul(LHS, RHS);
931 }
932 break;
933 default:
934 break;
935 }
936 }
937 }
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +0000938 // Can't simplify extracts from other values. Note that nested extracts are
939 // already simplified implicitely by the above (extract ( extract (insert) )
940 // will be translated into extract ( insert ( extract ) ) first and then just
941 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000942 return 0;
943}
944
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945
946
947
948/// TryToSinkInstruction - Try to move the specified instruction from its
949/// current block into the beginning of DestBlock, which can only happen if it's
950/// safe to move the instruction past all of the instructions between it and the
951/// end of its block.
952static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
953 assert(I->hasOneUse() && "Invariants didn't hold!");
954
955 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +0000956 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +0000957 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958
959 // Do not sink alloca instructions out of the entry block.
960 if (isa<AllocaInst>(I) && I->getParent() ==
961 &DestBlock->getParent()->getEntryBlock())
962 return false;
963
964 // We can only sink load instructions if there is nothing between the load and
965 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +0000966 if (I->mayReadFromMemory()) {
967 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000968 Scan != E; ++Scan)
969 if (Scan->mayWriteToMemory())
970 return false;
971 }
972
Dan Gohman514277c2008-05-23 21:05:58 +0000973 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974
975 I->moveBefore(InsertPos);
976 ++NumSunkInst;
977 return true;
978}
979
980
981/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
982/// all reachable code to the worklist.
983///
984/// This has a couple of tricks to make the code faster and more powerful. In
985/// particular, we constant fold and DCE instructions as we go, to avoid adding
986/// them to the worklist (this significantly speeds up instcombine on code where
987/// many instructions are dead or constant). Additionally, if we find a branch
988/// whose condition is a known constant, we only visit the reachable successors.
989///
Chris Lattnerc4269e52009-10-15 04:59:28 +0000990static bool AddReachableCodeToWorklist(BasicBlock *BB,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000991 SmallPtrSet<BasicBlock*, 64> &Visited,
992 InstCombiner &IC,
993 const TargetData *TD) {
Chris Lattnerc4269e52009-10-15 04:59:28 +0000994 bool MadeIRChange = false;
Chris Lattnera06291a2008-08-15 04:03:01 +0000995 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 Worklist.push_back(BB);
Chris Lattnerb5663c72009-10-12 03:58:40 +0000997
998 std::vector<Instruction*> InstrsForInstCombineWorklist;
999 InstrsForInstCombineWorklist.reserve(128);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001000
Chris Lattnerc4269e52009-10-15 04:59:28 +00001001 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001003 while (!Worklist.empty()) {
1004 BB = Worklist.back();
1005 Worklist.pop_back();
1006
1007 // We have now visited this block! If we've already been here, ignore it.
1008 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +00001009
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001010 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1011 Instruction *Inst = BBI++;
1012
1013 // DCE instruction if trivially dead.
1014 if (isInstructionTriviallyDead(Inst)) {
1015 ++NumDeadInst;
Chris Lattner8a6411c2009-08-23 04:37:46 +00001016 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001017 Inst->eraseFromParent();
1018 continue;
1019 }
1020
1021 // ConstantProp instruction if trivially constant.
Chris Lattneree5839b2009-10-15 04:13:44 +00001022 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00001023 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00001024 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1025 << *Inst << '\n');
1026 Inst->replaceAllUsesWith(C);
1027 ++NumConstProp;
1028 Inst->eraseFromParent();
1029 continue;
1030 }
Chris Lattnerc4269e52009-10-15 04:59:28 +00001031
1032
1033
1034 if (TD) {
1035 // See if we can constant fold its operands.
1036 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1037 i != e; ++i) {
1038 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1039 if (CE == 0) continue;
1040
1041 // If we already folded this constant, don't try again.
1042 if (!FoldedConstants.insert(CE))
1043 continue;
1044
Chris Lattner6070c012009-11-06 04:27:31 +00001045 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattnerc4269e52009-10-15 04:59:28 +00001046 if (NewC && NewC != CE) {
1047 *i = NewC;
1048 MadeIRChange = true;
1049 }
1050 }
1051 }
1052
Devang Patel794140c2008-11-19 18:56:50 +00001053
Chris Lattnerb5663c72009-10-12 03:58:40 +00001054 InstrsForInstCombineWorklist.push_back(Inst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001055 }
1056
1057 // Recursively visit successors. If this is a branch or switch on a
1058 // constant, only visit the reachable successor.
1059 TerminatorInst *TI = BB->getTerminator();
1060 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1061 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1062 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +00001063 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001064 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 continue;
1066 }
1067 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1068 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1069 // See if this is an explicit destination.
1070 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1071 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +00001072 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +00001073 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001074 continue;
1075 }
1076
1077 // Otherwise it is the default destination.
1078 Worklist.push_back(SI->getSuccessor(0));
1079 continue;
1080 }
1081 }
1082
1083 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1084 Worklist.push_back(TI->getSuccessor(i));
1085 }
Chris Lattnerb5663c72009-10-12 03:58:40 +00001086
1087 // Once we've found all of the instructions to add to instcombine's worklist,
1088 // add them in reverse order. This way instcombine will visit from the top
1089 // of the function down. This jives well with the way that it adds all uses
1090 // of instructions to the worklist after doing a transformation, thus avoiding
1091 // some N^2 behavior in pathological cases.
1092 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1093 InstrsForInstCombineWorklist.size());
Chris Lattnerc4269e52009-10-15 04:59:28 +00001094
1095 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096}
1097
1098bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattner21d79e22009-08-31 06:57:37 +00001099 MadeIRChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
Daniel Dunbar005975c2009-07-25 00:23:56 +00001101 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1102 << F.getNameStr() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001103
1104 {
1105 // Do a depth-first traversal of the function, populate the worklist with
1106 // the reachable instructions. Ignore blocks that are not reachable. Keep
1107 // track of which blocks we visit.
1108 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerc4269e52009-10-15 04:59:28 +00001109 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110
1111 // Do a quick scan over the function. If we find any blocks that are
1112 // unreachable, remove any instructions inside of them. This prevents
1113 // the instcombine code from having to deal with some bad special cases.
1114 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1115 if (!Visited.count(BB)) {
1116 Instruction *Term = BB->getTerminator();
1117 while (Term != BB->begin()) { // Remove instrs bottom-up
1118 BasicBlock::iterator I = Term; --I;
1119
Chris Lattner8a6411c2009-08-23 04:37:46 +00001120 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesendf356c62009-03-10 21:19:49 +00001121 // A debug intrinsic shouldn't force another iteration if we weren't
1122 // going to do one without it.
1123 if (!isa<DbgInfoIntrinsic>(I)) {
1124 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00001125 MadeIRChange = true;
Dale Johannesendf356c62009-03-10 21:19:49 +00001126 }
Devang Patele3829c82009-10-13 22:56:32 +00001127
Devang Patele3829c82009-10-13 22:56:32 +00001128 // If I is not void type then replaceAllUsesWith undef.
1129 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patele9d08b82009-10-14 17:29:00 +00001130 if (!I->getType()->isVoidTy())
Devang Patele3829c82009-10-13 22:56:32 +00001131 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001132 I->eraseFromParent();
1133 }
1134 }
1135 }
1136
Chris Lattner5119c702009-08-30 05:55:36 +00001137 while (!Worklist.isEmpty()) {
1138 Instruction *I = Worklist.RemoveOne();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001139 if (I == 0) continue; // skip null values.
1140
1141 // Check to see if we can DCE the instruction.
1142 if (isInstructionTriviallyDead(I)) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001143 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner3183fb62009-08-30 06:13:40 +00001144 EraseInstFromFunction(*I);
1145 ++NumDeadInst;
Chris Lattner21d79e22009-08-31 06:57:37 +00001146 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001147 continue;
1148 }
1149
1150 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattneree5839b2009-10-15 04:13:44 +00001151 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner6070c012009-11-06 04:27:31 +00001152 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattneree5839b2009-10-15 04:13:44 +00001153 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154
Chris Lattneree5839b2009-10-15 04:13:44 +00001155 // Add operands to the worklist.
1156 ReplaceInstUsesWith(*I, C);
1157 ++NumConstProp;
1158 EraseInstFromFunction(*I);
1159 MadeIRChange = true;
1160 continue;
1161 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001162
1163 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +00001164 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 BasicBlock *BB = I->getParent();
Chris Lattnerf27a0432009-10-14 15:21:58 +00001166 Instruction *UserInst = cast<Instruction>(I->use_back());
1167 BasicBlock *UserParent;
1168
1169 // Get the block the use occurs in.
1170 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1171 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1172 else
1173 UserParent = UserInst->getParent();
1174
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 if (UserParent != BB) {
1176 bool UserIsSuccessor = false;
1177 // See if the user is one of our successors.
1178 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1179 if (*SI == UserParent) {
1180 UserIsSuccessor = true;
1181 break;
1182 }
1183
1184 // If the user is one of our immediate successors, and if that successor
1185 // only has us as a predecessors (we'd have to split the critical edge
1186 // otherwise), we can keep going.
Chris Lattnerf27a0432009-10-14 15:21:58 +00001187 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattner21d79e22009-08-31 06:57:37 +00001189 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001190 }
1191 }
1192
Chris Lattnerc7694852009-08-30 07:44:24 +00001193 // Now that we have an instruction, try combining it to simplify it.
1194 Builder->SetInsertPoint(I->getParent(), I);
1195
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196#ifndef NDEBUG
1197 std::string OrigI;
1198#endif
Chris Lattner8a6411c2009-08-23 04:37:46 +00001199 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin17091f02009-10-08 00:12:24 +00001200 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1201
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001202 if (Instruction *Result = visit(*I)) {
1203 ++NumCombined;
1204 // Should we replace the old instruction with a new one?
1205 if (Result != I) {
Chris Lattner8a6411c2009-08-23 04:37:46 +00001206 DEBUG(errs() << "IC: Old = " << *I << '\n'
1207 << " New = " << *Result << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001208
1209 // Everything uses the new instruction now.
1210 I->replaceAllUsesWith(Result);
1211
1212 // Push the new instruction and any users onto the worklist.
Chris Lattner3183fb62009-08-30 06:13:40 +00001213 Worklist.Add(Result);
Chris Lattner4796b622009-08-30 06:22:51 +00001214 Worklist.AddUsersToWorkList(*Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001215
1216 // Move the name to the new instruction first.
1217 Result->takeName(I);
1218
1219 // Insert the new instruction into the basic block...
1220 BasicBlock *InstParent = I->getParent();
1221 BasicBlock::iterator InsertPos = I;
1222
1223 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1224 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1225 ++InsertPos;
1226
1227 InstParent->getInstList().insert(InsertPos, Result);
1228
Chris Lattner3183fb62009-08-30 06:13:40 +00001229 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001230 } else {
1231#ifndef NDEBUG
Chris Lattner8a6411c2009-08-23 04:37:46 +00001232 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1233 << " New = " << *I << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234#endif
1235
1236 // If the instruction was modified, it's possible that it is now dead.
1237 // if so, remove it.
1238 if (isInstructionTriviallyDead(I)) {
Chris Lattner3183fb62009-08-30 06:13:40 +00001239 EraseInstFromFunction(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001240 } else {
Chris Lattner3183fb62009-08-30 06:13:40 +00001241 Worklist.Add(I);
Chris Lattner4796b622009-08-30 06:22:51 +00001242 Worklist.AddUsersToWorkList(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001243 }
1244 }
Chris Lattner21d79e22009-08-31 06:57:37 +00001245 MadeIRChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 }
1247 }
1248
Chris Lattner5119c702009-08-30 05:55:36 +00001249 Worklist.Zap();
Chris Lattner21d79e22009-08-31 06:57:37 +00001250 return MadeIRChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251}
1252
1253
1254bool InstCombiner::runOnFunction(Function &F) {
1255 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattneree5839b2009-10-15 04:13:44 +00001256 TD = getAnalysisIfAvailable<TargetData>();
1257
Chris Lattnerc7694852009-08-30 07:44:24 +00001258
1259 /// Builder - This is an IRBuilder that automatically inserts new
1260 /// instructions into the worklist when they are created.
Chris Lattneree5839b2009-10-15 04:13:44 +00001261 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattner002e65d2009-11-06 05:59:53 +00001262 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattnerc7694852009-08-30 07:44:24 +00001263 InstCombineIRInserter(Worklist));
1264 Builder = &TheBuilder;
1265
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001266 bool EverMadeChange = false;
1267
1268 // Iterate while there is work to do.
1269 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +00001270 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 EverMadeChange = true;
Chris Lattnerc7694852009-08-30 07:44:24 +00001272
1273 Builder = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 return EverMadeChange;
1275}
1276
1277FunctionPass *llvm::createInstructionCombiningPass() {
1278 return new InstCombiner();
1279}