blob: 84d85b73c63f774ff5ea9d8d3e72f0a26284d03e [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 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.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000040#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000041#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000042#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000045#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000048#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000049#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000051#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000052#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000053#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000056
Chris Lattner0e5f4992006-12-19 21:40:18 +000057STATISTIC(NumCombined , "Number of insts combined");
58STATISTIC(NumConstProp, "Number of constant folds");
59STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000061STATISTIC(NumFactor , "Number of factorizations");
62STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000063
Owen Anderson74cfb0c2010-10-07 20:04:55 +000064// Initialization Routines
65void llvm::initializeInstCombine(PassRegistry &Registry) {
66 initializeInstCombinerPass(Registry);
67}
68
69void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
70 initializeInstCombine(*unwrap(R));
71}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000072
Dan Gohman844731a2008-05-13 00:00:25 +000073char InstCombiner::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000074INITIALIZE_PASS(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000075 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000076
Chris Lattnere0b4b722010-01-04 07:17:19 +000077void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
78 AU.addPreservedID(LCSSAID);
79 AU.setPreservesCFG();
80}
81
82
Chris Lattnerc22d4d12009-11-10 07:23:37 +000083/// ShouldChangeType - Return true if it is desirable to convert a computation
84/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
85/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000086bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000087 assert(From->isIntegerTy() && To->isIntegerTy());
Chris Lattnerc22d4d12009-11-10 07:23:37 +000088
89 // If we don't have TD, we don't know if the source/dest are legal.
90 if (!TD) return false;
91
92 unsigned FromWidth = From->getPrimitiveSizeInBits();
93 unsigned ToWidth = To->getPrimitiveSizeInBits();
94 bool FromLegal = TD->isLegalInteger(FromWidth);
95 bool ToLegal = TD->isLegalInteger(ToWidth);
96
97 // If this is a legal integer from type, and the result would be an illegal
98 // type, don't do the transformation.
99 if (FromLegal && !ToLegal)
100 return false;
101
102 // Otherwise, if both are illegal, do not increase the size of the result. We
103 // do allow things like i160 -> i64, but not i64 -> i160.
104 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
105 return false;
106
107 return true;
108}
109
Chris Lattner33a61132006-05-06 09:00:16 +0000110
Duncan Sands096aa792010-11-13 15:10:37 +0000111/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
112/// operators which are associative or commutative:
113//
114// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115//
Chris Lattner4f98c562003-03-10 21:43:22 +0000116// 1. Order operands such that they are listed from right (least complex) to
117// left (most complex). This puts constants before unary operators before
118// binary operators.
119//
Duncan Sands096aa792010-11-13 15:10:37 +0000120// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000121//
Duncan Sands096aa792010-11-13 15:10:37 +0000122// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
123// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
124//
125// Associative and commutative operators:
126//
127// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
128// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
129// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
130// if C1 and C2 are constants.
131//
132bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000133 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000134 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000135
Duncan Sands096aa792010-11-13 15:10:37 +0000136 do {
137 // Order operands such that they are listed from right (least complex) to
138 // left (most complex). This puts constants before unary operators before
139 // binary operators.
140 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
141 getComplexity(I.getOperand(1)))
142 Changed = !I.swapOperands();
143
144 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
145 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
146
147 if (I.isAssociative()) {
148 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
149 if (Op0 && Op0->getOpcode() == Opcode) {
150 Value *A = Op0->getOperand(0);
151 Value *B = Op0->getOperand(1);
152 Value *C = I.getOperand(1);
153
154 // Does "B op C" simplify?
155 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
156 // It simplifies to V. Form "A op V".
157 I.setOperand(0, A);
158 I.setOperand(1, V);
159 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000160 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000161 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000162 }
Duncan Sands096aa792010-11-13 15:10:37 +0000163 }
164
165 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
166 if (Op1 && Op1->getOpcode() == Opcode) {
167 Value *A = I.getOperand(0);
168 Value *B = Op1->getOperand(0);
169 Value *C = Op1->getOperand(1);
170
171 // Does "A op B" simplify?
172 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
173 // It simplifies to V. Form "V op C".
174 I.setOperand(0, V);
175 I.setOperand(1, C);
176 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000177 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000178 continue;
179 }
180 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000181 }
Duncan Sands096aa792010-11-13 15:10:37 +0000182
183 if (I.isAssociative() && I.isCommutative()) {
184 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
185 if (Op0 && Op0->getOpcode() == Opcode) {
186 Value *A = Op0->getOperand(0);
187 Value *B = Op0->getOperand(1);
188 Value *C = I.getOperand(1);
189
190 // Does "C op A" simplify?
191 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
192 // It simplifies to V. Form "V op B".
193 I.setOperand(0, V);
194 I.setOperand(1, B);
195 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000196 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000197 continue;
198 }
199 }
200
201 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
202 if (Op1 && Op1->getOpcode() == Opcode) {
203 Value *A = I.getOperand(0);
204 Value *B = Op1->getOperand(0);
205 Value *C = Op1->getOperand(1);
206
207 // Does "C op A" simplify?
208 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
209 // It simplifies to V. Form "B op V".
210 I.setOperand(0, B);
211 I.setOperand(1, V);
212 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000213 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000214 continue;
215 }
216 }
217
218 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
219 // if C1 and C2 are constants.
220 if (Op0 && Op1 &&
221 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
222 isa<Constant>(Op0->getOperand(1)) &&
223 isa<Constant>(Op1->getOperand(1)) &&
224 Op0->hasOneUse() && Op1->hasOneUse()) {
225 Value *A = Op0->getOperand(0);
226 Constant *C1 = cast<Constant>(Op0->getOperand(1));
227 Value *B = Op1->getOperand(0);
228 Constant *C2 = cast<Constant>(Op1->getOperand(1));
229
230 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
231 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
232 &I);
233 Worklist.Add(New);
234 I.setOperand(0, New);
235 I.setOperand(1, Folded);
236 Changed = true;
237 continue;
238 }
239 }
240
241 // No further simplifications.
242 return Changed;
243 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000244}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000245
Duncan Sands5057f382010-11-23 14:23:47 +0000246/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000247/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000248static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
249 Instruction::BinaryOps ROp) {
250 switch (LOp) {
251 default:
252 return false;
253
254 case Instruction::And:
255 // And distributes over Or and Xor.
256 switch (ROp) {
257 default:
258 return false;
259 case Instruction::Or:
260 case Instruction::Xor:
261 return true;
262 }
263
264 case Instruction::Mul:
265 // Multiplication distributes over addition and subtraction.
266 switch (ROp) {
267 default:
268 return false;
269 case Instruction::Add:
270 case Instruction::Sub:
271 return true;
272 }
273
274 case Instruction::Or:
275 // Or distributes over And.
276 switch (ROp) {
277 default:
278 return false;
279 case Instruction::And:
280 return true;
281 }
282 }
283}
284
285/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
286/// "(X ROp Z) LOp (Y ROp Z)".
287static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
288 Instruction::BinaryOps ROp) {
289 if (Instruction::isCommutative(ROp))
290 return LeftDistributesOverRight(ROp, LOp);
291 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
292 // but this requires knowing that the addition does not overflow and other
293 // such subtleties.
294 return false;
295}
296
Duncan Sands50f26252010-11-23 20:42:39 +0000297/// SimplifyByFactorizing - This tries to simplify binary operations which
298/// some other binary operation distributes over by factorizing out a common
299/// term (eg "(A*B)+(A*C)" -> "A*(B+C)"). Returns the simplified value, or
300/// null if no simplification was performed.
301Instruction *InstCombiner::SimplifyByFactorizing(BinaryOperator &I) {
Duncan Sands5057f382010-11-23 14:23:47 +0000302 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
303 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
304 if (!Op0 || !Op1 || Op0->getOpcode() != Op1->getOpcode())
305 return 0;
306
307 // The instruction has the form "(A op' B) op (C op' D)".
308 Value *A = Op0->getOperand(0); Value *B = Op0->getOperand(1);
309 Value *C = Op1->getOperand(0); Value *D = Op1->getOperand(1);
310 Instruction::BinaryOps OuterOpcode = I.getOpcode(); // op
311 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
312
Duncan Sands5057f382010-11-23 14:23:47 +0000313 // Does "X op' Y" always equal "Y op' X"?
314 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
315
Duncan Sandse104f1b2010-11-23 15:28:14 +0000316 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
317 if (LeftDistributesOverRight(InnerOpcode, OuterOpcode))
Duncan Sands5057f382010-11-23 14:23:47 +0000318 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
319 // commutative case, "(A op' B) op (C op' A)"?
320 if (A == C || (InnerCommutative && A == D)) {
321 if (A != C)
322 std::swap(C, D);
323 // Consider forming "A op' (B op D)".
324 // If "B op D" simplifies then it can be formed with no cost.
325 Value *RHS = SimplifyBinOp(OuterOpcode, B, D, TD);
326 // If "B op D" doesn't simplify then only proceed if both of the existing
327 // operations "A op' B" and "C op' D" will be zapped since no longer used.
328 if (!RHS && Op0->hasOneUse() && Op1->hasOneUse())
329 RHS = Builder->CreateBinOp(OuterOpcode, B, D, Op1->getName());
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000330 if (RHS) {
331 ++NumFactor;
Duncan Sands5057f382010-11-23 14:23:47 +0000332 return BinaryOperator::Create(InnerOpcode, A, RHS);
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000333 }
Duncan Sands5057f382010-11-23 14:23:47 +0000334 }
335
Duncan Sandse104f1b2010-11-23 15:28:14 +0000336 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
337 if (RightDistributesOverLeft(OuterOpcode, InnerOpcode))
Duncan Sands5057f382010-11-23 14:23:47 +0000338 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
339 // commutative case, "(A op' B) op (B op' D)"?
340 if (B == D || (InnerCommutative && B == C)) {
341 if (B != D)
342 std::swap(C, D);
343 // Consider forming "(A op C) op' B".
344 // If "A op C" simplifies then it can be formed with no cost.
345 Value *LHS = SimplifyBinOp(OuterOpcode, A, C, TD);
346 // If "A op C" doesn't simplify then only proceed if both of the existing
347 // operations "A op' B" and "C op' D" will be zapped since no longer used.
348 if (!LHS && Op0->hasOneUse() && Op1->hasOneUse())
349 LHS = Builder->CreateBinOp(OuterOpcode, A, C, Op0->getName());
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000350 if (LHS) {
351 ++NumFactor;
Duncan Sands5057f382010-11-23 14:23:47 +0000352 return BinaryOperator::Create(InnerOpcode, LHS, B);
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000353 }
Duncan Sands5057f382010-11-23 14:23:47 +0000354 }
355
356 return 0;
357}
358
Chris Lattner8d969642003-03-10 23:06:50 +0000359// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
360// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000361//
Chris Lattner02446fc2010-01-04 07:37:31 +0000362Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000363 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000364 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000365
Chris Lattner0ce85802004-12-14 20:08:06 +0000366 // Constants can be considered to be negated values if they can be folded.
367 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000368 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000369
370 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000371 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000372 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000373
Chris Lattner8d969642003-03-10 23:06:50 +0000374 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000375}
376
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000377// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
378// instruction if the LHS is a constant negative zero (which is the 'negate'
379// form).
380//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000381Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000382 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000383 return BinaryOperator::getFNegArgument(V);
384
385 // Constants can be considered to be negated values if they can be folded.
386 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000387 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000388
389 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000390 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000391 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000392
393 return 0;
394}
395
Chris Lattner6e7ba452005-01-01 16:22:27 +0000396static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000397 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000398 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000399 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000400
Chris Lattner2eefe512004-04-09 19:05:30 +0000401 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000402 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
403 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000404
Chris Lattner2eefe512004-04-09 19:05:30 +0000405 if (Constant *SOC = dyn_cast<Constant>(SO)) {
406 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000407 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
408 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000409 }
410
411 Value *Op0 = SO, *Op1 = ConstOperand;
412 if (!ConstIsRHS)
413 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000414
Chris Lattner6e7ba452005-01-01 16:22:27 +0000415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000416 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
417 SO->getName()+".op");
418 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
419 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
420 SO->getName()+".cmp");
421 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
422 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
423 SO->getName()+".cmp");
424 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000425}
426
427// FoldOpIntoSelect - Given an instruction with a select as one operand and a
428// constant as the other operand, try to fold the binary operator into the
429// select arguments. This also works for Cast instructions, which obviously do
430// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000431Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000432 // Don't modify shared select instructions
433 if (!SI->hasOneUse()) return 0;
434 Value *TV = SI->getOperand(1);
435 Value *FV = SI->getOperand(2);
436
437 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000438 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000439 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000440
Chris Lattner80f43d32010-01-04 07:53:58 +0000441 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
442 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000443
Gabor Greif051a9502008-04-06 20:25:17 +0000444 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
445 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000446 }
447 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000448}
449
Chris Lattner4e998b22004-09-29 05:07:12 +0000450
Chris Lattner5d1704d2009-09-27 19:57:57 +0000451/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
452/// has a PHI node as operand #0, see if we can fold the instruction into the
453/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000454///
455/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
456/// that would normally be unprofitable because they strongly encourage jump
457/// threading.
458Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
459 bool AllowAggressive) {
460 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000461 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000462 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000463 if (NumPHIValues == 0 ||
464 // We normally only transform phis with a single use, unless we're trying
465 // hard to make jump threading happen.
466 (!PN->hasOneUse() && !AllowAggressive))
467 return 0;
468
469
Chris Lattner5d1704d2009-09-27 19:57:57 +0000470 // Check to see if all of the operands of the PHI are simple constants
471 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000472 // remember the BB it is in. If there is more than one or if *it* is a PHI,
473 // bail out. We don't do arbitrary constant expressions here because moving
474 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000475 BasicBlock *NonConstBB = 0;
476 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000477 if (!isa<Constant>(PN->getIncomingValue(i)) ||
478 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000479 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000480 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000481 NonConstBB = PN->getIncomingBlock(i);
482
483 // If the incoming non-constant value is in I's block, we have an infinite
484 // loop.
485 if (NonConstBB == I.getParent())
486 return 0;
487 }
488
489 // If there is exactly one non-constant value, we can insert a copy of the
490 // operation in that block. However, if this is a critical edge, we would be
491 // inserting the computation one some other paths (e.g. inside a loop). Only
492 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000493 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000494 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
495 if (!BI || !BI->isUnconditional()) return 0;
496 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000497
498 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000499 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000500 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000501 InsertNewInstBefore(NewPN, *PN);
502 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000503
504 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000505 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
506 // We only currently try to fold the condition of a select when it is a phi,
507 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000508 Value *TrueV = SI->getTrueValue();
509 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000510 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000511 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000512 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000513 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
514 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000515 Value *InV = 0;
516 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000517 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000518 } else {
519 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000520 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
521 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000522 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000523 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000524 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000525 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000526 }
527 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000528 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000529 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000530 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000531 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000533 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000534 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000535 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000536 } else {
537 assert(PN->getIncomingBlock(i) == NonConstBB);
538 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000539 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000540 PN->getIncomingValue(i), C, "phitmp",
541 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000542 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000543 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000544 CI->getPredicate(),
545 PN->getIncomingValue(i), C, "phitmp",
546 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000547 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000548 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000549
550 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000551 }
552 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000553 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000554 } else {
555 CastInst *CI = cast<CastInst>(&I);
556 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000557 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000558 Value *InV;
559 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000560 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000561 } else {
562 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000563 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000564 I.getType(), "phitmp",
565 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000566 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000567 }
568 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000569 }
570 }
571 return ReplaceInstUsesWith(I, NewPN);
572}
573
Chris Lattner46cd5a12009-01-09 05:44:56 +0000574/// FindElementAtOffset - Given a type and a constant offset, determine whether
575/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000576/// the specified offset. If so, fill them into NewIndices and return the
577/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +0000578const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
579 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000580 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000581 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000582
583 // Start with the index over the outer type. Note that the type size
584 // might be zero (even if the offset isn't zero) if the indexed type
585 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +0000586 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000587 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000588 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000589 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000590 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000591
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000592 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000593 if (Offset < 0) {
594 --FirstIdx;
595 Offset += TySize;
596 assert(Offset >= 0);
597 }
598 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
599 }
600
Owen Andersoneed707b2009-07-24 23:12:02 +0000601 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000602
603 // Index into the types. If we fail, set OrigBase to null.
604 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000605 // Indexing into tail padding between struct/array elements.
606 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000607 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000608
Chris Lattner46cd5a12009-01-09 05:44:56 +0000609 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
610 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000611 assert(Offset < (int64_t)SL->getSizeInBytes() &&
612 "Offset must stay within the indexed type");
613
Chris Lattner46cd5a12009-01-09 05:44:56 +0000614 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000615 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
616 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000617
618 Offset -= SL->getElementOffset(Elt);
619 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +0000620 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000621 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000622 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000623 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000624 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000625 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000626 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000627 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000628 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000629 }
630 }
631
Chris Lattner3914f722009-01-24 01:00:13 +0000632 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000633}
634
Chris Lattner8a2a3112001-12-14 16:52:21 +0000635
Chris Lattner473945d2002-05-06 18:06:38 +0000636
Chris Lattner7e708292002-06-25 16:13:24 +0000637Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000638 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
639
640 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
641 return ReplaceInstUsesWith(GEP, V);
642
Chris Lattner620ce142004-05-07 22:09:22 +0000643 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000644
Duncan Sandsa63395a2010-11-22 16:32:50 +0000645 // Eliminate unneeded casts for indices, and replace indices which displace
646 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000647 if (TD) {
648 bool MadeChange = false;
Duncan Sandsa63395a2010-11-22 16:32:50 +0000649 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
650
Chris Lattnerccf4b342009-08-30 04:49:01 +0000651 gep_type_iterator GTI = gep_type_begin(GEP);
652 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
653 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000654 // Skip indices into struct types.
655 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
656 if (!SeqTy) continue;
657
658 // If the element type has zero size then any index over it is equivalent
659 // to an index of zero, so replace it with zero if it is not zero already.
660 if (SeqTy->getElementType()->isSized() &&
661 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
662 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
663 *I = Constant::getNullValue(IntPtrTy);
664 MadeChange = true;
665 }
666
667 if ((*I)->getType() != IntPtrTy) {
668 // If we are using a wider index than needed for this platform, shrink
669 // it to what we need. If narrower, sign-extend it to what we need.
670 // This explicit cast can make subsequent optimizations more obvious.
671 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
672 MadeChange = true;
673 }
Chris Lattner28977af2004-04-05 01:30:19 +0000674 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000675 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000676 }
Chris Lattner28977af2004-04-05 01:30:19 +0000677
Chris Lattner90ac28c2002-08-02 19:29:35 +0000678 // Combine Indices - If the source pointer to this getelementptr instruction
679 // is a getelementptr instruction, combine the indices of the two
680 // getelementptr instructions into a single instruction.
681 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000682 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +0000683 // Note that if our source is a gep chain itself that we wait for that
684 // chain to be resolved before we perform this transformation. This
685 // avoids us creating a TON of code in some cases.
686 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000687 if (GetElementPtrInst *SrcGEP =
688 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
689 if (SrcGEP->getNumOperands() == 2)
690 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000691
Chris Lattner72588fc2007-02-15 22:48:32 +0000692 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000693
694 // Find out whether the last index in the source GEP is a sequential idx.
695 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000696 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
697 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000698 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000699
Chris Lattner90ac28c2002-08-02 19:29:35 +0000700 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000701 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000702 // Replace: gep (gep %P, long B), long A, ...
703 // With: T = long A+B; gep %P, T, ...
704 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000705 Value *Sum;
706 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
707 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000708 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000709 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000710 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000711 Sum = SO1;
712 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000713 // If they aren't the same type, then the input hasn't been processed
714 // by the loop above yet (which canonicalizes sequential index types to
715 // intptr_t). Just avoid transforming this until the input has been
716 // normalized.
717 if (SO1->getType() != GO1->getType())
718 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000719 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000720 }
Chris Lattner620ce142004-05-07 22:09:22 +0000721
Chris Lattnerab984842009-08-30 05:30:55 +0000722 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000723 if (Src->getNumOperands() == 2) {
724 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000725 GEP.setOperand(1, Sum);
726 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000727 }
Chris Lattnerab984842009-08-30 05:30:55 +0000728 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000729 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000730 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000731 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000732 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000733 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000734 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000735 Indices.append(Src->op_begin()+1, Src->op_end());
736 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000737 }
738
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000739 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000740 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000741 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
742 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000743 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +0000744 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000745 }
746
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000747 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000748 Value *StrippedPtr = PtrOp->stripPointerCasts();
749 if (StrippedPtr != PtrOp) {
750 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattner963f4ba2009-08-30 20:36:46 +0000751
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000752 bool HasZeroPointerIndex = false;
753 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
754 HasZeroPointerIndex = C->isZero();
755
Chris Lattner963f4ba2009-08-30 20:36:46 +0000756 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
757 // into : GEP [10 x i8]* X, i32 0, ...
758 //
759 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
760 // into : GEP i8* X, ...
761 //
762 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000763 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +0000764 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000765 if (const ArrayType *CATy =
766 dyn_cast<ArrayType>(CPTy->getElementType())) {
767 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000768 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000769 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000770 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
771 GetElementPtrInst *Res =
772 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
773 Idx.end(), GEP.getName());
774 Res->setIsInBounds(GEP.isInBounds());
775 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000776 }
777
Chris Lattner948cdeb2010-01-05 07:42:10 +0000778 if (const ArrayType *XATy =
779 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000780 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000781 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000782 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000783 // At this point, we know that the cast source type is a pointer
784 // to an array of the same type as the destination pointer
785 // array. Because the array type is never stepped over (there
786 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000787 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000788 return &GEP;
789 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000790 }
791 }
Chris Lattnereed48272005-09-13 00:40:14 +0000792 } else if (GEP.getNumOperands() == 2) {
793 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000794 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
795 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner948cdeb2010-01-05 07:42:10 +0000796 const Type *SrcElTy = StrippedPtrTy->getElementType();
Chris Lattnereed48272005-09-13 00:40:14 +0000797 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000798 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000799 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
800 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000801 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000802 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000803 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000804 Value *NewGEP = GEP.isInBounds() ?
805 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
806 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000807 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000808 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000809 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000810
811 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000812 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000813 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000814 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000815
Duncan Sands1df98592010-02-16 11:11:14 +0000816 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000817 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000818 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000819
820 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
821 // allow either a mul, shift, or constant here.
822 Value *NewIdx = 0;
823 ConstantInt *Scale = 0;
824 if (ArrayEltSize == 1) {
825 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000826 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000827 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000828 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000829 Scale = CI;
830 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
831 if (Inst->getOpcode() == Instruction::Shl &&
832 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000833 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
834 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000835 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000836 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000837 NewIdx = Inst->getOperand(0);
838 } else if (Inst->getOpcode() == Instruction::Mul &&
839 isa<ConstantInt>(Inst->getOperand(1))) {
840 Scale = cast<ConstantInt>(Inst->getOperand(1));
841 NewIdx = Inst->getOperand(0);
842 }
843 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000844
Chris Lattner7835cdd2005-09-13 18:36:04 +0000845 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000846 // out, perform the transformation. Note, we don't know whether Scale is
847 // signed or not. We'll use unsigned version of division/modulo
848 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +0000849 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000850 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000851 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000852 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +0000853 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +0000854 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
855 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000856 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +0000857 }
858
859 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +0000860 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000861 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000862 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +0000863 Value *NewGEP = GEP.isInBounds() ?
864 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
865 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000866 // The NewGEP must be pointer typed, so must the old one -> BitCast
867 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000868 }
869 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000870 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000871 }
Chris Lattner58407792009-01-09 04:53:57 +0000872
Chris Lattner46cd5a12009-01-09 05:44:56 +0000873 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +0000874 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +0000875 /// Y = gep X, <...constant indices...>
876 /// into a gep of the original struct. This is important for SROA and alias
877 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +0000878 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000879 if (TD &&
880 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000881 // Determine how much the GEP moves the pointer. We are guaranteed to get
882 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +0000883 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000884 int64_t Offset = OffsetV->getSExtValue();
885
886 // If this GEP instruction doesn't move the pointer, just replace the GEP
887 // with a bitcast of the real input to the dest type.
888 if (Offset == 0) {
889 // If the bitcast is of an allocation, and the allocation will be
890 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000891 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +0000892 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000893 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
894 if (Instruction *I = visitBitCast(*BCI)) {
895 if (I != BCI) {
896 I->takeName(BCI);
897 BCI->getParent()->getInstList().insert(BCI, I);
898 ReplaceInstUsesWith(*BCI, I);
899 }
900 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +0000901 }
Chris Lattner58407792009-01-09 04:53:57 +0000902 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000903 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +0000904 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000905
906 // Otherwise, if the offset is non-zero, we need to find out if there is a
907 // field at Offset in 'A's type. If so, we can pull the cast through the
908 // GEP.
909 SmallVector<Value*, 8> NewIndices;
910 const Type *InTy =
911 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000912 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +0000913 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000914 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
915 NewIndices.end()) :
916 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
917 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000918
919 if (NGEP->getType() == GEP.getType())
920 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +0000921 NGEP->takeName(&GEP);
922 return new BitCastInst(NGEP, GEP.getType());
923 }
Chris Lattner58407792009-01-09 04:53:57 +0000924 }
925 }
926
Chris Lattner8a2a3112001-12-14 16:52:21 +0000927 return 0;
928}
929
Duncan Sands1d9b9732010-05-27 19:09:06 +0000930
931
932static bool IsOnlyNullComparedAndFreed(const Value &V) {
933 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
934 UI != UE; ++UI) {
Gabor Greiffc36c0f2010-07-09 15:01:36 +0000935 const User *U = *UI;
936 if (isFreeCall(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +0000937 continue;
Gabor Greiffc36c0f2010-07-09 15:01:36 +0000938 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +0000939 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
940 continue;
941 return false;
942 }
943 return true;
944}
945
946Instruction *InstCombiner::visitMalloc(Instruction &MI) {
947 // If we have a malloc call which is only used in any amount of comparisons
948 // to null and free calls, delete the calls and replace the comparisons with
949 // true or false as appropriate.
950 if (IsOnlyNullComparedAndFreed(MI)) {
951 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
952 UI != UE;) {
953 // We can assume that every remaining use is a free call or an icmp eq/ne
954 // to null, so the cast is safe.
955 Instruction *I = cast<Instruction>(*UI);
956
957 // Early increment here, as we're about to get rid of the user.
958 ++UI;
959
960 if (isFreeCall(I)) {
961 EraseInstFromFunction(*cast<CallInst>(I));
962 continue;
963 }
964 // Again, the cast is safe.
965 ICmpInst *C = cast<ICmpInst>(I);
966 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
967 C->isFalseWhenEqual()));
968 EraseInstFromFunction(*C);
969 }
970 return EraseInstFromFunction(MI);
971 }
972 return 0;
973}
974
975
976
Gabor Greif91697372010-06-24 12:21:15 +0000977Instruction *InstCombiner::visitFree(CallInst &FI) {
978 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +0000979
980 // free undef -> unreachable.
981 if (isa<UndefValue>(Op)) {
982 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +0000983 new StoreInst(ConstantInt::getTrue(FI.getContext()),
984 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000985 return EraseInstFromFunction(FI);
986 }
987
988 // If we have 'free null' delete the instruction. This can happen in stl code
989 // when lots of inlining happens.
990 if (isa<ConstantPointerNull>(Op))
991 return EraseInstFromFunction(FI);
992
Victor Hernandez66284e02009-10-24 04:23:03 +0000993 return 0;
994}
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000995
Chris Lattner3284d1f2007-04-15 00:07:55 +0000996
Chris Lattner2f503e62005-01-31 05:36:43 +0000997
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000998Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
999 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001000 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001001 BasicBlock *TrueDest;
1002 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001003 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001004 !isa<Constant>(X)) {
1005 // Swap Destinations and condition...
1006 BI.setCondition(X);
1007 BI.setSuccessor(0, FalseDest);
1008 BI.setSuccessor(1, TrueDest);
1009 return &BI;
1010 }
1011
Reid Spencere4d87aa2006-12-23 06:05:41 +00001012 // Cannonicalize fcmp_one -> fcmp_oeq
1013 FCmpInst::Predicate FPred; Value *Y;
1014 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001015 TrueDest, FalseDest)) &&
1016 BI.getCondition()->hasOneUse())
1017 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1018 FPred == FCmpInst::FCMP_OGE) {
1019 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1020 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1021
1022 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001023 BI.setSuccessor(0, FalseDest);
1024 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001025 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001026 return &BI;
1027 }
1028
1029 // Cannonicalize icmp_ne -> icmp_eq
1030 ICmpInst::Predicate IPred;
1031 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001032 TrueDest, FalseDest)) &&
1033 BI.getCondition()->hasOneUse())
1034 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1035 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1036 IPred == ICmpInst::ICMP_SGE) {
1037 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1038 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1039 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00001040 BI.setSuccessor(0, FalseDest);
1041 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001042 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001043 return &BI;
1044 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001045
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001046 return 0;
1047}
Chris Lattner0864acf2002-11-04 16:18:53 +00001048
Chris Lattner46238a62004-07-03 00:26:11 +00001049Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1050 Value *Cond = SI.getCondition();
1051 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1052 if (I->getOpcode() == Instruction::Add)
1053 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1054 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1055 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00001056 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00001057 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00001058 AddRHS));
1059 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001060 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001061 return &SI;
1062 }
1063 }
1064 return 0;
1065}
1066
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001067Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001068 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001069
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001070 if (!EV.hasIndices())
1071 return ReplaceInstUsesWith(EV, Agg);
1072
1073 if (Constant *C = dyn_cast<Constant>(Agg)) {
1074 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001075 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001076
1077 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00001078 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001079
1080 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1081 // Extract the element indexed by the first index out of the constant
1082 Value *V = C->getOperand(*EV.idx_begin());
1083 if (EV.getNumIndices() > 1)
1084 // Extract the remaining indices out of the constant indexed by the
1085 // first index
1086 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1087 else
1088 return ReplaceInstUsesWith(EV, V);
1089 }
1090 return 0; // Can't handle other constants
1091 }
1092 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1093 // We're extracting from an insertvalue instruction, compare the indices
1094 const unsigned *exti, *exte, *insi, *inse;
1095 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1096 exte = EV.idx_end(), inse = IV->idx_end();
1097 exti != exte && insi != inse;
1098 ++exti, ++insi) {
1099 if (*insi != *exti)
1100 // The insert and extract both reference distinctly different elements.
1101 // This means the extract is not influenced by the insert, and we can
1102 // replace the aggregate operand of the extract with the aggregate
1103 // operand of the insert. i.e., replace
1104 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1105 // %E = extractvalue { i32, { i32 } } %I, 0
1106 // with
1107 // %E = extractvalue { i32, { i32 } } %A, 0
1108 return ExtractValueInst::Create(IV->getAggregateOperand(),
1109 EV.idx_begin(), EV.idx_end());
1110 }
1111 if (exti == exte && insi == inse)
1112 // Both iterators are at the end: Index lists are identical. Replace
1113 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1114 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1115 // with "i32 42"
1116 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1117 if (exti == exte) {
1118 // The extract list is a prefix of the insert list. i.e. replace
1119 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1120 // %E = extractvalue { i32, { i32 } } %I, 1
1121 // with
1122 // %X = extractvalue { i32, { i32 } } %A, 1
1123 // %E = insertvalue { i32 } %X, i32 42, 0
1124 // by switching the order of the insert and extract (though the
1125 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001126 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1127 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001128 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1129 insi, inse);
1130 }
1131 if (insi == inse)
1132 // The insert list is a prefix of the extract list
1133 // We can simply remove the common indices from the extract and make it
1134 // operate on the inserted value instead of the insertvalue result.
1135 // i.e., replace
1136 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1137 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1138 // with
1139 // %E extractvalue { i32 } { i32 42 }, 0
1140 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1141 exti, exte);
1142 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001143 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1144 // We're extracting from an intrinsic, see if we're the only user, which
1145 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001146 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001147 if (II->hasOneUse()) {
1148 // Check if we're grabbing the overflow bit or the result of a 'with
1149 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1150 // and replace it with a traditional binary instruction.
1151 switch (II->getIntrinsicID()) {
1152 case Intrinsic::uadd_with_overflow:
1153 case Intrinsic::sadd_with_overflow:
1154 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001155 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001156 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1157 EraseInstFromFunction(*II);
1158 return BinaryOperator::CreateAdd(LHS, RHS);
1159 }
Chris Lattner74b64612010-12-19 19:43:52 +00001160
1161 // If the normal result of the add is dead, and the RHS is a constant,
1162 // we can transform this into a range comparison.
1163 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001164 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1165 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1166 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1167 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001168 break;
1169 case Intrinsic::usub_with_overflow:
1170 case Intrinsic::ssub_with_overflow:
1171 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001172 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001173 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1174 EraseInstFromFunction(*II);
1175 return BinaryOperator::CreateSub(LHS, RHS);
1176 }
1177 break;
1178 case Intrinsic::umul_with_overflow:
1179 case Intrinsic::smul_with_overflow:
1180 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001181 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001182 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1183 EraseInstFromFunction(*II);
1184 return BinaryOperator::CreateMul(LHS, RHS);
1185 }
1186 break;
1187 default:
1188 break;
1189 }
1190 }
1191 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001192 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1193 // If the (non-volatile) load only has one use, we can rewrite this to a
1194 // load from a GEP. This reduces the size of the load.
1195 // FIXME: If a load is used only by extractvalue instructions then this
1196 // could be done regardless of having multiple uses.
1197 if (!L->isVolatile() && L->hasOneUse()) {
1198 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1199 SmallVector<Value*, 4> Indices;
1200 // Prefix an i32 0 since we need the first element.
1201 Indices.push_back(Builder->getInt32(0));
1202 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1203 I != E; ++I)
1204 Indices.push_back(Builder->getInt32(*I));
1205
1206 // We need to insert these at the location of the old load, not at that of
1207 // the extractvalue.
1208 Builder->SetInsertPoint(L->getParent(), L);
1209 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(),
1210 Indices.begin(), Indices.end());
1211 // Returning the load directly will cause the main loop to insert it in
1212 // the wrong spot, so use ReplaceInstUsesWith().
1213 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1214 }
1215 // We could simplify extracts from other values. Note that nested extracts may
1216 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001217 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001218 // the value inserted, if appropriate. Similarly for extracts from single-use
1219 // loads: extract (extract (load)) will be translated to extract (load (gep))
1220 // and if again single-use then via load (gep (gep)) to load (gep).
1221 // However, double extracts from e.g. function arguments or return values
1222 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001223 return 0;
1224}
1225
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001226
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001227
Chris Lattnerea1c4542004-12-08 23:43:58 +00001228
1229/// TryToSinkInstruction - Try to move the specified instruction from its
1230/// current block into the beginning of DestBlock, which can only happen if it's
1231/// safe to move the instruction past all of the instructions between it and the
1232/// end of its block.
1233static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1234 assert(I->hasOneUse() && "Invariants didn't hold!");
1235
Chris Lattner108e9022005-10-27 17:13:11 +00001236 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00001237 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001238 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001239
Chris Lattnerea1c4542004-12-08 23:43:58 +00001240 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001241 if (isa<AllocaInst>(I) && I->getParent() ==
1242 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001243 return false;
1244
Chris Lattner96a52a62004-12-09 07:14:34 +00001245 // We can only sink load instructions if there is nothing between the load and
1246 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001247 if (I->mayReadFromMemory()) {
1248 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001249 Scan != E; ++Scan)
1250 if (Scan->mayWriteToMemory())
1251 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001252 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001253
Dan Gohman02dea8b2008-05-23 21:05:58 +00001254 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00001255
Chris Lattner4bc5f802005-08-08 19:11:57 +00001256 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001257 ++NumSunkInst;
1258 return true;
1259}
1260
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001261
1262/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1263/// all reachable code to the worklist.
1264///
1265/// This has a couple of tricks to make the code faster and more powerful. In
1266/// particular, we constant fold and DCE instructions as we go, to avoid adding
1267/// them to the worklist (this significantly speeds up instcombine on code where
1268/// many instructions are dead or constant). Additionally, if we find a branch
1269/// whose condition is a known constant, we only visit the reachable successors.
1270///
Chris Lattner2ee743b2009-10-15 04:59:28 +00001271static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001272 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001273 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001274 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001275 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001276 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001277 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001278
Benjamin Kramera53fe602010-10-23 17:10:24 +00001279 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001280 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1281
Dan Gohman321a8132010-01-05 16:27:25 +00001282 do {
1283 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001284
1285 // We have now visited this block! If we've already been here, ignore it.
1286 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001287
Chris Lattner2c7718a2007-03-23 19:17:18 +00001288 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1289 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001290
Chris Lattner2c7718a2007-03-23 19:17:18 +00001291 // DCE instruction if trivially dead.
1292 if (isInstructionTriviallyDead(Inst)) {
1293 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001294 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001295 Inst->eraseFromParent();
1296 continue;
1297 }
1298
1299 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001300 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001301 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001302 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1303 << *Inst << '\n');
1304 Inst->replaceAllUsesWith(C);
1305 ++NumConstProp;
1306 Inst->eraseFromParent();
1307 continue;
1308 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001309
Chris Lattner2ee743b2009-10-15 04:59:28 +00001310 if (TD) {
1311 // See if we can constant fold its operands.
1312 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1313 i != e; ++i) {
1314 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1315 if (CE == 0) continue;
1316
1317 // If we already folded this constant, don't try again.
1318 if (!FoldedConstants.insert(CE))
1319 continue;
1320
Chris Lattner7b550cc2009-11-06 04:27:31 +00001321 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00001322 if (NewC && NewC != CE) {
1323 *i = NewC;
1324 MadeIRChange = true;
1325 }
1326 }
1327 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001328
Chris Lattner67f7d542009-10-12 03:58:40 +00001329 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001330 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001331
1332 // Recursively visit successors. If this is a branch or switch on a
1333 // constant, only visit the reachable successor.
1334 TerminatorInst *TI = BB->getTerminator();
1335 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1336 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1337 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001338 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001339 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001340 continue;
1341 }
1342 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1343 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1344 // See if this is an explicit destination.
1345 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1346 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001347 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001348 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001349 continue;
1350 }
1351
1352 // Otherwise it is the default destination.
1353 Worklist.push_back(SI->getSuccessor(0));
1354 continue;
1355 }
1356 }
1357
1358 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1359 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001360 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001361
1362 // Once we've found all of the instructions to add to instcombine's worklist,
1363 // add them in reverse order. This way instcombine will visit from the top
1364 // of the function down. This jives well with the way that it adds all uses
1365 // of instructions to the worklist after doing a transformation, thus avoiding
1366 // some N^2 behavior in pathological cases.
1367 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1368 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001369
1370 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001371}
1372
Chris Lattnerec9c3582007-03-03 02:04:50 +00001373bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001374 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001375
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001376 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1377 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001378
Chris Lattnerb3d59702005-07-07 20:40:38 +00001379 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001380 // Do a depth-first traversal of the function, populate the worklist with
1381 // the reachable instructions. Ignore blocks that are not reachable. Keep
1382 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001383 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001384 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001385
Chris Lattnerb3d59702005-07-07 20:40:38 +00001386 // Do a quick scan over the function. If we find any blocks that are
1387 // unreachable, remove any instructions inside of them. This prevents
1388 // the instcombine code from having to deal with some bad special cases.
1389 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1390 if (!Visited.count(BB)) {
1391 Instruction *Term = BB->getTerminator();
1392 while (Term != BB->begin()) { // Remove instrs bottom-up
1393 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001394
Chris Lattnerbdff5482009-08-23 04:37:46 +00001395 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001396 // A debug intrinsic shouldn't force another iteration if we weren't
1397 // going to do one without it.
1398 if (!isa<DbgInfoIntrinsic>(I)) {
1399 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001400 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001401 }
Devang Patel228ebd02009-10-13 22:56:32 +00001402
Devang Patel228ebd02009-10-13 22:56:32 +00001403 // If I is not void type then replaceAllUsesWith undef.
1404 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001405 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001406 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001407 I->eraseFromParent();
1408 }
1409 }
1410 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001411
Chris Lattner873ff012009-08-30 05:55:36 +00001412 while (!Worklist.isEmpty()) {
1413 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001414 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001415
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001416 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001417 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001418 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001419 EraseInstFromFunction(*I);
1420 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001421 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001422 continue;
1423 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001424
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001425 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001426 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001427 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001428 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001429
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001430 // Add operands to the worklist.
1431 ReplaceInstUsesWith(*I, C);
1432 ++NumConstProp;
1433 EraseInstFromFunction(*I);
1434 MadeIRChange = true;
1435 continue;
1436 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001437
Chris Lattnerea1c4542004-12-08 23:43:58 +00001438 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001439 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001440 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001441 Instruction *UserInst = cast<Instruction>(I->use_back());
1442 BasicBlock *UserParent;
1443
1444 // Get the block the use occurs in.
1445 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1446 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1447 else
1448 UserParent = UserInst->getParent();
1449
Chris Lattnerea1c4542004-12-08 23:43:58 +00001450 if (UserParent != BB) {
1451 bool UserIsSuccessor = false;
1452 // See if the user is one of our successors.
1453 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1454 if (*SI == UserParent) {
1455 UserIsSuccessor = true;
1456 break;
1457 }
1458
1459 // If the user is one of our immediate successors, and if that successor
1460 // only has us as a predecessors (we'd have to split the critical edge
1461 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001462 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001463 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001464 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001465 }
1466 }
1467
Chris Lattner74381062009-08-30 07:44:24 +00001468 // Now that we have an instruction, try combining it to simplify it.
1469 Builder->SetInsertPoint(I->getParent(), I);
1470
Reid Spencera9b81012007-03-26 17:44:01 +00001471#ifndef NDEBUG
1472 std::string OrigI;
1473#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001474 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001475 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1476
Chris Lattner90ac28c2002-08-02 19:29:35 +00001477 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001478 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001479 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001480 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001481 DEBUG(errs() << "IC: Old = " << *I << '\n'
1482 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001483
Chris Lattnerf523d062004-06-09 05:08:07 +00001484 // Everything uses the new instruction now.
1485 I->replaceAllUsesWith(Result);
1486
1487 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001488 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001489 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001490
Chris Lattner6934a042007-02-11 01:23:03 +00001491 // Move the name to the new instruction first.
1492 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001493
1494 // Insert the new instruction into the basic block...
1495 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001496 BasicBlock::iterator InsertPos = I;
1497
1498 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1499 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1500 ++InsertPos;
1501
1502 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001503
Chris Lattner7a1e9242009-08-30 06:13:40 +00001504 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001505 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001506#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001507 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1508 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001509#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001510
Chris Lattner90ac28c2002-08-02 19:29:35 +00001511 // If the instruction was modified, it's possible that it is now dead.
1512 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001513 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001514 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001515 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001516 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001517 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001518 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001519 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001520 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001521 }
1522 }
1523
Chris Lattner873ff012009-08-30 05:55:36 +00001524 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001525 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001526}
1527
Chris Lattnerec9c3582007-03-03 02:04:50 +00001528
1529bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00001530 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001531 TD = getAnalysisIfAvailable<TargetData>();
1532
Chris Lattner74381062009-08-30 07:44:24 +00001533
1534 /// Builder - This is an IRBuilder that automatically inserts new
1535 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001536 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001537 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001538 InstCombineIRInserter(Worklist));
1539 Builder = &TheBuilder;
1540
Chris Lattnerec9c3582007-03-03 02:04:50 +00001541 bool EverMadeChange = false;
1542
1543 // Iterate while there is work to do.
1544 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001545 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001546 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001547
1548 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001549 return EverMadeChange;
1550}
1551
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001552FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001553 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001554}