blob: 2d5773a31fc7665d04ba545efec2156db56421ff [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000038#include "InstCombine.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000040#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000041#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000042#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000044#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000045#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000048#include "llvm/Support/PatternMatch.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000049#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000050#include "llvm/ADT/Statistic.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000051#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000052#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000053#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000056
Chris Lattner0e5f4992006-12-19 21:40:18 +000057STATISTIC(NumCombined , "Number of insts combined");
58STATISTIC(NumConstProp, "Number of constant folds");
59STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sands37bf92b2010-12-22 13:36:08 +000061STATISTIC(NumExpand, "Number of expansions");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000062STATISTIC(NumFactor , "Number of factorizations");
63STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000064
Owen Anderson74cfb0c2010-10-07 20:04:55 +000065// Initialization Routines
66void llvm::initializeInstCombine(PassRegistry &Registry) {
67 initializeInstCombinerPass(Registry);
68}
69
70void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
71 initializeInstCombine(*unwrap(R));
72}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073
Dan Gohman844731a2008-05-13 00:00:25 +000074char InstCombiner::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000075INITIALIZE_PASS(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000076 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000077
Chris Lattnere0b4b722010-01-04 07:17:19 +000078void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
79 AU.addPreservedID(LCSSAID);
80 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 Lattner80f43d32010-01-04 07:53:58 +000087bool InstCombiner::ShouldChangeType(const Type *From, const 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
Chris Lattner33a61132006-05-06 09:00:16 +0000111
Duncan Sands096aa792010-11-13 15:10:37 +0000112/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
113/// operators which are associative or commutative:
114//
115// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116//
Chris Lattner4f98c562003-03-10 21:43:22 +0000117// 1. Order operands such that they are listed from right (least complex) to
118// left (most complex). This puts constants before unary operators before
119// binary operators.
120//
Duncan Sands096aa792010-11-13 15:10:37 +0000121// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000122//
Duncan Sands096aa792010-11-13 15:10:37 +0000123// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
124// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
125//
126// Associative and commutative operators:
127//
128// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
129// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
130// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
131// if C1 and C2 are constants.
132//
133bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000134 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000135 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000136
Duncan Sands096aa792010-11-13 15:10:37 +0000137 do {
138 // Order operands such that they are listed from right (least complex) to
139 // left (most complex). This puts constants before unary operators before
140 // binary operators.
141 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
142 getComplexity(I.getOperand(1)))
143 Changed = !I.swapOperands();
144
145 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
146 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
147
148 if (I.isAssociative()) {
149 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
150 if (Op0 && Op0->getOpcode() == Opcode) {
151 Value *A = Op0->getOperand(0);
152 Value *B = Op0->getOperand(1);
153 Value *C = I.getOperand(1);
154
155 // Does "B op C" simplify?
156 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
157 // It simplifies to V. Form "A op V".
158 I.setOperand(0, A);
159 I.setOperand(1, V);
160 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000161 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000162 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000163 }
Duncan Sands096aa792010-11-13 15:10:37 +0000164 }
165
166 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
167 if (Op1 && Op1->getOpcode() == Opcode) {
168 Value *A = I.getOperand(0);
169 Value *B = Op1->getOperand(0);
170 Value *C = Op1->getOperand(1);
171
172 // Does "A op B" simplify?
173 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
174 // It simplifies to V. Form "V op C".
175 I.setOperand(0, V);
176 I.setOperand(1, C);
177 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000178 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000179 continue;
180 }
181 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000182 }
Duncan Sands096aa792010-11-13 15:10:37 +0000183
184 if (I.isAssociative() && I.isCommutative()) {
185 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
186 if (Op0 && Op0->getOpcode() == Opcode) {
187 Value *A = Op0->getOperand(0);
188 Value *B = Op0->getOperand(1);
189 Value *C = I.getOperand(1);
190
191 // Does "C op A" simplify?
192 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
193 // It simplifies to V. Form "V op B".
194 I.setOperand(0, V);
195 I.setOperand(1, B);
196 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000197 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000198 continue;
199 }
200 }
201
202 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
203 if (Op1 && Op1->getOpcode() == Opcode) {
204 Value *A = I.getOperand(0);
205 Value *B = Op1->getOperand(0);
206 Value *C = Op1->getOperand(1);
207
208 // Does "C op A" simplify?
209 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
210 // It simplifies to V. Form "B op V".
211 I.setOperand(0, B);
212 I.setOperand(1, V);
213 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000214 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000215 continue;
216 }
217 }
218
219 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
220 // if C1 and C2 are constants.
221 if (Op0 && Op1 &&
222 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
223 isa<Constant>(Op0->getOperand(1)) &&
224 isa<Constant>(Op1->getOperand(1)) &&
225 Op0->hasOneUse() && Op1->hasOneUse()) {
226 Value *A = Op0->getOperand(0);
227 Constant *C1 = cast<Constant>(Op0->getOperand(1));
228 Value *B = Op1->getOperand(0);
229 Constant *C2 = cast<Constant>(Op1->getOperand(1));
230
231 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
232 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
233 &I);
234 Worklist.Add(New);
235 I.setOperand(0, New);
236 I.setOperand(1, Folded);
237 Changed = true;
238 continue;
239 }
240 }
241
242 // No further simplifications.
243 return Changed;
244 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000245}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000246
Duncan Sands5057f382010-11-23 14:23:47 +0000247/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000248/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000249static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
250 Instruction::BinaryOps ROp) {
251 switch (LOp) {
252 default:
253 return false;
254
255 case Instruction::And:
256 // And distributes over Or and Xor.
257 switch (ROp) {
258 default:
259 return false;
260 case Instruction::Or:
261 case Instruction::Xor:
262 return true;
263 }
264
265 case Instruction::Mul:
266 // Multiplication distributes over addition and subtraction.
267 switch (ROp) {
268 default:
269 return false;
270 case Instruction::Add:
271 case Instruction::Sub:
272 return true;
273 }
274
275 case Instruction::Or:
276 // Or distributes over And.
277 switch (ROp) {
278 default:
279 return false;
280 case Instruction::And:
281 return true;
282 }
283 }
284}
285
286/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
287/// "(X ROp Z) LOp (Y ROp Z)".
288static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
289 Instruction::BinaryOps ROp) {
290 if (Instruction::isCommutative(ROp))
291 return LeftDistributesOverRight(ROp, LOp);
292 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
293 // but this requires knowing that the addition does not overflow and other
294 // such subtleties.
295 return false;
296}
297
Duncan Sands37bf92b2010-12-22 13:36:08 +0000298/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
299/// which some other binary operation distributes over either by factorizing
300/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
301/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
302/// a win). Returns the simplified value, or null if it didn't simplify.
303Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
304 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
305 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
306 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
307 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
Duncan Sands5057f382010-11-23 14:23:47 +0000308
Duncan Sands37bf92b2010-12-22 13:36:08 +0000309 // Factorization.
310 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
311 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
312 // a common term.
313 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
314 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
315 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
Duncan Sands5057f382010-11-23 14:23:47 +0000316
Duncan Sands37bf92b2010-12-22 13:36:08 +0000317 // Does "X op' Y" always equal "Y op' X"?
318 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
Duncan Sands5057f382010-11-23 14:23:47 +0000319
Duncan Sands37bf92b2010-12-22 13:36:08 +0000320 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
321 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
322 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
323 // commutative case, "(A op' B) op (C op' A)"?
324 if (A == C || (InnerCommutative && A == D)) {
325 if (A != C)
326 std::swap(C, D);
327 // Consider forming "A op' (B op D)".
328 // If "B op D" simplifies then it can be formed with no cost.
329 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
330 // If "B op D" doesn't simplify then only go on if both of the existing
331 // operations "A op' B" and "C op' D" will be zapped as no longer used.
332 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
333 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
334 if (V) {
335 ++NumFactor;
336 V = Builder->CreateBinOp(InnerOpcode, A, V);
337 V->takeName(&I);
338 return V;
339 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000340 }
Duncan Sands5057f382010-11-23 14:23:47 +0000341
Duncan Sands37bf92b2010-12-22 13:36:08 +0000342 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
343 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
344 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
345 // commutative case, "(A op' B) op (B op' D)"?
346 if (B == D || (InnerCommutative && B == C)) {
347 if (B != D)
348 std::swap(C, D);
349 // Consider forming "(A op C) op' B".
350 // If "A op C" simplifies then it can be formed with no cost.
351 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
352 // If "A op C" doesn't simplify then only go on if both of the existing
353 // operations "A op' B" and "C op' D" will be zapped as no longer used.
354 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
355 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
356 if (V) {
357 ++NumFactor;
358 V = Builder->CreateBinOp(InnerOpcode, V, B);
359 V->takeName(&I);
360 return V;
361 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000362 }
Duncan Sands37bf92b2010-12-22 13:36:08 +0000363 }
364
365 // Expansion.
366 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
367 // The instruction has the form "(A op' B) op C". See if expanding it out
368 // to "(A op C) op' (B op C)" results in simplifications.
369 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
370 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
371
372 // Do "A op C" and "B op C" both simplify?
373 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
374 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
375 // They do! Return "L op' R".
376 ++NumExpand;
377 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
378 if ((L == A && R == B) ||
379 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
380 return Op0;
381 // Otherwise return "L op' R" if it simplifies.
382 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
383 return V;
384 // Otherwise, create a new instruction.
385 C = Builder->CreateBinOp(InnerOpcode, L, R);
386 C->takeName(&I);
387 return C;
388 }
389 }
390
391 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
392 // The instruction has the form "A op (B op' C)". See if expanding it out
393 // to "(A op B) op' (A op C)" results in simplifications.
394 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
395 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
396
397 // Do "A op B" and "A op C" both simplify?
398 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
399 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
400 // They do! Return "L op' R".
401 ++NumExpand;
402 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
403 if ((L == B && R == C) ||
404 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
405 return Op1;
406 // Otherwise return "L op' R" if it simplifies.
407 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
408 return V;
409 // Otherwise, create a new instruction.
410 A = Builder->CreateBinOp(InnerOpcode, L, R);
411 A->takeName(&I);
412 return A;
413 }
414 }
Duncan Sands5057f382010-11-23 14:23:47 +0000415
416 return 0;
417}
418
Chris Lattner8d969642003-03-10 23:06:50 +0000419// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
420// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000421//
Chris Lattner02446fc2010-01-04 07:37:31 +0000422Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000423 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000424 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000425
Chris Lattner0ce85802004-12-14 20:08:06 +0000426 // Constants can be considered to be negated values if they can be folded.
427 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000428 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000429
430 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000431 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000432 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000433
Chris Lattner8d969642003-03-10 23:06:50 +0000434 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000435}
436
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000437// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
438// instruction if the LHS is a constant negative zero (which is the 'negate'
439// form).
440//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000441Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000442 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000443 return BinaryOperator::getFNegArgument(V);
444
445 // Constants can be considered to be negated values if they can be folded.
446 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000447 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000448
449 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000450 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000451 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000452
453 return 0;
454}
455
Chris Lattner6e7ba452005-01-01 16:22:27 +0000456static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000457 InstCombiner *IC) {
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000458 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +0000459 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000460 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000461
Chris Lattner2eefe512004-04-09 19:05:30 +0000462 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000463 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
464 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000465
Chris Lattner2eefe512004-04-09 19:05:30 +0000466 if (Constant *SOC = dyn_cast<Constant>(SO)) {
467 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000468 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
469 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000470 }
471
472 Value *Op0 = SO, *Op1 = ConstOperand;
473 if (!ConstIsRHS)
474 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000475
Chris Lattner6e7ba452005-01-01 16:22:27 +0000476 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000477 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
478 SO->getName()+".op");
479 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
480 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
481 SO->getName()+".cmp");
482 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
483 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
484 SO->getName()+".cmp");
485 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000486}
487
488// FoldOpIntoSelect - Given an instruction with a select as one operand and a
489// constant as the other operand, try to fold the binary operator into the
490// select arguments. This also works for Cast instructions, which obviously do
491// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000492Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000493 // Don't modify shared select instructions
494 if (!SI->hasOneUse()) return 0;
495 Value *TV = SI->getOperand(1);
496 Value *FV = SI->getOperand(2);
497
498 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000499 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000500 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000501
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000502 // If it's a bitcast involving vectors, make sure it has the same number of
503 // elements on both sides.
504 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
505 const VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
506 const VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
507
508 // Verify that either both or neither are vectors.
509 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
510 // If vectors, verify that they have the same number of elements.
511 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
512 return 0;
513 }
514
Chris Lattner80f43d32010-01-04 07:53:58 +0000515 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
516 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000517
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000518 return SelectInst::Create(SI->getCondition(),
519 SelectTrueVal, SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000520 }
521 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000522}
523
Chris Lattner4e998b22004-09-29 05:07:12 +0000524
Chris Lattner5d1704d2009-09-27 19:57:57 +0000525/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
526/// has a PHI node as operand #0, see if we can fold the instruction into the
527/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000528///
Chris Lattner9922ccf2011-01-16 05:14:26 +0000529Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000530 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000531 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner5aac8322011-01-16 04:37:29 +0000532 if (NumPHIValues == 0)
Chris Lattner213cd612009-09-27 20:46:36 +0000533 return 0;
534
Chris Lattner084fe622011-01-21 05:08:26 +0000535 // We normally only transform phis with a single use. However, if a PHI has
536 // multiple uses and they are all the same operation, we can fold *all* of the
537 // uses into the PHI.
Chris Lattner192228e2011-01-16 05:28:59 +0000538 if (!PN->hasOneUse()) {
539 // Walk the use list for the instruction, comparing them to I.
540 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnercd151d22011-01-21 05:29:50 +0000541 UI != E; ++UI) {
542 Instruction *User = cast<Instruction>(*UI);
543 if (User != &I && !I.isIdenticalTo(User))
Chris Lattner192228e2011-01-16 05:28:59 +0000544 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000545 }
Chris Lattner192228e2011-01-16 05:28:59 +0000546 // Otherwise, we can replace *all* users with the new PHI we form.
547 }
Chris Lattner213cd612009-09-27 20:46:36 +0000548
Chris Lattner5d1704d2009-09-27 19:57:57 +0000549 // Check to see if all of the operands of the PHI are simple constants
550 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000551 // remember the BB it is in. If there is more than one or if *it* is a PHI,
552 // bail out. We don't do arbitrary constant expressions here because moving
553 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000554 BasicBlock *NonConstBB = 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000555 for (unsigned i = 0; i != NumPHIValues; ++i) {
556 Value *InVal = PN->getIncomingValue(i);
557 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
558 continue;
559
560 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
561 if (NonConstBB) return 0; // More than one non-const value.
562
563 NonConstBB = PN->getIncomingBlock(i);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000564
565 // If the InVal is an invoke at the end of the pred block, then we can't
566 // insert a computation after it without breaking the edge.
567 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
568 if (II->getParent() == NonConstBB)
569 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000570
571 // If the incoming non-constant value is in I's block, we will remove one
572 // instruction, but insert another equivalent one, leading to infinite
573 // instcombine.
574 if (NonConstBB == I.getParent())
575 return 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000576 }
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000577
578 // If there is exactly one non-constant value, we can insert a copy of the
579 // operation in that block. However, if this is a critical edge, we would be
580 // inserting the computation one some other paths (e.g. inside a loop). Only
581 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9922ccf2011-01-16 05:14:26 +0000582 if (NonConstBB != 0) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000583 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
584 if (!BI || !BI->isUnconditional()) return 0;
585 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000586
587 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000588 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000589 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000590 InsertNewInstBefore(NewPN, *PN);
591 NewPN->takeName(PN);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000592
593 // If we are going to have to insert a new computation, do so right before the
594 // predecessors terminator.
595 if (NonConstBB)
596 Builder->SetInsertPoint(NonConstBB->getTerminator());
597
Chris Lattner4e998b22004-09-29 05:07:12 +0000598 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000599 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
600 // We only currently try to fold the condition of a select when it is a phi,
601 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000602 Value *TrueV = SI->getTrueValue();
603 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000604 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000605 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000606 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000607 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
608 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000609 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000610 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000611 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000612 else
613 InV = Builder->CreateSelect(PN->getIncomingValue(i),
614 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000615 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000616 }
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000617 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
618 Constant *C = cast<Constant>(I.getOperand(1));
619 for (unsigned i = 0; i != NumPHIValues; ++i) {
620 Value *InV = 0;
621 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
622 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
623 else if (isa<ICmpInst>(CI))
624 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
625 C, "phitmp");
626 else
627 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
628 C, "phitmp");
629 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
630 }
Chris Lattner5d1704d2009-09-27 19:57:57 +0000631 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000632 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000633 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000634 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000635 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
636 InV = ConstantExpr::get(I.getOpcode(), InC, C);
637 else
638 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
639 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000640 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000641 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000642 } else {
643 CastInst *CI = cast<CastInst>(&I);
644 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000645 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000646 Value *InV;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000647 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000648 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000649 else
650 InV = Builder->CreateCast(CI->getOpcode(),
651 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000652 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000653 }
654 }
Chris Lattner192228e2011-01-16 05:28:59 +0000655
656 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
657 UI != E; ) {
658 Instruction *User = cast<Instruction>(*UI++);
659 if (User == &I) continue;
660 ReplaceInstUsesWith(*User, NewPN);
661 EraseInstFromFunction(*User);
662 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000663 return ReplaceInstUsesWith(I, NewPN);
664}
665
Chris Lattner46cd5a12009-01-09 05:44:56 +0000666/// FindElementAtOffset - Given a type and a constant offset, determine whether
667/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000668/// the specified offset. If so, fill them into NewIndices and return the
669/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +0000670const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
671 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000672 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000673 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000674
675 // Start with the index over the outer type. Note that the type size
676 // might be zero (even if the offset isn't zero) if the indexed type
677 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +0000678 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000679 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000680 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000681 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000682 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000683
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000684 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000685 if (Offset < 0) {
686 --FirstIdx;
687 Offset += TySize;
688 assert(Offset >= 0);
689 }
690 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
691 }
692
Owen Andersoneed707b2009-07-24 23:12:02 +0000693 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000694
695 // Index into the types. If we fail, set OrigBase to null.
696 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000697 // Indexing into tail padding between struct/array elements.
698 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000699 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000700
Chris Lattner46cd5a12009-01-09 05:44:56 +0000701 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
702 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000703 assert(Offset < (int64_t)SL->getSizeInBytes() &&
704 "Offset must stay within the indexed type");
705
Chris Lattner46cd5a12009-01-09 05:44:56 +0000706 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000707 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
708 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000709
710 Offset -= SL->getElementOffset(Elt);
711 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +0000712 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000713 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000714 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000715 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000716 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000717 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000718 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000719 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000720 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000721 }
722 }
723
Chris Lattner3914f722009-01-24 01:00:13 +0000724 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000725}
726
Chris Lattner8a2a3112001-12-14 16:52:21 +0000727
Chris Lattner473945d2002-05-06 18:06:38 +0000728
Chris Lattner7e708292002-06-25 16:13:24 +0000729Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000730 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
731
732 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
733 return ReplaceInstUsesWith(GEP, V);
734
Chris Lattner620ce142004-05-07 22:09:22 +0000735 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000736
Duncan Sandsa63395a2010-11-22 16:32:50 +0000737 // Eliminate unneeded casts for indices, and replace indices which displace
738 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000739 if (TD) {
740 bool MadeChange = false;
Duncan Sandsa63395a2010-11-22 16:32:50 +0000741 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
742
Chris Lattnerccf4b342009-08-30 04:49:01 +0000743 gep_type_iterator GTI = gep_type_begin(GEP);
744 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
745 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000746 // Skip indices into struct types.
747 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
748 if (!SeqTy) continue;
749
750 // If the element type has zero size then any index over it is equivalent
751 // to an index of zero, so replace it with zero if it is not zero already.
752 if (SeqTy->getElementType()->isSized() &&
753 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
754 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
755 *I = Constant::getNullValue(IntPtrTy);
756 MadeChange = true;
757 }
758
759 if ((*I)->getType() != IntPtrTy) {
760 // If we are using a wider index than needed for this platform, shrink
761 // it to what we need. If narrower, sign-extend it to what we need.
762 // This explicit cast can make subsequent optimizations more obvious.
763 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
764 MadeChange = true;
765 }
Chris Lattner28977af2004-04-05 01:30:19 +0000766 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000767 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000768 }
Chris Lattner28977af2004-04-05 01:30:19 +0000769
Chris Lattner90ac28c2002-08-02 19:29:35 +0000770 // Combine Indices - If the source pointer to this getelementptr instruction
771 // is a getelementptr instruction, combine the indices of the two
772 // getelementptr instructions into a single instruction.
773 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000774 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +0000775 // Note that if our source is a gep chain itself that we wait for that
776 // chain to be resolved before we perform this transformation. This
777 // avoids us creating a TON of code in some cases.
778 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000779 if (GetElementPtrInst *SrcGEP =
780 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
781 if (SrcGEP->getNumOperands() == 2)
782 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000783
Chris Lattner72588fc2007-02-15 22:48:32 +0000784 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000785
786 // Find out whether the last index in the source GEP is a sequential idx.
787 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000788 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
789 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000790 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000791
Chris Lattner90ac28c2002-08-02 19:29:35 +0000792 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000793 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000794 // Replace: gep (gep %P, long B), long A, ...
795 // With: T = long A+B; gep %P, T, ...
796 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000797 Value *Sum;
798 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
799 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000800 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000801 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000802 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000803 Sum = SO1;
804 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000805 // If they aren't the same type, then the input hasn't been processed
806 // by the loop above yet (which canonicalizes sequential index types to
807 // intptr_t). Just avoid transforming this until the input has been
808 // normalized.
809 if (SO1->getType() != GO1->getType())
810 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000811 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000812 }
Chris Lattner620ce142004-05-07 22:09:22 +0000813
Chris Lattnerab984842009-08-30 05:30:55 +0000814 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000815 if (Src->getNumOperands() == 2) {
816 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000817 GEP.setOperand(1, Sum);
818 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000819 }
Chris Lattnerab984842009-08-30 05:30:55 +0000820 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000821 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000822 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000823 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000824 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000825 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000826 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000827 Indices.append(Src->op_begin()+1, Src->op_end());
828 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000829 }
830
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000831 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000832 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000833 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
834 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000835 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +0000836 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000837 }
838
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000839 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000840 Value *StrippedPtr = PtrOp->stripPointerCasts();
841 if (StrippedPtr != PtrOp) {
842 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattner963f4ba2009-08-30 20:36:46 +0000843
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000844 bool HasZeroPointerIndex = false;
845 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
846 HasZeroPointerIndex = C->isZero();
847
Chris Lattner963f4ba2009-08-30 20:36:46 +0000848 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
849 // into : GEP [10 x i8]* X, i32 0, ...
850 //
851 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
852 // into : GEP i8* X, ...
853 //
854 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000855 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +0000856 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000857 if (const ArrayType *CATy =
858 dyn_cast<ArrayType>(CPTy->getElementType())) {
859 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000860 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000861 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000862 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
863 GetElementPtrInst *Res =
864 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
865 Idx.end(), GEP.getName());
866 Res->setIsInBounds(GEP.isInBounds());
867 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000868 }
869
Chris Lattner948cdeb2010-01-05 07:42:10 +0000870 if (const ArrayType *XATy =
871 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000872 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000873 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000874 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000875 // At this point, we know that the cast source type is a pointer
876 // to an array of the same type as the destination pointer
877 // array. Because the array type is never stepped over (there
878 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000879 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000880 return &GEP;
881 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000882 }
883 }
Chris Lattnereed48272005-09-13 00:40:14 +0000884 } else if (GEP.getNumOperands() == 2) {
885 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000886 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
887 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner948cdeb2010-01-05 07:42:10 +0000888 const Type *SrcElTy = StrippedPtrTy->getElementType();
Chris Lattnereed48272005-09-13 00:40:14 +0000889 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000890 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000891 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
892 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000893 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000894 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000895 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000896 Value *NewGEP = GEP.isInBounds() ?
897 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
898 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000899 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000900 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000901 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000902
903 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000904 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000905 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000906 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000907
Duncan Sands1df98592010-02-16 11:11:14 +0000908 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000909 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000910 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000911
912 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
913 // allow either a mul, shift, or constant here.
914 Value *NewIdx = 0;
915 ConstantInt *Scale = 0;
916 if (ArrayEltSize == 1) {
917 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000918 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000919 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000920 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000921 Scale = CI;
922 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
923 if (Inst->getOpcode() == Instruction::Shl &&
924 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000925 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
926 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000927 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000928 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000929 NewIdx = Inst->getOperand(0);
930 } else if (Inst->getOpcode() == Instruction::Mul &&
931 isa<ConstantInt>(Inst->getOperand(1))) {
932 Scale = cast<ConstantInt>(Inst->getOperand(1));
933 NewIdx = Inst->getOperand(0);
934 }
935 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000936
Chris Lattner7835cdd2005-09-13 18:36:04 +0000937 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000938 // out, perform the transformation. Note, we don't know whether Scale is
939 // signed or not. We'll use unsigned version of division/modulo
940 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +0000941 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000942 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000943 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000944 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +0000945 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +0000946 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
947 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000948 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +0000949 }
950
951 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +0000952 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000953 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000954 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +0000955 Value *NewGEP = GEP.isInBounds() ?
956 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
957 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000958 // The NewGEP must be pointer typed, so must the old one -> BitCast
959 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000960 }
961 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000962 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000963 }
Chris Lattner58407792009-01-09 04:53:57 +0000964
Chris Lattner46cd5a12009-01-09 05:44:56 +0000965 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +0000966 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +0000967 /// Y = gep X, <...constant indices...>
968 /// into a gep of the original struct. This is important for SROA and alias
969 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +0000970 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000971 if (TD &&
972 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000973 // Determine how much the GEP moves the pointer. We are guaranteed to get
974 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +0000975 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000976 int64_t Offset = OffsetV->getSExtValue();
977
978 // If this GEP instruction doesn't move the pointer, just replace the GEP
979 // with a bitcast of the real input to the dest type.
980 if (Offset == 0) {
981 // If the bitcast is of an allocation, and the allocation will be
982 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000983 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +0000984 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000985 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
986 if (Instruction *I = visitBitCast(*BCI)) {
987 if (I != BCI) {
988 I->takeName(BCI);
989 BCI->getParent()->getInstList().insert(BCI, I);
990 ReplaceInstUsesWith(*BCI, I);
991 }
992 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +0000993 }
Chris Lattner58407792009-01-09 04:53:57 +0000994 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000995 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +0000996 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000997
998 // Otherwise, if the offset is non-zero, we need to find out if there is a
999 // field at Offset in 'A's type. If so, we can pull the cast through the
1000 // GEP.
1001 SmallVector<Value*, 8> NewIndices;
1002 const Type *InTy =
1003 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001004 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00001005 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +00001006 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
1007 NewIndices.end()) :
1008 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
1009 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001010
1011 if (NGEP->getType() == GEP.getType())
1012 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00001013 NGEP->takeName(&GEP);
1014 return new BitCastInst(NGEP, GEP.getType());
1015 }
Chris Lattner58407792009-01-09 04:53:57 +00001016 }
1017 }
1018
Chris Lattner8a2a3112001-12-14 16:52:21 +00001019 return 0;
1020}
1021
Duncan Sands1d9b9732010-05-27 19:09:06 +00001022
1023
1024static bool IsOnlyNullComparedAndFreed(const Value &V) {
1025 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
1026 UI != UE; ++UI) {
Gabor Greiffc36c0f2010-07-09 15:01:36 +00001027 const User *U = *UI;
1028 if (isFreeCall(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +00001029 continue;
Gabor Greiffc36c0f2010-07-09 15:01:36 +00001030 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +00001031 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
1032 continue;
1033 return false;
1034 }
1035 return true;
1036}
1037
1038Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1039 // If we have a malloc call which is only used in any amount of comparisons
1040 // to null and free calls, delete the calls and replace the comparisons with
1041 // true or false as appropriate.
1042 if (IsOnlyNullComparedAndFreed(MI)) {
1043 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
1044 UI != UE;) {
1045 // We can assume that every remaining use is a free call or an icmp eq/ne
1046 // to null, so the cast is safe.
1047 Instruction *I = cast<Instruction>(*UI);
1048
1049 // Early increment here, as we're about to get rid of the user.
1050 ++UI;
1051
1052 if (isFreeCall(I)) {
1053 EraseInstFromFunction(*cast<CallInst>(I));
1054 continue;
1055 }
1056 // Again, the cast is safe.
1057 ICmpInst *C = cast<ICmpInst>(I);
1058 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
1059 C->isFalseWhenEqual()));
1060 EraseInstFromFunction(*C);
1061 }
1062 return EraseInstFromFunction(MI);
1063 }
1064 return 0;
1065}
1066
1067
1068
Gabor Greif91697372010-06-24 12:21:15 +00001069Instruction *InstCombiner::visitFree(CallInst &FI) {
1070 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +00001071
1072 // free undef -> unreachable.
1073 if (isa<UndefValue>(Op)) {
1074 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +00001075 new StoreInst(ConstantInt::getTrue(FI.getContext()),
1076 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +00001077 return EraseInstFromFunction(FI);
1078 }
1079
1080 // If we have 'free null' delete the instruction. This can happen in stl code
1081 // when lots of inlining happens.
1082 if (isa<ConstantPointerNull>(Op))
1083 return EraseInstFromFunction(FI);
1084
Victor Hernandez66284e02009-10-24 04:23:03 +00001085 return 0;
1086}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00001087
Chris Lattner3284d1f2007-04-15 00:07:55 +00001088
Chris Lattner2f503e62005-01-31 05:36:43 +00001089
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001090Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1091 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001092 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001093 BasicBlock *TrueDest;
1094 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001095 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001096 !isa<Constant>(X)) {
1097 // Swap Destinations and condition...
1098 BI.setCondition(X);
1099 BI.setSuccessor(0, FalseDest);
1100 BI.setSuccessor(1, TrueDest);
1101 return &BI;
1102 }
1103
Reid Spencere4d87aa2006-12-23 06:05:41 +00001104 // Cannonicalize fcmp_one -> fcmp_oeq
1105 FCmpInst::Predicate FPred; Value *Y;
1106 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001107 TrueDest, FalseDest)) &&
1108 BI.getCondition()->hasOneUse())
1109 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1110 FPred == FCmpInst::FCMP_OGE) {
1111 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1112 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1113
1114 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001115 BI.setSuccessor(0, FalseDest);
1116 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001117 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001118 return &BI;
1119 }
1120
1121 // Cannonicalize icmp_ne -> icmp_eq
1122 ICmpInst::Predicate IPred;
1123 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001124 TrueDest, FalseDest)) &&
1125 BI.getCondition()->hasOneUse())
1126 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1127 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1128 IPred == ICmpInst::ICMP_SGE) {
1129 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1130 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1131 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00001132 BI.setSuccessor(0, FalseDest);
1133 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001134 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001135 return &BI;
1136 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001137
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001138 return 0;
1139}
Chris Lattner0864acf2002-11-04 16:18:53 +00001140
Chris Lattner46238a62004-07-03 00:26:11 +00001141Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1142 Value *Cond = SI.getCondition();
1143 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1144 if (I->getOpcode() == Instruction::Add)
1145 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1146 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1147 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00001148 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00001149 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00001150 AddRHS));
1151 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001152 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001153 return &SI;
1154 }
1155 }
1156 return 0;
1157}
1158
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001159Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001160 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001161
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001162 if (!EV.hasIndices())
1163 return ReplaceInstUsesWith(EV, Agg);
1164
1165 if (Constant *C = dyn_cast<Constant>(Agg)) {
1166 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001167 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001168
1169 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00001170 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001171
1172 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1173 // Extract the element indexed by the first index out of the constant
1174 Value *V = C->getOperand(*EV.idx_begin());
1175 if (EV.getNumIndices() > 1)
1176 // Extract the remaining indices out of the constant indexed by the
1177 // first index
1178 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1179 else
1180 return ReplaceInstUsesWith(EV, V);
1181 }
1182 return 0; // Can't handle other constants
1183 }
1184 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1185 // We're extracting from an insertvalue instruction, compare the indices
1186 const unsigned *exti, *exte, *insi, *inse;
1187 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1188 exte = EV.idx_end(), inse = IV->idx_end();
1189 exti != exte && insi != inse;
1190 ++exti, ++insi) {
1191 if (*insi != *exti)
1192 // The insert and extract both reference distinctly different elements.
1193 // This means the extract is not influenced by the insert, and we can
1194 // replace the aggregate operand of the extract with the aggregate
1195 // operand of the insert. i.e., replace
1196 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1197 // %E = extractvalue { i32, { i32 } } %I, 0
1198 // with
1199 // %E = extractvalue { i32, { i32 } } %A, 0
1200 return ExtractValueInst::Create(IV->getAggregateOperand(),
1201 EV.idx_begin(), EV.idx_end());
1202 }
1203 if (exti == exte && insi == inse)
1204 // Both iterators are at the end: Index lists are identical. Replace
1205 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1206 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1207 // with "i32 42"
1208 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1209 if (exti == exte) {
1210 // The extract list is a prefix of the insert list. i.e. replace
1211 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1212 // %E = extractvalue { i32, { i32 } } %I, 1
1213 // with
1214 // %X = extractvalue { i32, { i32 } } %A, 1
1215 // %E = insertvalue { i32 } %X, i32 42, 0
1216 // by switching the order of the insert and extract (though the
1217 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001218 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1219 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001220 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1221 insi, inse);
1222 }
1223 if (insi == inse)
1224 // The insert list is a prefix of the extract list
1225 // We can simply remove the common indices from the extract and make it
1226 // operate on the inserted value instead of the insertvalue result.
1227 // i.e., replace
1228 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1229 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1230 // with
1231 // %E extractvalue { i32 } { i32 42 }, 0
1232 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1233 exti, exte);
1234 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001235 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1236 // We're extracting from an intrinsic, see if we're the only user, which
1237 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001238 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001239 if (II->hasOneUse()) {
1240 // Check if we're grabbing the overflow bit or the result of a 'with
1241 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1242 // and replace it with a traditional binary instruction.
1243 switch (II->getIntrinsicID()) {
1244 case Intrinsic::uadd_with_overflow:
1245 case Intrinsic::sadd_with_overflow:
1246 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001247 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001248 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1249 EraseInstFromFunction(*II);
1250 return BinaryOperator::CreateAdd(LHS, RHS);
1251 }
Chris Lattner74b64612010-12-19 19:43:52 +00001252
1253 // If the normal result of the add is dead, and the RHS is a constant,
1254 // we can transform this into a range comparison.
1255 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001256 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1257 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1258 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1259 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001260 break;
1261 case Intrinsic::usub_with_overflow:
1262 case Intrinsic::ssub_with_overflow:
1263 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001264 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001265 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1266 EraseInstFromFunction(*II);
1267 return BinaryOperator::CreateSub(LHS, RHS);
1268 }
1269 break;
1270 case Intrinsic::umul_with_overflow:
1271 case Intrinsic::smul_with_overflow:
1272 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001273 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001274 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1275 EraseInstFromFunction(*II);
1276 return BinaryOperator::CreateMul(LHS, RHS);
1277 }
1278 break;
1279 default:
1280 break;
1281 }
1282 }
1283 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001284 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1285 // If the (non-volatile) load only has one use, we can rewrite this to a
1286 // load from a GEP. This reduces the size of the load.
1287 // FIXME: If a load is used only by extractvalue instructions then this
1288 // could be done regardless of having multiple uses.
1289 if (!L->isVolatile() && L->hasOneUse()) {
1290 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1291 SmallVector<Value*, 4> Indices;
1292 // Prefix an i32 0 since we need the first element.
1293 Indices.push_back(Builder->getInt32(0));
1294 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1295 I != E; ++I)
1296 Indices.push_back(Builder->getInt32(*I));
1297
1298 // We need to insert these at the location of the old load, not at that of
1299 // the extractvalue.
1300 Builder->SetInsertPoint(L->getParent(), L);
1301 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(),
1302 Indices.begin(), Indices.end());
1303 // Returning the load directly will cause the main loop to insert it in
1304 // the wrong spot, so use ReplaceInstUsesWith().
1305 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1306 }
1307 // We could simplify extracts from other values. Note that nested extracts may
1308 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001309 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001310 // the value inserted, if appropriate. Similarly for extracts from single-use
1311 // loads: extract (extract (load)) will be translated to extract (load (gep))
1312 // and if again single-use then via load (gep (gep)) to load (gep).
1313 // However, double extracts from e.g. function arguments or return values
1314 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001315 return 0;
1316}
1317
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001318
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001319
Chris Lattnerea1c4542004-12-08 23:43:58 +00001320
1321/// TryToSinkInstruction - Try to move the specified instruction from its
1322/// current block into the beginning of DestBlock, which can only happen if it's
1323/// safe to move the instruction past all of the instructions between it and the
1324/// end of its block.
1325static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1326 assert(I->hasOneUse() && "Invariants didn't hold!");
1327
Chris Lattner108e9022005-10-27 17:13:11 +00001328 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00001329 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001330 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001331
Chris Lattnerea1c4542004-12-08 23:43:58 +00001332 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001333 if (isa<AllocaInst>(I) && I->getParent() ==
1334 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001335 return false;
1336
Chris Lattner96a52a62004-12-09 07:14:34 +00001337 // We can only sink load instructions if there is nothing between the load and
1338 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001339 if (I->mayReadFromMemory()) {
1340 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001341 Scan != E; ++Scan)
1342 if (Scan->mayWriteToMemory())
1343 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001344 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001345
Dan Gohman02dea8b2008-05-23 21:05:58 +00001346 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00001347
Chris Lattner4bc5f802005-08-08 19:11:57 +00001348 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001349 ++NumSunkInst;
1350 return true;
1351}
1352
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001353
1354/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1355/// all reachable code to the worklist.
1356///
1357/// This has a couple of tricks to make the code faster and more powerful. In
1358/// particular, we constant fold and DCE instructions as we go, to avoid adding
1359/// them to the worklist (this significantly speeds up instcombine on code where
1360/// many instructions are dead or constant). Additionally, if we find a branch
1361/// whose condition is a known constant, we only visit the reachable successors.
1362///
Chris Lattner2ee743b2009-10-15 04:59:28 +00001363static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001364 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001365 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001366 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001367 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001368 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001369 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001370
Benjamin Kramera53fe602010-10-23 17:10:24 +00001371 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001372 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1373
Dan Gohman321a8132010-01-05 16:27:25 +00001374 do {
1375 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001376
1377 // We have now visited this block! If we've already been here, ignore it.
1378 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001379
Chris Lattner2c7718a2007-03-23 19:17:18 +00001380 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1381 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001382
Chris Lattner2c7718a2007-03-23 19:17:18 +00001383 // DCE instruction if trivially dead.
1384 if (isInstructionTriviallyDead(Inst)) {
1385 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001386 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001387 Inst->eraseFromParent();
1388 continue;
1389 }
1390
1391 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001392 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001393 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001394 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1395 << *Inst << '\n');
1396 Inst->replaceAllUsesWith(C);
1397 ++NumConstProp;
1398 Inst->eraseFromParent();
1399 continue;
1400 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001401
Chris Lattner2ee743b2009-10-15 04:59:28 +00001402 if (TD) {
1403 // See if we can constant fold its operands.
1404 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1405 i != e; ++i) {
1406 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1407 if (CE == 0) continue;
1408
1409 // If we already folded this constant, don't try again.
1410 if (!FoldedConstants.insert(CE))
1411 continue;
1412
Chris Lattner7b550cc2009-11-06 04:27:31 +00001413 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00001414 if (NewC && NewC != CE) {
1415 *i = NewC;
1416 MadeIRChange = true;
1417 }
1418 }
1419 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001420
Chris Lattner67f7d542009-10-12 03:58:40 +00001421 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001422 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001423
1424 // Recursively visit successors. If this is a branch or switch on a
1425 // constant, only visit the reachable successor.
1426 TerminatorInst *TI = BB->getTerminator();
1427 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1428 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1429 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001430 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001431 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001432 continue;
1433 }
1434 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1435 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1436 // See if this is an explicit destination.
1437 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1438 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001439 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001440 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001441 continue;
1442 }
1443
1444 // Otherwise it is the default destination.
1445 Worklist.push_back(SI->getSuccessor(0));
1446 continue;
1447 }
1448 }
1449
1450 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1451 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001452 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001453
1454 // Once we've found all of the instructions to add to instcombine's worklist,
1455 // add them in reverse order. This way instcombine will visit from the top
1456 // of the function down. This jives well with the way that it adds all uses
1457 // of instructions to the worklist after doing a transformation, thus avoiding
1458 // some N^2 behavior in pathological cases.
1459 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1460 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001461
1462 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001463}
1464
Chris Lattnerec9c3582007-03-03 02:04:50 +00001465bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001466 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001467
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001468 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1469 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001470
Chris Lattnerb3d59702005-07-07 20:40:38 +00001471 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001472 // Do a depth-first traversal of the function, populate the worklist with
1473 // the reachable instructions. Ignore blocks that are not reachable. Keep
1474 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001475 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001476 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001477
Chris Lattnerb3d59702005-07-07 20:40:38 +00001478 // Do a quick scan over the function. If we find any blocks that are
1479 // unreachable, remove any instructions inside of them. This prevents
1480 // the instcombine code from having to deal with some bad special cases.
1481 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1482 if (!Visited.count(BB)) {
1483 Instruction *Term = BB->getTerminator();
1484 while (Term != BB->begin()) { // Remove instrs bottom-up
1485 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001486
Chris Lattnerbdff5482009-08-23 04:37:46 +00001487 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001488 // A debug intrinsic shouldn't force another iteration if we weren't
1489 // going to do one without it.
1490 if (!isa<DbgInfoIntrinsic>(I)) {
1491 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001492 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001493 }
Devang Patel228ebd02009-10-13 22:56:32 +00001494
Devang Patel228ebd02009-10-13 22:56:32 +00001495 // If I is not void type then replaceAllUsesWith undef.
1496 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001497 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001498 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001499 I->eraseFromParent();
1500 }
1501 }
1502 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001503
Chris Lattner873ff012009-08-30 05:55:36 +00001504 while (!Worklist.isEmpty()) {
1505 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001506 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001507
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001508 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001509 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001510 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001511 EraseInstFromFunction(*I);
1512 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001513 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001514 continue;
1515 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001516
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001517 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001518 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001519 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001520 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001521
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001522 // Add operands to the worklist.
1523 ReplaceInstUsesWith(*I, C);
1524 ++NumConstProp;
1525 EraseInstFromFunction(*I);
1526 MadeIRChange = true;
1527 continue;
1528 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001529
Chris Lattnerea1c4542004-12-08 23:43:58 +00001530 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001531 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001532 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001533 Instruction *UserInst = cast<Instruction>(I->use_back());
1534 BasicBlock *UserParent;
1535
1536 // Get the block the use occurs in.
1537 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1538 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1539 else
1540 UserParent = UserInst->getParent();
1541
Chris Lattnerea1c4542004-12-08 23:43:58 +00001542 if (UserParent != BB) {
1543 bool UserIsSuccessor = false;
1544 // See if the user is one of our successors.
1545 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1546 if (*SI == UserParent) {
1547 UserIsSuccessor = true;
1548 break;
1549 }
1550
1551 // If the user is one of our immediate successors, and if that successor
1552 // only has us as a predecessors (we'd have to split the critical edge
1553 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001554 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001555 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001556 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001557 }
1558 }
1559
Chris Lattner74381062009-08-30 07:44:24 +00001560 // Now that we have an instruction, try combining it to simplify it.
1561 Builder->SetInsertPoint(I->getParent(), I);
1562
Reid Spencera9b81012007-03-26 17:44:01 +00001563#ifndef NDEBUG
1564 std::string OrigI;
1565#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001566 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001567 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1568
Chris Lattner90ac28c2002-08-02 19:29:35 +00001569 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001570 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001571 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001572 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001573 DEBUG(errs() << "IC: Old = " << *I << '\n'
1574 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001575
Chris Lattnerf523d062004-06-09 05:08:07 +00001576 // Everything uses the new instruction now.
1577 I->replaceAllUsesWith(Result);
1578
1579 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001580 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001581 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001582
Chris Lattner6934a042007-02-11 01:23:03 +00001583 // Move the name to the new instruction first.
1584 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001585
1586 // Insert the new instruction into the basic block...
1587 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001588 BasicBlock::iterator InsertPos = I;
1589
1590 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1591 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1592 ++InsertPos;
1593
1594 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001595
Chris Lattner7a1e9242009-08-30 06:13:40 +00001596 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001597 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001598#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001599 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1600 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001601#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001602
Chris Lattner90ac28c2002-08-02 19:29:35 +00001603 // If the instruction was modified, it's possible that it is now dead.
1604 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001605 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001606 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001607 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001608 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001609 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001610 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001611 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001612 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001613 }
1614 }
1615
Chris Lattner873ff012009-08-30 05:55:36 +00001616 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001617 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001618}
1619
Chris Lattnerec9c3582007-03-03 02:04:50 +00001620
1621bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00001622 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001623 TD = getAnalysisIfAvailable<TargetData>();
1624
Chris Lattner74381062009-08-30 07:44:24 +00001625
1626 /// Builder - This is an IRBuilder that automatically inserts new
1627 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001628 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001629 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001630 InstCombineIRInserter(Worklist));
1631 Builder = &TheBuilder;
1632
Chris Lattnerec9c3582007-03-03 02:04:50 +00001633 bool EverMadeChange = false;
1634
1635 // Iterate while there is work to do.
1636 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001637 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001638 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001639
1640 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001641 return EverMadeChange;
1642}
1643
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001644FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001645 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001646}