blob: 41d542af685aee7bad14d24e8440209426b8ea60 [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"
Nick Lewyckyd5061a92011-08-03 00:43:35 +000049#include "llvm/Support/ValueHandle.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000050#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000052#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000054#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattner0e5f4992006-12-19 21:40:18 +000058STATISTIC(NumCombined , "Number of insts combined");
59STATISTIC(NumConstProp, "Number of constant folds");
60STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000061STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sands37bf92b2010-12-22 13:36:08 +000062STATISTIC(NumExpand, "Number of expansions");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000063STATISTIC(NumFactor , "Number of factorizations");
64STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Owen Anderson74cfb0c2010-10-07 20:04:55 +000066// Initialization Routines
67void llvm::initializeInstCombine(PassRegistry &Registry) {
68 initializeInstCombinerPass(Registry);
69}
70
71void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
72 initializeInstCombine(*unwrap(R));
73}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074
Dan Gohman844731a2008-05-13 00:00:25 +000075char InstCombiner::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000076INITIALIZE_PASS(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000077 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000078
Chris Lattnere0b4b722010-01-04 07:17:19 +000079void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere0b4b722010-01-04 07:17:19 +000080 AU.setPreservesCFG();
81}
82
83
Chris Lattnerc22d4d12009-11-10 07:23:37 +000084/// ShouldChangeType - Return true if it is desirable to convert a computation
85/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
86/// type for example, or from a smaller to a larger illegal type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000087bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000088 assert(From->isIntegerTy() && To->isIntegerTy());
Chris Lattnerc22d4d12009-11-10 07:23:37 +000089
90 // If we don't have TD, we don't know if the source/dest are legal.
91 if (!TD) return false;
92
93 unsigned FromWidth = From->getPrimitiveSizeInBits();
94 unsigned ToWidth = To->getPrimitiveSizeInBits();
95 bool FromLegal = TD->isLegalInteger(FromWidth);
96 bool ToLegal = TD->isLegalInteger(ToWidth);
97
98 // If this is a legal integer from type, and the result would be an illegal
99 // type, don't do the transformation.
100 if (FromLegal && !ToLegal)
101 return false;
102
103 // Otherwise, if both are illegal, do not increase the size of the result. We
104 // do allow things like i160 -> i64, but not i64 -> i160.
105 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106 return false;
107
108 return true;
109}
110
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000111// Return true, if No Signed Wrap should be maintained for I.
112// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
113// where both B and C should be ConstantInts, results in a constant that does
114// not overflow. This function only handles the Add and Sub opcodes. For
115// all other opcodes, the function conservatively returns false.
116static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
117 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
118 if (!OBO || !OBO->hasNoSignedWrap()) {
119 return false;
120 }
121
122 // We reason about Add and Sub Only.
123 Instruction::BinaryOps Opcode = I.getOpcode();
124 if (Opcode != Instruction::Add &&
125 Opcode != Instruction::Sub) {
126 return false;
127 }
128
129 ConstantInt *CB = dyn_cast<ConstantInt>(B);
130 ConstantInt *CC = dyn_cast<ConstantInt>(C);
131
132 if (!CB || !CC) {
133 return false;
134 }
135
136 const APInt &BVal = CB->getValue();
137 const APInt &CVal = CC->getValue();
138 bool Overflow = false;
139
140 if (Opcode == Instruction::Add) {
141 BVal.sadd_ov(CVal, Overflow);
142 } else {
143 BVal.ssub_ov(CVal, Overflow);
144 }
145
146 return !Overflow;
147}
148
Duncan Sands096aa792010-11-13 15:10:37 +0000149/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
150/// operators which are associative or commutative:
151//
152// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000153//
Chris Lattner4f98c562003-03-10 21:43:22 +0000154// 1. Order operands such that they are listed from right (least complex) to
155// left (most complex). This puts constants before unary operators before
156// binary operators.
157//
Duncan Sands096aa792010-11-13 15:10:37 +0000158// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000159//
Duncan Sands096aa792010-11-13 15:10:37 +0000160// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
161// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
162//
163// Associative and commutative operators:
164//
165// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
166// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
167// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
168// if C1 and C2 are constants.
169//
170bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000171 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000172 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000173
Duncan Sands096aa792010-11-13 15:10:37 +0000174 do {
175 // Order operands such that they are listed from right (least complex) to
176 // left (most complex). This puts constants before unary operators before
177 // binary operators.
178 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
179 getComplexity(I.getOperand(1)))
180 Changed = !I.swapOperands();
181
182 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
183 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
184
185 if (I.isAssociative()) {
186 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
187 if (Op0 && Op0->getOpcode() == Opcode) {
188 Value *A = Op0->getOperand(0);
189 Value *B = Op0->getOperand(1);
190 Value *C = I.getOperand(1);
191
192 // Does "B op C" simplify?
193 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
194 // It simplifies to V. Form "A op V".
195 I.setOperand(0, A);
196 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000197 // Conservatively clear the optional flags, since they may not be
198 // preserved by the reassociation.
Nick Lewycky7f0170c2011-08-14 03:41:33 +0000199 if (MaintainNoSignedWrap(I, B, C) &&
200 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
201 // Note: this is only valid because SimplifyBinOp doesn't look at
202 // the operands to Op0.
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000203 I.clearSubclassOptionalData();
204 I.setHasNoSignedWrap(true);
205 } else {
206 I.clearSubclassOptionalData();
207 }
208
Duncan Sands096aa792010-11-13 15:10:37 +0000209 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000210 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000211 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000212 }
Duncan Sands096aa792010-11-13 15:10:37 +0000213 }
214
215 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
216 if (Op1 && Op1->getOpcode() == Opcode) {
217 Value *A = I.getOperand(0);
218 Value *B = Op1->getOperand(0);
219 Value *C = Op1->getOperand(1);
220
221 // Does "A op B" simplify?
222 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
223 // It simplifies to V. Form "V op C".
224 I.setOperand(0, V);
225 I.setOperand(1, C);
Dan Gohman5195b712011-02-02 02:05:46 +0000226 // Conservatively clear the optional flags, since they may not be
227 // preserved by the reassociation.
228 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000229 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000230 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000231 continue;
232 }
233 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000234 }
Duncan Sands096aa792010-11-13 15:10:37 +0000235
236 if (I.isAssociative() && I.isCommutative()) {
237 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
238 if (Op0 && Op0->getOpcode() == Opcode) {
239 Value *A = Op0->getOperand(0);
240 Value *B = Op0->getOperand(1);
241 Value *C = I.getOperand(1);
242
243 // Does "C op A" simplify?
244 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
245 // It simplifies to V. Form "V op B".
246 I.setOperand(0, V);
247 I.setOperand(1, B);
Dan Gohman5195b712011-02-02 02:05:46 +0000248 // Conservatively clear the optional flags, since they may not be
249 // preserved by the reassociation.
250 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000251 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000252 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000253 continue;
254 }
255 }
256
257 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
258 if (Op1 && Op1->getOpcode() == Opcode) {
259 Value *A = I.getOperand(0);
260 Value *B = Op1->getOperand(0);
261 Value *C = Op1->getOperand(1);
262
263 // Does "C op A" simplify?
264 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
265 // It simplifies to V. Form "B op V".
266 I.setOperand(0, B);
267 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000268 // Conservatively clear the optional flags, since they may not be
269 // preserved by the reassociation.
270 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000271 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000272 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000273 continue;
274 }
275 }
276
277 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
278 // if C1 and C2 are constants.
279 if (Op0 && Op1 &&
280 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
281 isa<Constant>(Op0->getOperand(1)) &&
282 isa<Constant>(Op1->getOperand(1)) &&
283 Op0->hasOneUse() && Op1->hasOneUse()) {
284 Value *A = Op0->getOperand(0);
285 Constant *C1 = cast<Constant>(Op0->getOperand(1));
286 Value *B = Op1->getOperand(0);
287 Constant *C2 = cast<Constant>(Op1->getOperand(1));
288
289 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000290 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Eli Friedmana311c342011-05-27 00:19:40 +0000291 InsertNewInstWith(New, I);
Eli Friedmane6f364b2011-05-18 23:58:37 +0000292 New->takeName(Op1);
Duncan Sands096aa792010-11-13 15:10:37 +0000293 I.setOperand(0, New);
294 I.setOperand(1, Folded);
Dan Gohman5195b712011-02-02 02:05:46 +0000295 // Conservatively clear the optional flags, since they may not be
296 // preserved by the reassociation.
Nick Lewycky28b84ff2011-08-14 04:51:49 +0000297 I.clearSubclassOptionalData();
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000298
Duncan Sands096aa792010-11-13 15:10:37 +0000299 Changed = true;
300 continue;
301 }
302 }
303
304 // No further simplifications.
305 return Changed;
306 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000307}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000308
Duncan Sands5057f382010-11-23 14:23:47 +0000309/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000310/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000311static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
312 Instruction::BinaryOps ROp) {
313 switch (LOp) {
314 default:
315 return false;
316
317 case Instruction::And:
318 // And distributes over Or and Xor.
319 switch (ROp) {
320 default:
321 return false;
322 case Instruction::Or:
323 case Instruction::Xor:
324 return true;
325 }
326
327 case Instruction::Mul:
328 // Multiplication distributes over addition and subtraction.
329 switch (ROp) {
330 default:
331 return false;
332 case Instruction::Add:
333 case Instruction::Sub:
334 return true;
335 }
336
337 case Instruction::Or:
338 // Or distributes over And.
339 switch (ROp) {
340 default:
341 return false;
342 case Instruction::And:
343 return true;
344 }
345 }
346}
347
348/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
349/// "(X ROp Z) LOp (Y ROp Z)".
350static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
351 Instruction::BinaryOps ROp) {
352 if (Instruction::isCommutative(ROp))
353 return LeftDistributesOverRight(ROp, LOp);
354 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
355 // but this requires knowing that the addition does not overflow and other
356 // such subtleties.
357 return false;
358}
359
Duncan Sands37bf92b2010-12-22 13:36:08 +0000360/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
361/// which some other binary operation distributes over either by factorizing
362/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
363/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
364/// a win). Returns the simplified value, or null if it didn't simplify.
365Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
366 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
367 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
368 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
369 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
Duncan Sands5057f382010-11-23 14:23:47 +0000370
Duncan Sands37bf92b2010-12-22 13:36:08 +0000371 // Factorization.
372 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
373 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
374 // a common term.
375 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
376 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
377 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
Duncan Sands5057f382010-11-23 14:23:47 +0000378
Duncan Sands37bf92b2010-12-22 13:36:08 +0000379 // Does "X op' Y" always equal "Y op' X"?
380 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
Duncan Sands5057f382010-11-23 14:23:47 +0000381
Duncan Sands37bf92b2010-12-22 13:36:08 +0000382 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
383 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
384 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
385 // commutative case, "(A op' B) op (C op' A)"?
386 if (A == C || (InnerCommutative && A == D)) {
387 if (A != C)
388 std::swap(C, D);
389 // Consider forming "A op' (B op D)".
390 // If "B op D" simplifies then it can be formed with no cost.
391 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
392 // If "B op D" doesn't simplify then only go on if both of the existing
393 // operations "A op' B" and "C op' D" will be zapped as no longer used.
394 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
395 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
396 if (V) {
397 ++NumFactor;
398 V = Builder->CreateBinOp(InnerOpcode, A, V);
399 V->takeName(&I);
400 return V;
401 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000402 }
Duncan Sands5057f382010-11-23 14:23:47 +0000403
Duncan Sands37bf92b2010-12-22 13:36:08 +0000404 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
405 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
406 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
407 // commutative case, "(A op' B) op (B op' D)"?
408 if (B == D || (InnerCommutative && B == C)) {
409 if (B != D)
410 std::swap(C, D);
411 // Consider forming "(A op C) op' B".
412 // If "A op C" simplifies then it can be formed with no cost.
413 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
414 // If "A op C" doesn't simplify then only go on if both of the existing
415 // operations "A op' B" and "C op' D" will be zapped as no longer used.
416 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
417 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
418 if (V) {
419 ++NumFactor;
420 V = Builder->CreateBinOp(InnerOpcode, V, B);
421 V->takeName(&I);
422 return V;
423 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000424 }
Duncan Sands37bf92b2010-12-22 13:36:08 +0000425 }
426
427 // Expansion.
428 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
429 // The instruction has the form "(A op' B) op C". See if expanding it out
430 // to "(A op C) op' (B op C)" results in simplifications.
431 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
432 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
433
434 // Do "A op C" and "B op C" both simplify?
435 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
436 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
437 // They do! Return "L op' R".
438 ++NumExpand;
439 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
440 if ((L == A && R == B) ||
441 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
442 return Op0;
443 // Otherwise return "L op' R" if it simplifies.
444 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
445 return V;
446 // Otherwise, create a new instruction.
447 C = Builder->CreateBinOp(InnerOpcode, L, R);
448 C->takeName(&I);
449 return C;
450 }
451 }
452
453 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
454 // The instruction has the form "A op (B op' C)". See if expanding it out
455 // to "(A op B) op' (A op C)" results in simplifications.
456 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
457 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
458
459 // Do "A op B" and "A op C" both simplify?
460 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
461 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
462 // They do! Return "L op' R".
463 ++NumExpand;
464 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
465 if ((L == B && R == C) ||
466 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
467 return Op1;
468 // Otherwise return "L op' R" if it simplifies.
469 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
470 return V;
471 // Otherwise, create a new instruction.
472 A = Builder->CreateBinOp(InnerOpcode, L, R);
473 A->takeName(&I);
474 return A;
475 }
476 }
Duncan Sands5057f382010-11-23 14:23:47 +0000477
478 return 0;
479}
480
Chris Lattner8d969642003-03-10 23:06:50 +0000481// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
482// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000483//
Chris Lattner02446fc2010-01-04 07:37:31 +0000484Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000485 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000486 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000487
Chris Lattner0ce85802004-12-14 20:08:06 +0000488 // Constants can be considered to be negated values if they can be folded.
489 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000490 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000491
492 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000493 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000494 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000495
Chris Lattner8d969642003-03-10 23:06:50 +0000496 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000497}
498
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000499// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
500// instruction if the LHS is a constant negative zero (which is the 'negate'
501// form).
502//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000503Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000504 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000505 return BinaryOperator::getFNegArgument(V);
506
507 // Constants can be considered to be negated values if they can be folded.
508 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000509 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000510
511 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000512 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000513 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000514
515 return 0;
516}
517
Chris Lattner6e7ba452005-01-01 16:22:27 +0000518static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000519 InstCombiner *IC) {
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000520 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +0000521 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000522 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000523
Chris Lattner2eefe512004-04-09 19:05:30 +0000524 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000525 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
526 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000527
Chris Lattner2eefe512004-04-09 19:05:30 +0000528 if (Constant *SOC = dyn_cast<Constant>(SO)) {
529 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000530 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
531 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000532 }
533
534 Value *Op0 = SO, *Op1 = ConstOperand;
535 if (!ConstIsRHS)
536 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000537
Chris Lattner6e7ba452005-01-01 16:22:27 +0000538 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000539 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
540 SO->getName()+".op");
541 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
542 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
543 SO->getName()+".cmp");
544 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
545 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
546 SO->getName()+".cmp");
547 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000548}
549
550// FoldOpIntoSelect - Given an instruction with a select as one operand and a
551// constant as the other operand, try to fold the binary operator into the
552// select arguments. This also works for Cast instructions, which obviously do
553// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000554Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000555 // Don't modify shared select instructions
556 if (!SI->hasOneUse()) return 0;
557 Value *TV = SI->getOperand(1);
558 Value *FV = SI->getOperand(2);
559
560 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000561 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000562 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000563
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000564 // If it's a bitcast involving vectors, make sure it has the same number of
565 // elements on both sides.
566 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000567 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
568 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000569
570 // Verify that either both or neither are vectors.
571 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
572 // If vectors, verify that they have the same number of elements.
573 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
574 return 0;
575 }
576
Chris Lattner80f43d32010-01-04 07:53:58 +0000577 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
578 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000579
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000580 return SelectInst::Create(SI->getCondition(),
581 SelectTrueVal, SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000582 }
583 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000584}
585
Chris Lattner4e998b22004-09-29 05:07:12 +0000586
Chris Lattner5d1704d2009-09-27 19:57:57 +0000587/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
588/// has a PHI node as operand #0, see if we can fold the instruction into the
589/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000590///
Chris Lattner9922ccf2011-01-16 05:14:26 +0000591Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000592 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000593 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner5aac8322011-01-16 04:37:29 +0000594 if (NumPHIValues == 0)
Chris Lattner213cd612009-09-27 20:46:36 +0000595 return 0;
596
Chris Lattner084fe622011-01-21 05:08:26 +0000597 // We normally only transform phis with a single use. However, if a PHI has
598 // multiple uses and they are all the same operation, we can fold *all* of the
599 // uses into the PHI.
Chris Lattner192228e2011-01-16 05:28:59 +0000600 if (!PN->hasOneUse()) {
601 // Walk the use list for the instruction, comparing them to I.
602 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnercd151d22011-01-21 05:29:50 +0000603 UI != E; ++UI) {
604 Instruction *User = cast<Instruction>(*UI);
605 if (User != &I && !I.isIdenticalTo(User))
Chris Lattner192228e2011-01-16 05:28:59 +0000606 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000607 }
Chris Lattner192228e2011-01-16 05:28:59 +0000608 // Otherwise, we can replace *all* users with the new PHI we form.
609 }
Chris Lattner213cd612009-09-27 20:46:36 +0000610
Chris Lattner5d1704d2009-09-27 19:57:57 +0000611 // Check to see if all of the operands of the PHI are simple constants
612 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000613 // remember the BB it is in. If there is more than one or if *it* is a PHI,
614 // bail out. We don't do arbitrary constant expressions here because moving
615 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000616 BasicBlock *NonConstBB = 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000617 for (unsigned i = 0; i != NumPHIValues; ++i) {
618 Value *InVal = PN->getIncomingValue(i);
619 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
620 continue;
621
622 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
623 if (NonConstBB) return 0; // More than one non-const value.
624
625 NonConstBB = PN->getIncomingBlock(i);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000626
627 // If the InVal is an invoke at the end of the pred block, then we can't
628 // insert a computation after it without breaking the edge.
629 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
630 if (II->getParent() == NonConstBB)
631 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000632
633 // If the incoming non-constant value is in I's block, we will remove one
634 // instruction, but insert another equivalent one, leading to infinite
635 // instcombine.
636 if (NonConstBB == I.getParent())
637 return 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000638 }
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000639
640 // If there is exactly one non-constant value, we can insert a copy of the
641 // operation in that block. However, if this is a critical edge, we would be
642 // inserting the computation one some other paths (e.g. inside a loop). Only
643 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9922ccf2011-01-16 05:14:26 +0000644 if (NonConstBB != 0) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000645 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
646 if (!BI || !BI->isUnconditional()) return 0;
647 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000648
649 // Okay, we can do the transformation: create the new PHI node.
Eli Friedmane6f364b2011-05-18 23:58:37 +0000650 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner857eb572009-10-21 23:41:58 +0000651 InsertNewInstBefore(NewPN, *PN);
652 NewPN->takeName(PN);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000653
654 // If we are going to have to insert a new computation, do so right before the
655 // predecessors terminator.
656 if (NonConstBB)
657 Builder->SetInsertPoint(NonConstBB->getTerminator());
658
Chris Lattner4e998b22004-09-29 05:07:12 +0000659 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000660 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
661 // We only currently try to fold the condition of a select when it is a phi,
662 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000663 Value *TrueV = SI->getTrueValue();
664 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000665 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000666 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000667 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000668 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
669 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000670 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000671 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000672 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000673 else
674 InV = Builder->CreateSelect(PN->getIncomingValue(i),
675 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000676 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000677 }
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000678 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
679 Constant *C = cast<Constant>(I.getOperand(1));
680 for (unsigned i = 0; i != NumPHIValues; ++i) {
681 Value *InV = 0;
682 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
683 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
684 else if (isa<ICmpInst>(CI))
685 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
686 C, "phitmp");
687 else
688 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
689 C, "phitmp");
690 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
691 }
Chris Lattner5d1704d2009-09-27 19:57:57 +0000692 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000693 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000694 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000695 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000696 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
697 InV = ConstantExpr::get(I.getOpcode(), InC, C);
698 else
699 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
700 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000701 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000702 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000703 } else {
704 CastInst *CI = cast<CastInst>(&I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000705 Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000706 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000707 Value *InV;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000708 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000709 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000710 else
711 InV = Builder->CreateCast(CI->getOpcode(),
712 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000713 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000714 }
715 }
Chris Lattner192228e2011-01-16 05:28:59 +0000716
717 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
718 UI != E; ) {
719 Instruction *User = cast<Instruction>(*UI++);
720 if (User == &I) continue;
721 ReplaceInstUsesWith(*User, NewPN);
722 EraseInstFromFunction(*User);
723 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000724 return ReplaceInstUsesWith(I, NewPN);
725}
726
Chris Lattner46cd5a12009-01-09 05:44:56 +0000727/// FindElementAtOffset - Given a type and a constant offset, determine whether
728/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000729/// the specified offset. If so, fill them into NewIndices and return the
730/// resultant element type, otherwise return null.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000731Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner80f43d32010-01-04 07:53:58 +0000732 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000733 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000734 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000735
736 // Start with the index over the outer type. Note that the type size
737 // might be zero (even if the offset isn't zero) if the indexed type
738 // is something like [0 x {int, int}]
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000739 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000740 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000741 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000742 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000743 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000744
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000745 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000746 if (Offset < 0) {
747 --FirstIdx;
748 Offset += TySize;
749 assert(Offset >= 0);
750 }
751 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
752 }
753
Owen Andersoneed707b2009-07-24 23:12:02 +0000754 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000755
756 // Index into the types. If we fail, set OrigBase to null.
757 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000758 // Indexing into tail padding between struct/array elements.
759 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000760 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000761
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000762 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000763 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000764 assert(Offset < (int64_t)SL->getSizeInBytes() &&
765 "Offset must stay within the indexed type");
766
Chris Lattner46cd5a12009-01-09 05:44:56 +0000767 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000768 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
769 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000770
771 Offset -= SL->getElementOffset(Elt);
772 Ty = STy->getElementType(Elt);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000773 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000774 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000775 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000776 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000777 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000778 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000779 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000780 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000781 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000782 }
783 }
784
Chris Lattner3914f722009-01-24 01:00:13 +0000785 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000786}
787
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000788static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
789 // If this GEP has only 0 indices, it is the same pointer as
790 // Src. If Src is not a trivial GEP too, don't combine
791 // the indices.
792 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
793 !Src.hasOneUse())
794 return false;
795 return true;
796}
Chris Lattner473945d2002-05-06 18:06:38 +0000797
Chris Lattner7e708292002-06-25 16:13:24 +0000798Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000799 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
800
Jay Foadb9b54eb2011-07-19 15:07:52 +0000801 if (Value *V = SimplifyGEPInst(Ops, TD))
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000802 return ReplaceInstUsesWith(GEP, V);
803
Chris Lattner620ce142004-05-07 22:09:22 +0000804 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000805
Duncan Sandsa63395a2010-11-22 16:32:50 +0000806 // Eliminate unneeded casts for indices, and replace indices which displace
807 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000808 if (TD) {
809 bool MadeChange = false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000810 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
Duncan Sandsa63395a2010-11-22 16:32:50 +0000811
Chris Lattnerccf4b342009-08-30 04:49:01 +0000812 gep_type_iterator GTI = gep_type_begin(GEP);
813 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
814 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000815 // Skip indices into struct types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000816 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
Duncan Sandsa63395a2010-11-22 16:32:50 +0000817 if (!SeqTy) continue;
818
819 // If the element type has zero size then any index over it is equivalent
820 // to an index of zero, so replace it with zero if it is not zero already.
821 if (SeqTy->getElementType()->isSized() &&
822 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
823 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
824 *I = Constant::getNullValue(IntPtrTy);
825 MadeChange = true;
826 }
827
828 if ((*I)->getType() != IntPtrTy) {
829 // If we are using a wider index than needed for this platform, shrink
830 // it to what we need. If narrower, sign-extend it to what we need.
831 // This explicit cast can make subsequent optimizations more obvious.
832 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
833 MadeChange = true;
834 }
Chris Lattner28977af2004-04-05 01:30:19 +0000835 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000836 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000837 }
Chris Lattner28977af2004-04-05 01:30:19 +0000838
Chris Lattner90ac28c2002-08-02 19:29:35 +0000839 // Combine Indices - If the source pointer to this getelementptr instruction
840 // is a getelementptr instruction, combine the indices of the two
841 // getelementptr instructions into a single instruction.
842 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000843 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000844 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Rafael Espindolab5a12dd2011-07-11 03:43:47 +0000845 return 0;
846
Chris Lattner620ce142004-05-07 22:09:22 +0000847 // Note that if our source is a gep chain itself that we wait for that
848 // chain to be resolved before we perform this transformation. This
849 // avoids us creating a TON of code in some cases.
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000850 if (GEPOperator *SrcGEP =
851 dyn_cast<GEPOperator>(Src->getOperand(0)))
852 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000853 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000854
Chris Lattner72588fc2007-02-15 22:48:32 +0000855 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000856
857 // Find out whether the last index in the source GEP is a sequential idx.
858 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000859 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
860 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000861 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000862
Chris Lattner90ac28c2002-08-02 19:29:35 +0000863 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000864 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000865 // Replace: gep (gep %P, long B), long A, ...
866 // With: T = long A+B; gep %P, T, ...
867 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000868 Value *Sum;
869 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
870 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000871 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000872 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000873 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000874 Sum = SO1;
875 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000876 // If they aren't the same type, then the input hasn't been processed
877 // by the loop above yet (which canonicalizes sequential index types to
878 // intptr_t). Just avoid transforming this until the input has been
879 // normalized.
880 if (SO1->getType() != GO1->getType())
881 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000882 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000883 }
Chris Lattner620ce142004-05-07 22:09:22 +0000884
Chris Lattnerab984842009-08-30 05:30:55 +0000885 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000886 if (Src->getNumOperands() == 2) {
887 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000888 GEP.setOperand(1, Sum);
889 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000890 }
Chris Lattnerab984842009-08-30 05:30:55 +0000891 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000892 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000893 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000894 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000895 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000896 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000897 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000898 Indices.append(Src->op_begin()+1, Src->op_end());
899 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000900 }
901
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000902 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000903 return (GEP.isInBounds() && Src->isInBounds()) ?
Jay Foada9203102011-07-25 09:48:08 +0000904 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
905 GEP.getName()) :
906 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000907 }
Nadav Rotem0286ca82011-04-05 14:29:52 +0000908
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000909 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000910 Value *StrippedPtr = PtrOp->stripPointerCasts();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000911 PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Nadav Rotem0286ca82011-04-05 14:29:52 +0000912 if (StrippedPtr != PtrOp &&
913 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
Chris Lattner963f4ba2009-08-30 20:36:46 +0000914
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000915 bool HasZeroPointerIndex = false;
916 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
917 HasZeroPointerIndex = C->isZero();
Nadav Rotem0286ca82011-04-05 14:29:52 +0000918
Chris Lattner963f4ba2009-08-30 20:36:46 +0000919 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
920 // into : GEP [10 x i8]* X, i32 0, ...
921 //
922 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
923 // into : GEP i8* X, ...
Nadav Rotem0286ca82011-04-05 14:29:52 +0000924 //
Chris Lattner963f4ba2009-08-30 20:36:46 +0000925 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000926 if (HasZeroPointerIndex) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000927 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
928 if (ArrayType *CATy =
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000929 dyn_cast<ArrayType>(CPTy->getElementType())) {
930 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000931 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000932 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000933 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
934 GetElementPtrInst *Res =
Jay Foada9203102011-07-25 09:48:08 +0000935 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Chris Lattner948cdeb2010-01-05 07:42:10 +0000936 Res->setIsInBounds(GEP.isInBounds());
937 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000938 }
939
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000940 if (ArrayType *XATy =
Chris Lattner948cdeb2010-01-05 07:42:10 +0000941 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000942 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000943 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000944 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000945 // At this point, we know that the cast source type is a pointer
946 // to an array of the same type as the destination pointer
947 // array. Because the array type is never stepped over (there
948 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000949 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000950 return &GEP;
951 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000952 }
953 }
Chris Lattnereed48272005-09-13 00:40:14 +0000954 } else if (GEP.getNumOperands() == 2) {
955 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000956 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
957 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000958 Type *SrcElTy = StrippedPtrTy->getElementType();
959 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000960 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000961 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
962 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000963 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000964 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000965 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000966 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +0000967 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
968 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000969 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000970 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000971 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000972
973 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000974 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000975 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000976 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000977
Duncan Sands1df98592010-02-16 11:11:14 +0000978 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000979 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000980 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000981
982 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
983 // allow either a mul, shift, or constant here.
984 Value *NewIdx = 0;
985 ConstantInt *Scale = 0;
986 if (ArrayEltSize == 1) {
987 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000988 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000989 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000990 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000991 Scale = CI;
992 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
993 if (Inst->getOpcode() == Instruction::Shl &&
994 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000995 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
996 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000997 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000998 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000999 NewIdx = Inst->getOperand(0);
1000 } else if (Inst->getOpcode() == Instruction::Mul &&
1001 isa<ConstantInt>(Inst->getOperand(1))) {
1002 Scale = cast<ConstantInt>(Inst->getOperand(1));
1003 NewIdx = Inst->getOperand(0);
1004 }
1005 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001006
Chris Lattner7835cdd2005-09-13 18:36:04 +00001007 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001008 // out, perform the transformation. Note, we don't know whether Scale is
1009 // signed or not. We'll use unsigned version of division/modulo
1010 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00001011 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001012 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001013 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001014 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00001015 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00001016 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
1017 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001018 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00001019 }
1020
1021 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00001022 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00001023 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00001024 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +00001025 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001026 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
1027 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00001028 // The NewGEP must be pointer typed, so must the old one -> BitCast
1029 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00001030 }
1031 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00001032 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001033 }
Nadav Rotem0286ca82011-04-05 14:29:52 +00001034
Chris Lattner46cd5a12009-01-09 05:44:56 +00001035 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00001036 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00001037 /// Y = gep X, <...constant indices...>
1038 /// into a gep of the original struct. This is important for SROA and alias
1039 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00001040 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00001041 if (TD &&
Nadav Rotem0286ca82011-04-05 14:29:52 +00001042 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
1043 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1044
Chris Lattner46cd5a12009-01-09 05:44:56 +00001045 // Determine how much the GEP moves the pointer. We are guaranteed to get
1046 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00001047 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00001048 int64_t Offset = OffsetV->getSExtValue();
Nadav Rotem0286ca82011-04-05 14:29:52 +00001049
Chris Lattner46cd5a12009-01-09 05:44:56 +00001050 // If this GEP instruction doesn't move the pointer, just replace the GEP
1051 // with a bitcast of the real input to the dest type.
1052 if (Offset == 0) {
1053 // If the bitcast is of an allocation, and the allocation will be
1054 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001055 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00001056 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00001057 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1058 if (Instruction *I = visitBitCast(*BCI)) {
1059 if (I != BCI) {
1060 I->takeName(BCI);
1061 BCI->getParent()->getInstList().insert(BCI, I);
1062 ReplaceInstUsesWith(*BCI, I);
1063 }
1064 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00001065 }
Chris Lattner58407792009-01-09 04:53:57 +00001066 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001067 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00001068 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001069
1070 // Otherwise, if the offset is non-zero, we need to find out if there is a
1071 // field at Offset in 'A's type. If so, we can pull the cast through the
1072 // GEP.
1073 SmallVector<Value*, 8> NewIndices;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001074 Type *InTy =
Chris Lattner46cd5a12009-01-09 05:44:56 +00001075 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001076 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00001077 Value *NGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001078 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1079 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001080
1081 if (NGEP->getType() == GEP.getType())
1082 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00001083 NGEP->takeName(&GEP);
1084 return new BitCastInst(NGEP, GEP.getType());
1085 }
Chris Lattner58407792009-01-09 04:53:57 +00001086 }
1087 }
1088
Chris Lattner8a2a3112001-12-14 16:52:21 +00001089 return 0;
1090}
1091
Duncan Sands1d9b9732010-05-27 19:09:06 +00001092
1093
Nick Lewyckydbd22552011-08-03 01:11:40 +00001094static bool IsOnlyNullComparedAndFreed(Value *V, SmallVectorImpl<WeakVH> &Users,
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001095 int Depth = 0) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001096 if (Depth == 8)
1097 return false;
1098
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001099 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
Duncan Sands1d9b9732010-05-27 19:09:06 +00001100 UI != UE; ++UI) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001101 User *U = *UI;
1102 if (isFreeCall(U)) {
1103 Users.push_back(U);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001104 continue;
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001105 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001106 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
1107 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) {
1108 Users.push_back(ICI);
1109 continue;
1110 }
1111 }
1112 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1113 if (IsOnlyNullComparedAndFreed(BCI, Users, Depth+1)) {
1114 Users.push_back(BCI);
1115 continue;
1116 }
1117 }
1118 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Nick Lewyckydbd22552011-08-03 01:11:40 +00001119 if (IsOnlyNullComparedAndFreed(GEPI, Users, Depth+1)) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001120 Users.push_back(GEPI);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001121 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001122 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001123 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001124 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001125 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001126 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1127 Users.push_back(II);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001128 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001129 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001130 }
Duncan Sands1d9b9732010-05-27 19:09:06 +00001131 return false;
1132 }
1133 return true;
1134}
1135
1136Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1137 // If we have a malloc call which is only used in any amount of comparisons
1138 // to null and free calls, delete the calls and replace the comparisons with
1139 // true or false as appropriate.
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001140 SmallVector<WeakVH, 64> Users;
1141 if (IsOnlyNullComparedAndFreed(&MI, Users)) {
1142 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1143 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1144 if (!I) continue;
Duncan Sands1d9b9732010-05-27 19:09:06 +00001145
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001146 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001147 ReplaceInstUsesWith(*C,
1148 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1149 C->isFalseWhenEqual()));
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001150 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001151 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sands1d9b9732010-05-27 19:09:06 +00001152 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001153 EraseInstFromFunction(*I);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001154 }
1155 return EraseInstFromFunction(MI);
1156 }
1157 return 0;
1158}
1159
1160
1161
Gabor Greif91697372010-06-24 12:21:15 +00001162Instruction *InstCombiner::visitFree(CallInst &FI) {
1163 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +00001164
1165 // free undef -> unreachable.
1166 if (isa<UndefValue>(Op)) {
1167 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedmane6f364b2011-05-18 23:58:37 +00001168 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1169 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandez66284e02009-10-24 04:23:03 +00001170 return EraseInstFromFunction(FI);
1171 }
1172
1173 // If we have 'free null' delete the instruction. This can happen in stl code
1174 // when lots of inlining happens.
1175 if (isa<ConstantPointerNull>(Op))
1176 return EraseInstFromFunction(FI);
1177
Victor Hernandez66284e02009-10-24 04:23:03 +00001178 return 0;
1179}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00001180
Chris Lattner3284d1f2007-04-15 00:07:55 +00001181
Chris Lattner2f503e62005-01-31 05:36:43 +00001182
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001183Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1184 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001185 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001186 BasicBlock *TrueDest;
1187 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001188 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001189 !isa<Constant>(X)) {
1190 // Swap Destinations and condition...
1191 BI.setCondition(X);
1192 BI.setSuccessor(0, FalseDest);
1193 BI.setSuccessor(1, TrueDest);
1194 return &BI;
1195 }
1196
Reid Spencere4d87aa2006-12-23 06:05:41 +00001197 // Cannonicalize fcmp_one -> fcmp_oeq
1198 FCmpInst::Predicate FPred; Value *Y;
1199 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001200 TrueDest, FalseDest)) &&
1201 BI.getCondition()->hasOneUse())
1202 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1203 FPred == FCmpInst::FCMP_OGE) {
1204 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1205 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1206
1207 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001208 BI.setSuccessor(0, FalseDest);
1209 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001210 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001211 return &BI;
1212 }
1213
1214 // Cannonicalize icmp_ne -> icmp_eq
1215 ICmpInst::Predicate IPred;
1216 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001217 TrueDest, FalseDest)) &&
1218 BI.getCondition()->hasOneUse())
1219 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1220 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1221 IPred == ICmpInst::ICMP_SGE) {
1222 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1223 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1224 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00001225 BI.setSuccessor(0, FalseDest);
1226 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001227 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001228 return &BI;
1229 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001230
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001231 return 0;
1232}
Chris Lattner0864acf2002-11-04 16:18:53 +00001233
Chris Lattner46238a62004-07-03 00:26:11 +00001234Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1235 Value *Cond = SI.getCondition();
1236 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1237 if (I->getOpcode() == Instruction::Add)
1238 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1239 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1240 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00001241 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00001242 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00001243 AddRHS));
1244 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001245 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001246 return &SI;
1247 }
1248 }
1249 return 0;
1250}
1251
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001252Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001253 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001254
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001255 if (!EV.hasIndices())
1256 return ReplaceInstUsesWith(EV, Agg);
1257
1258 if (Constant *C = dyn_cast<Constant>(Agg)) {
1259 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001260 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001261
1262 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00001263 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001264
1265 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1266 // Extract the element indexed by the first index out of the constant
1267 Value *V = C->getOperand(*EV.idx_begin());
1268 if (EV.getNumIndices() > 1)
1269 // Extract the remaining indices out of the constant indexed by the
1270 // first index
Jay Foadfc6d3a42011-07-13 10:26:04 +00001271 return ExtractValueInst::Create(V, EV.getIndices().slice(1));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001272 else
1273 return ReplaceInstUsesWith(EV, V);
1274 }
1275 return 0; // Can't handle other constants
1276 }
1277 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1278 // We're extracting from an insertvalue instruction, compare the indices
1279 const unsigned *exti, *exte, *insi, *inse;
1280 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1281 exte = EV.idx_end(), inse = IV->idx_end();
1282 exti != exte && insi != inse;
1283 ++exti, ++insi) {
1284 if (*insi != *exti)
1285 // The insert and extract both reference distinctly different elements.
1286 // This means the extract is not influenced by the insert, and we can
1287 // replace the aggregate operand of the extract with the aggregate
1288 // operand of the insert. i.e., replace
1289 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1290 // %E = extractvalue { i32, { i32 } } %I, 0
1291 // with
1292 // %E = extractvalue { i32, { i32 } } %A, 0
1293 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001294 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001295 }
1296 if (exti == exte && insi == inse)
1297 // Both iterators are at the end: Index lists are identical. Replace
1298 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1299 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1300 // with "i32 42"
1301 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1302 if (exti == exte) {
1303 // The extract list is a prefix of the insert list. i.e. replace
1304 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1305 // %E = extractvalue { i32, { i32 } } %I, 1
1306 // with
1307 // %X = extractvalue { i32, { i32 } } %A, 1
1308 // %E = insertvalue { i32 } %X, i32 42, 0
1309 // by switching the order of the insert and extract (though the
1310 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001311 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001312 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001313 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001314 makeArrayRef(insi, inse));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001315 }
1316 if (insi == inse)
1317 // The insert list is a prefix of the extract list
1318 // We can simply remove the common indices from the extract and make it
1319 // operate on the inserted value instead of the insertvalue result.
1320 // i.e., replace
1321 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1322 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1323 // with
1324 // %E extractvalue { i32 } { i32 42 }, 0
1325 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001326 makeArrayRef(exti, exte));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001327 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001328 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1329 // We're extracting from an intrinsic, see if we're the only user, which
1330 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001331 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001332 if (II->hasOneUse()) {
1333 // Check if we're grabbing the overflow bit or the result of a 'with
1334 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1335 // and replace it with a traditional binary instruction.
1336 switch (II->getIntrinsicID()) {
1337 case Intrinsic::uadd_with_overflow:
1338 case Intrinsic::sadd_with_overflow:
1339 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001340 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001341 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001342 EraseInstFromFunction(*II);
1343 return BinaryOperator::CreateAdd(LHS, RHS);
1344 }
Chris Lattner74b64612010-12-19 19:43:52 +00001345
1346 // If the normal result of the add is dead, and the RHS is a constant,
1347 // we can transform this into a range comparison.
1348 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001349 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1350 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1351 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1352 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001353 break;
1354 case Intrinsic::usub_with_overflow:
1355 case Intrinsic::ssub_with_overflow:
1356 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001357 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001358 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001359 EraseInstFromFunction(*II);
1360 return BinaryOperator::CreateSub(LHS, RHS);
1361 }
1362 break;
1363 case Intrinsic::umul_with_overflow:
1364 case Intrinsic::smul_with_overflow:
1365 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001366 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001367 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001368 EraseInstFromFunction(*II);
1369 return BinaryOperator::CreateMul(LHS, RHS);
1370 }
1371 break;
1372 default:
1373 break;
1374 }
1375 }
1376 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001377 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1378 // If the (non-volatile) load only has one use, we can rewrite this to a
1379 // load from a GEP. This reduces the size of the load.
1380 // FIXME: If a load is used only by extractvalue instructions then this
1381 // could be done regardless of having multiple uses.
1382 if (!L->isVolatile() && L->hasOneUse()) {
1383 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1384 SmallVector<Value*, 4> Indices;
1385 // Prefix an i32 0 since we need the first element.
1386 Indices.push_back(Builder->getInt32(0));
1387 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1388 I != E; ++I)
1389 Indices.push_back(Builder->getInt32(*I));
1390
1391 // We need to insert these at the location of the old load, not at that of
1392 // the extractvalue.
1393 Builder->SetInsertPoint(L->getParent(), L);
Jay Foad0a2a60a2011-07-22 08:16:57 +00001394 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001395 // Returning the load directly will cause the main loop to insert it in
1396 // the wrong spot, so use ReplaceInstUsesWith().
1397 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1398 }
1399 // We could simplify extracts from other values. Note that nested extracts may
1400 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001401 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001402 // the value inserted, if appropriate. Similarly for extracts from single-use
1403 // loads: extract (extract (load)) will be translated to extract (load (gep))
1404 // and if again single-use then via load (gep (gep)) to load (gep).
1405 // However, double extracts from e.g. function arguments or return values
1406 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001407 return 0;
1408}
1409
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001410
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001411
Chris Lattnerea1c4542004-12-08 23:43:58 +00001412
1413/// TryToSinkInstruction - Try to move the specified instruction from its
1414/// current block into the beginning of DestBlock, which can only happen if it's
1415/// safe to move the instruction past all of the instructions between it and the
1416/// end of its block.
1417static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1418 assert(I->hasOneUse() && "Invariants didn't hold!");
1419
Bill Wendling9d6070f2011-08-15 21:14:31 +00001420 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1421 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001422 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001423
Chris Lattnerea1c4542004-12-08 23:43:58 +00001424 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001425 if (isa<AllocaInst>(I) && I->getParent() ==
1426 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001427 return false;
1428
Chris Lattner96a52a62004-12-09 07:14:34 +00001429 // We can only sink load instructions if there is nothing between the load and
1430 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001431 if (I->mayReadFromMemory()) {
1432 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001433 Scan != E; ++Scan)
1434 if (Scan->mayWriteToMemory())
1435 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001436 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001437
Dan Gohman02dea8b2008-05-23 21:05:58 +00001438 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00001439
Chris Lattner4bc5f802005-08-08 19:11:57 +00001440 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001441 ++NumSunkInst;
1442 return true;
1443}
1444
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001445
1446/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1447/// all reachable code to the worklist.
1448///
1449/// This has a couple of tricks to make the code faster and more powerful. In
1450/// particular, we constant fold and DCE instructions as we go, to avoid adding
1451/// them to the worklist (this significantly speeds up instcombine on code where
1452/// many instructions are dead or constant). Additionally, if we find a branch
1453/// whose condition is a known constant, we only visit the reachable successors.
1454///
Chris Lattner2ee743b2009-10-15 04:59:28 +00001455static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001456 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001457 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001458 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001459 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001460 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001461 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001462
Benjamin Kramera53fe602010-10-23 17:10:24 +00001463 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001464 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1465
Dan Gohman321a8132010-01-05 16:27:25 +00001466 do {
1467 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001468
1469 // We have now visited this block! If we've already been here, ignore it.
1470 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001471
Chris Lattner2c7718a2007-03-23 19:17:18 +00001472 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1473 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001474
Chris Lattner2c7718a2007-03-23 19:17:18 +00001475 // DCE instruction if trivially dead.
1476 if (isInstructionTriviallyDead(Inst)) {
1477 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001478 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001479 Inst->eraseFromParent();
1480 continue;
1481 }
1482
1483 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001484 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001485 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001486 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1487 << *Inst << '\n');
1488 Inst->replaceAllUsesWith(C);
1489 ++NumConstProp;
1490 Inst->eraseFromParent();
1491 continue;
1492 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001493
Chris Lattner2ee743b2009-10-15 04:59:28 +00001494 if (TD) {
1495 // See if we can constant fold its operands.
1496 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1497 i != e; ++i) {
1498 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1499 if (CE == 0) continue;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001500
1501 Constant*& FoldRes = FoldedConstants[CE];
1502 if (!FoldRes)
1503 FoldRes = ConstantFoldConstantExpression(CE, TD);
1504 if (!FoldRes)
1505 FoldRes = CE;
1506
1507 if (FoldRes != CE) {
1508 *i = FoldRes;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001509 MadeIRChange = true;
1510 }
1511 }
1512 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001513
Chris Lattner67f7d542009-10-12 03:58:40 +00001514 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001515 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001516
1517 // Recursively visit successors. If this is a branch or switch on a
1518 // constant, only visit the reachable successor.
1519 TerminatorInst *TI = BB->getTerminator();
1520 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1521 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1522 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001523 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001524 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001525 continue;
1526 }
1527 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1528 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1529 // See if this is an explicit destination.
1530 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1531 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001532 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001533 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001534 continue;
1535 }
1536
1537 // Otherwise it is the default destination.
1538 Worklist.push_back(SI->getSuccessor(0));
1539 continue;
1540 }
1541 }
1542
1543 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1544 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001545 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001546
1547 // Once we've found all of the instructions to add to instcombine's worklist,
1548 // add them in reverse order. This way instcombine will visit from the top
1549 // of the function down. This jives well with the way that it adds all uses
1550 // of instructions to the worklist after doing a transformation, thus avoiding
1551 // some N^2 behavior in pathological cases.
1552 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1553 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001554
1555 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001556}
1557
Chris Lattnerec9c3582007-03-03 02:04:50 +00001558bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001559 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001560
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001561 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1562 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001563
Chris Lattnerb3d59702005-07-07 20:40:38 +00001564 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001565 // Do a depth-first traversal of the function, populate the worklist with
1566 // the reachable instructions. Ignore blocks that are not reachable. Keep
1567 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001568 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001569 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001570
Chris Lattnerb3d59702005-07-07 20:40:38 +00001571 // Do a quick scan over the function. If we find any blocks that are
1572 // unreachable, remove any instructions inside of them. This prevents
1573 // the instcombine code from having to deal with some bad special cases.
1574 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1575 if (!Visited.count(BB)) {
1576 Instruction *Term = BB->getTerminator();
1577 while (Term != BB->begin()) { // Remove instrs bottom-up
1578 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001579
Chris Lattnerbdff5482009-08-23 04:37:46 +00001580 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001581 // A debug intrinsic shouldn't force another iteration if we weren't
1582 // going to do one without it.
1583 if (!isa<DbgInfoIntrinsic>(I)) {
1584 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001585 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001586 }
Devang Patel228ebd02009-10-13 22:56:32 +00001587
Devang Patel228ebd02009-10-13 22:56:32 +00001588 // If I is not void type then replaceAllUsesWith undef.
1589 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001590 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001591 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001592 I->eraseFromParent();
1593 }
1594 }
1595 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001596
Chris Lattner873ff012009-08-30 05:55:36 +00001597 while (!Worklist.isEmpty()) {
1598 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001599 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001600
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001601 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001602 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001603 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001604 EraseInstFromFunction(*I);
1605 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001606 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001607 continue;
1608 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001609
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001610 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001611 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001612 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001613 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001614
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001615 // Add operands to the worklist.
1616 ReplaceInstUsesWith(*I, C);
1617 ++NumConstProp;
1618 EraseInstFromFunction(*I);
1619 MadeIRChange = true;
1620 continue;
1621 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001622
Chris Lattnerea1c4542004-12-08 23:43:58 +00001623 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001624 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001625 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001626 Instruction *UserInst = cast<Instruction>(I->use_back());
1627 BasicBlock *UserParent;
1628
1629 // Get the block the use occurs in.
1630 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1631 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1632 else
1633 UserParent = UserInst->getParent();
1634
Chris Lattnerea1c4542004-12-08 23:43:58 +00001635 if (UserParent != BB) {
1636 bool UserIsSuccessor = false;
1637 // See if the user is one of our successors.
1638 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1639 if (*SI == UserParent) {
1640 UserIsSuccessor = true;
1641 break;
1642 }
1643
1644 // If the user is one of our immediate successors, and if that successor
1645 // only has us as a predecessors (we'd have to split the critical edge
1646 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001647 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001648 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001649 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001650 }
1651 }
1652
Chris Lattner74381062009-08-30 07:44:24 +00001653 // Now that we have an instruction, try combining it to simplify it.
1654 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedmanef819d02011-05-18 01:28:27 +00001655 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Chris Lattner74381062009-08-30 07:44:24 +00001656
Reid Spencera9b81012007-03-26 17:44:01 +00001657#ifndef NDEBUG
1658 std::string OrigI;
1659#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001660 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001661 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1662
Chris Lattner90ac28c2002-08-02 19:29:35 +00001663 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001664 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001665 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001666 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001667 DEBUG(errs() << "IC: Old = " << *I << '\n'
1668 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001669
Eli Friedmana311c342011-05-27 00:19:40 +00001670 if (!I->getDebugLoc().isUnknown())
1671 Result->setDebugLoc(I->getDebugLoc());
Chris Lattnerf523d062004-06-09 05:08:07 +00001672 // Everything uses the new instruction now.
1673 I->replaceAllUsesWith(Result);
1674
1675 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001676 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001677 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001678
Chris Lattner6934a042007-02-11 01:23:03 +00001679 // Move the name to the new instruction first.
1680 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001681
1682 // Insert the new instruction into the basic block...
1683 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001684 BasicBlock::iterator InsertPos = I;
1685
1686 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1687 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1688 ++InsertPos;
1689
1690 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001691
Chris Lattner7a1e9242009-08-30 06:13:40 +00001692 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001693 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001694#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001695 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1696 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001697#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001698
Chris Lattner90ac28c2002-08-02 19:29:35 +00001699 // If the instruction was modified, it's possible that it is now dead.
1700 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001701 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001702 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001703 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001704 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001705 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001706 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001707 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001708 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001709 }
1710 }
1711
Chris Lattner873ff012009-08-30 05:55:36 +00001712 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001713 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001714}
1715
Chris Lattnerec9c3582007-03-03 02:04:50 +00001716
1717bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001718 TD = getAnalysisIfAvailable<TargetData>();
1719
Chris Lattner74381062009-08-30 07:44:24 +00001720
1721 /// Builder - This is an IRBuilder that automatically inserts new
1722 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001723 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001724 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001725 InstCombineIRInserter(Worklist));
1726 Builder = &TheBuilder;
1727
Chris Lattnerec9c3582007-03-03 02:04:50 +00001728 bool EverMadeChange = false;
1729
Devang Patel813c9a02011-03-17 22:18:16 +00001730 // Lower dbg.declare intrinsics otherwise their value may be clobbered
1731 // by instcombiner.
1732 EverMadeChange = LowerDbgDeclare(F);
1733
Chris Lattnerec9c3582007-03-03 02:04:50 +00001734 // Iterate while there is work to do.
1735 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001736 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001737 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001738
1739 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001740 return EverMadeChange;
1741}
1742
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001743FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001744 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001745}