blob: 9a203f8512e4f51d82337cf8ae5edeffa8197b87 [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");
Chris Lattnera92f6962002-10-01 22:38:41 +000061
Owen Anderson74cfb0c2010-10-07 20:04:55 +000062// Initialization Routines
63void llvm::initializeInstCombine(PassRegistry &Registry) {
64 initializeInstCombinerPass(Registry);
65}
66
67void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
68 initializeInstCombine(*unwrap(R));
69}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Dan Gohman844731a2008-05-13 00:00:25 +000071char InstCombiner::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000072INITIALIZE_PASS(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000073 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000074
Chris Lattnere0b4b722010-01-04 07:17:19 +000075void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addPreservedID(LCSSAID);
77 AU.setPreservesCFG();
78}
79
80
Chris Lattnerc22d4d12009-11-10 07:23:37 +000081/// ShouldChangeType - Return true if it is desirable to convert a computation
82/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
83/// type for example, or from a smaller to a larger illegal type.
Chris Lattner80f43d32010-01-04 07:53:58 +000084bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000085 assert(From->isIntegerTy() && To->isIntegerTy());
Chris Lattnerc22d4d12009-11-10 07:23:37 +000086
87 // If we don't have TD, we don't know if the source/dest are legal.
88 if (!TD) return false;
89
90 unsigned FromWidth = From->getPrimitiveSizeInBits();
91 unsigned ToWidth = To->getPrimitiveSizeInBits();
92 bool FromLegal = TD->isLegalInteger(FromWidth);
93 bool ToLegal = TD->isLegalInteger(ToWidth);
94
95 // If this is a legal integer from type, and the result would be an illegal
96 // type, don't do the transformation.
97 if (FromLegal && !ToLegal)
98 return false;
99
100 // Otherwise, if both are illegal, do not increase the size of the result. We
101 // do allow things like i160 -> i64, but not i64 -> i160.
102 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
103 return false;
104
105 return true;
106}
107
Chris Lattner33a61132006-05-06 09:00:16 +0000108
Duncan Sands096aa792010-11-13 15:10:37 +0000109/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
110/// operators which are associative or commutative:
111//
112// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113//
Chris Lattner4f98c562003-03-10 21:43:22 +0000114// 1. Order operands such that they are listed from right (least complex) to
115// left (most complex). This puts constants before unary operators before
116// binary operators.
117//
Duncan Sands096aa792010-11-13 15:10:37 +0000118// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000119//
Duncan Sands096aa792010-11-13 15:10:37 +0000120// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
121// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
122//
123// Associative and commutative operators:
124//
125// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
126// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
127// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
128// if C1 and C2 are constants.
129//
130bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000131 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000132 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000133
Duncan Sands096aa792010-11-13 15:10:37 +0000134 do {
135 // Order operands such that they are listed from right (least complex) to
136 // left (most complex). This puts constants before unary operators before
137 // binary operators.
138 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
139 getComplexity(I.getOperand(1)))
140 Changed = !I.swapOperands();
141
142 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
143 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
144
145 if (I.isAssociative()) {
146 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
147 if (Op0 && Op0->getOpcode() == Opcode) {
148 Value *A = Op0->getOperand(0);
149 Value *B = Op0->getOperand(1);
150 Value *C = I.getOperand(1);
151
152 // Does "B op C" simplify?
153 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
154 // It simplifies to V. Form "A op V".
155 I.setOperand(0, A);
156 I.setOperand(1, V);
157 Changed = true;
158 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000159 }
Duncan Sands096aa792010-11-13 15:10:37 +0000160 }
161
162 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
163 if (Op1 && Op1->getOpcode() == Opcode) {
164 Value *A = I.getOperand(0);
165 Value *B = Op1->getOperand(0);
166 Value *C = Op1->getOperand(1);
167
168 // Does "A op B" simplify?
169 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
170 // It simplifies to V. Form "V op C".
171 I.setOperand(0, V);
172 I.setOperand(1, C);
173 Changed = true;
174 continue;
175 }
176 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000177 }
Duncan Sands096aa792010-11-13 15:10:37 +0000178
179 if (I.isAssociative() && I.isCommutative()) {
180 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
181 if (Op0 && Op0->getOpcode() == Opcode) {
182 Value *A = Op0->getOperand(0);
183 Value *B = Op0->getOperand(1);
184 Value *C = I.getOperand(1);
185
186 // Does "C op A" simplify?
187 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
188 // It simplifies to V. Form "V op B".
189 I.setOperand(0, V);
190 I.setOperand(1, B);
191 Changed = true;
192 continue;
193 }
194 }
195
196 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
197 if (Op1 && Op1->getOpcode() == Opcode) {
198 Value *A = I.getOperand(0);
199 Value *B = Op1->getOperand(0);
200 Value *C = Op1->getOperand(1);
201
202 // Does "C op A" simplify?
203 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
204 // It simplifies to V. Form "B op V".
205 I.setOperand(0, B);
206 I.setOperand(1, V);
207 Changed = true;
208 continue;
209 }
210 }
211
212 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
213 // if C1 and C2 are constants.
214 if (Op0 && Op1 &&
215 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
216 isa<Constant>(Op0->getOperand(1)) &&
217 isa<Constant>(Op1->getOperand(1)) &&
218 Op0->hasOneUse() && Op1->hasOneUse()) {
219 Value *A = Op0->getOperand(0);
220 Constant *C1 = cast<Constant>(Op0->getOperand(1));
221 Value *B = Op1->getOperand(0);
222 Constant *C2 = cast<Constant>(Op1->getOperand(1));
223
224 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
225 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
226 &I);
227 Worklist.Add(New);
228 I.setOperand(0, New);
229 I.setOperand(1, Folded);
230 Changed = true;
231 continue;
232 }
233 }
234
235 // No further simplifications.
236 return Changed;
237 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000238}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000239
Duncan Sands5057f382010-11-23 14:23:47 +0000240/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000241/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000242static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
243 Instruction::BinaryOps ROp) {
244 switch (LOp) {
245 default:
246 return false;
247
248 case Instruction::And:
249 // And distributes over Or and Xor.
250 switch (ROp) {
251 default:
252 return false;
253 case Instruction::Or:
254 case Instruction::Xor:
255 return true;
256 }
257
258 case Instruction::Mul:
259 // Multiplication distributes over addition and subtraction.
260 switch (ROp) {
261 default:
262 return false;
263 case Instruction::Add:
264 case Instruction::Sub:
265 return true;
266 }
267
268 case Instruction::Or:
269 // Or distributes over And.
270 switch (ROp) {
271 default:
272 return false;
273 case Instruction::And:
274 return true;
275 }
276 }
277}
278
279/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
280/// "(X ROp Z) LOp (Y ROp Z)".
281static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
282 Instruction::BinaryOps ROp) {
283 if (Instruction::isCommutative(ROp))
284 return LeftDistributesOverRight(ROp, LOp);
285 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
286 // but this requires knowing that the addition does not overflow and other
287 // such subtleties.
288 return false;
289}
290
291/// SimplifyDistributed - This tries to simplify binary operations which some
292/// other binary operation distributes over (eg "A*B+A*C" -> "A*(B+C)" since
293/// addition is distributed over by multiplication). Returns the result of
294/// the simplification, or null if no simplification was performed.
295Instruction *InstCombiner::SimplifyDistributed(BinaryOperator &I) {
296 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
297 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
298 if (!Op0 || !Op1 || Op0->getOpcode() != Op1->getOpcode())
299 return 0;
300
301 // The instruction has the form "(A op' B) op (C op' D)".
302 Value *A = Op0->getOperand(0); Value *B = Op0->getOperand(1);
303 Value *C = Op1->getOperand(0); Value *D = Op1->getOperand(1);
304 Instruction::BinaryOps OuterOpcode = I.getOpcode(); // op
305 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
306
307 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
308 bool LeftDistributes = LeftDistributesOverRight(InnerOpcode, OuterOpcode);
309 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
310 bool RightDistributes = RightDistributesOverLeft(OuterOpcode, InnerOpcode);
311 // Does "X op' Y" always equal "Y op' X"?
312 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
313
314 if (LeftDistributes)
315 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
316 // commutative case, "(A op' B) op (C op' A)"?
317 if (A == C || (InnerCommutative && A == D)) {
318 if (A != C)
319 std::swap(C, D);
320 // Consider forming "A op' (B op D)".
321 // If "B op D" simplifies then it can be formed with no cost.
322 Value *RHS = SimplifyBinOp(OuterOpcode, B, D, TD);
323 // If "B op D" doesn't simplify then only proceed if both of the existing
324 // operations "A op' B" and "C op' D" will be zapped since no longer used.
325 if (!RHS && Op0->hasOneUse() && Op1->hasOneUse())
326 RHS = Builder->CreateBinOp(OuterOpcode, B, D, Op1->getName());
327 if (RHS)
328 return BinaryOperator::Create(InnerOpcode, A, RHS);
329 }
330
331 if (RightDistributes)
332 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
333 // commutative case, "(A op' B) op (B op' D)"?
334 if (B == D || (InnerCommutative && B == C)) {
335 if (B != D)
336 std::swap(C, D);
337 // Consider forming "(A op C) op' B".
338 // If "A op C" simplifies then it can be formed with no cost.
339 Value *LHS = SimplifyBinOp(OuterOpcode, A, C, TD);
340 // If "A op C" doesn't simplify then only proceed if both of the existing
341 // operations "A op' B" and "C op' D" will be zapped since no longer used.
342 if (!LHS && Op0->hasOneUse() && Op1->hasOneUse())
343 LHS = Builder->CreateBinOp(OuterOpcode, A, C, Op0->getName());
344 if (LHS)
345 return BinaryOperator::Create(InnerOpcode, LHS, B);
346 }
347
348 return 0;
349}
350
Chris Lattner8d969642003-03-10 23:06:50 +0000351// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
352// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000353//
Chris Lattner02446fc2010-01-04 07:37:31 +0000354Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000355 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000356 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000357
Chris Lattner0ce85802004-12-14 20:08:06 +0000358 // Constants can be considered to be negated values if they can be folded.
359 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000360 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000361
362 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000363 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000364 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000365
Chris Lattner8d969642003-03-10 23:06:50 +0000366 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000367}
368
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000369// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
370// instruction if the LHS is a constant negative zero (which is the 'negate'
371// form).
372//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000373Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000374 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000375 return BinaryOperator::getFNegArgument(V);
376
377 // Constants can be considered to be negated values if they can be folded.
378 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000379 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000380
381 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000382 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000383 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000384
385 return 0;
386}
387
Chris Lattner6e7ba452005-01-01 16:22:27 +0000388static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000389 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +0000390 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +0000391 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +0000392
Chris Lattner2eefe512004-04-09 19:05:30 +0000393 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000394 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
395 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000396
Chris Lattner2eefe512004-04-09 19:05:30 +0000397 if (Constant *SOC = dyn_cast<Constant>(SO)) {
398 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000399 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
400 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000401 }
402
403 Value *Op0 = SO, *Op1 = ConstOperand;
404 if (!ConstIsRHS)
405 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +0000406
Chris Lattner6e7ba452005-01-01 16:22:27 +0000407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000408 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
409 SO->getName()+".op");
410 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
411 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
412 SO->getName()+".cmp");
413 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
414 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
415 SO->getName()+".cmp");
416 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000417}
418
419// FoldOpIntoSelect - Given an instruction with a select as one operand and a
420// constant as the other operand, try to fold the binary operator into the
421// select arguments. This also works for Cast instructions, which obviously do
422// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000423Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000424 // Don't modify shared select instructions
425 if (!SI->hasOneUse()) return 0;
426 Value *TV = SI->getOperand(1);
427 Value *FV = SI->getOperand(2);
428
429 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000430 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000431 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000432
Chris Lattner80f43d32010-01-04 07:53:58 +0000433 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
434 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000435
Gabor Greif051a9502008-04-06 20:25:17 +0000436 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
437 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000438 }
439 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000440}
441
Chris Lattner4e998b22004-09-29 05:07:12 +0000442
Chris Lattner5d1704d2009-09-27 19:57:57 +0000443/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
444/// has a PHI node as operand #0, see if we can fold the instruction into the
445/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000446///
447/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
448/// that would normally be unprofitable because they strongly encourage jump
449/// threading.
450Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
451 bool AllowAggressive) {
452 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +0000453 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000454 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +0000455 if (NumPHIValues == 0 ||
456 // We normally only transform phis with a single use, unless we're trying
457 // hard to make jump threading happen.
458 (!PN->hasOneUse() && !AllowAggressive))
459 return 0;
460
461
Chris Lattner5d1704d2009-09-27 19:57:57 +0000462 // Check to see if all of the operands of the PHI are simple constants
463 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000464 // remember the BB it is in. If there is more than one or if *it* is a PHI,
465 // bail out. We don't do arbitrary constant expressions here because moving
466 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000467 BasicBlock *NonConstBB = 0;
468 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +0000469 if (!isa<Constant>(PN->getIncomingValue(i)) ||
470 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000471 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +0000472 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000473 NonConstBB = PN->getIncomingBlock(i);
474
475 // If the incoming non-constant value is in I's block, we have an infinite
476 // loop.
477 if (NonConstBB == I.getParent())
478 return 0;
479 }
480
481 // If there is exactly one non-constant value, we can insert a copy of the
482 // operation in that block. However, if this is a critical edge, we would be
483 // inserting the computation one some other paths (e.g. inside a loop). Only
484 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +0000485 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000486 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
487 if (!BI || !BI->isUnconditional()) return 0;
488 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000489
490 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +0000491 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +0000492 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +0000493 InsertNewInstBefore(NewPN, *PN);
494 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +0000495
496 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000497 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
498 // We only currently try to fold the condition of a select when it is a phi,
499 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000500 Value *TrueV = SI->getTrueValue();
501 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000502 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000503 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000504 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000505 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
506 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000507 Value *InV = 0;
508 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000509 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +0000510 } else {
511 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000512 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
513 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +0000514 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000515 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +0000516 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000517 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000518 }
519 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000520 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000521 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000522 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000523 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000524 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000525 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000526 else
Owen Andersonbaf3c402009-07-29 18:55:55 +0000527 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000528 } else {
529 assert(PN->getIncomingBlock(i) == NonConstBB);
530 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000531 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000532 PN->getIncomingValue(i), C, "phitmp",
533 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +0000534 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000535 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +0000536 CI->getPredicate(),
537 PN->getIncomingValue(i), C, "phitmp",
538 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000539 else
Torok Edwinc23197a2009-07-14 16:55:14 +0000540 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +0000541
542 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000543 }
544 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000545 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000546 } else {
547 CastInst *CI = cast<CastInst>(&I);
548 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000549 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000550 Value *InV;
551 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000552 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000553 } else {
554 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000555 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +0000556 I.getType(), "phitmp",
557 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +0000558 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000559 }
560 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000561 }
562 }
563 return ReplaceInstUsesWith(I, NewPN);
564}
565
Chris Lattner46cd5a12009-01-09 05:44:56 +0000566/// FindElementAtOffset - Given a type and a constant offset, determine whether
567/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000568/// the specified offset. If so, fill them into NewIndices and return the
569/// resultant element type, otherwise return null.
Chris Lattner80f43d32010-01-04 07:53:58 +0000570const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
571 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000572 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000573 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000574
575 // Start with the index over the outer type. Note that the type size
576 // might be zero (even if the offset isn't zero) if the indexed type
577 // is something like [0 x {int, int}]
Chris Lattner4de84762010-01-04 07:02:48 +0000578 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000579 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000580 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000581 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000582 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000583
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000584 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000585 if (Offset < 0) {
586 --FirstIdx;
587 Offset += TySize;
588 assert(Offset >= 0);
589 }
590 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
591 }
592
Owen Andersoneed707b2009-07-24 23:12:02 +0000593 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000594
595 // Index into the types. If we fail, set OrigBase to null.
596 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000597 // Indexing into tail padding between struct/array elements.
598 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000599 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000600
Chris Lattner46cd5a12009-01-09 05:44:56 +0000601 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
602 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000603 assert(Offset < (int64_t)SL->getSizeInBytes() &&
604 "Offset must stay within the indexed type");
605
Chris Lattner46cd5a12009-01-09 05:44:56 +0000606 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000607 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
608 Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000609
610 Offset -= SL->getElementOffset(Elt);
611 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +0000612 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000613 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000614 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000615 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000616 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000617 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000618 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000619 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000620 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000621 }
622 }
623
Chris Lattner3914f722009-01-24 01:00:13 +0000624 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000625}
626
Chris Lattner8a2a3112001-12-14 16:52:21 +0000627
Chris Lattner473945d2002-05-06 18:06:38 +0000628
Chris Lattner7e708292002-06-25 16:13:24 +0000629Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000630 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
631
632 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
633 return ReplaceInstUsesWith(GEP, V);
634
Chris Lattner620ce142004-05-07 22:09:22 +0000635 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000636
Duncan Sandsa63395a2010-11-22 16:32:50 +0000637 // Eliminate unneeded casts for indices, and replace indices which displace
638 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000639 if (TD) {
640 bool MadeChange = false;
Duncan Sandsa63395a2010-11-22 16:32:50 +0000641 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
642
Chris Lattnerccf4b342009-08-30 04:49:01 +0000643 gep_type_iterator GTI = gep_type_begin(GEP);
644 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
645 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000646 // Skip indices into struct types.
647 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
648 if (!SeqTy) continue;
649
650 // If the element type has zero size then any index over it is equivalent
651 // to an index of zero, so replace it with zero if it is not zero already.
652 if (SeqTy->getElementType()->isSized() &&
653 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
654 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
655 *I = Constant::getNullValue(IntPtrTy);
656 MadeChange = true;
657 }
658
659 if ((*I)->getType() != IntPtrTy) {
660 // If we are using a wider index than needed for this platform, shrink
661 // it to what we need. If narrower, sign-extend it to what we need.
662 // This explicit cast can make subsequent optimizations more obvious.
663 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
664 MadeChange = true;
665 }
Chris Lattner28977af2004-04-05 01:30:19 +0000666 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000667 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000668 }
Chris Lattner28977af2004-04-05 01:30:19 +0000669
Chris Lattner90ac28c2002-08-02 19:29:35 +0000670 // Combine Indices - If the source pointer to this getelementptr instruction
671 // is a getelementptr instruction, combine the indices of the two
672 // getelementptr instructions into a single instruction.
673 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000674 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +0000675 // Note that if our source is a gep chain itself that we wait for that
676 // chain to be resolved before we perform this transformation. This
677 // avoids us creating a TON of code in some cases.
678 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000679 if (GetElementPtrInst *SrcGEP =
680 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
681 if (SrcGEP->getNumOperands() == 2)
682 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000683
Chris Lattner72588fc2007-02-15 22:48:32 +0000684 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000685
686 // Find out whether the last index in the source GEP is a sequential idx.
687 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000688 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
689 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000690 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000691
Chris Lattner90ac28c2002-08-02 19:29:35 +0000692 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000693 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000694 // Replace: gep (gep %P, long B), long A, ...
695 // With: T = long A+B; gep %P, T, ...
696 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000697 Value *Sum;
698 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
699 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000700 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000701 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000702 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000703 Sum = SO1;
704 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000705 // If they aren't the same type, then the input hasn't been processed
706 // by the loop above yet (which canonicalizes sequential index types to
707 // intptr_t). Just avoid transforming this until the input has been
708 // normalized.
709 if (SO1->getType() != GO1->getType())
710 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000711 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000712 }
Chris Lattner620ce142004-05-07 22:09:22 +0000713
Chris Lattnerab984842009-08-30 05:30:55 +0000714 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000715 if (Src->getNumOperands() == 2) {
716 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000717 GEP.setOperand(1, Sum);
718 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000719 }
Chris Lattnerab984842009-08-30 05:30:55 +0000720 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000721 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000722 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000723 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000724 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000725 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000726 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000727 Indices.append(Src->op_begin()+1, Src->op_end());
728 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000729 }
730
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000731 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000732 return (GEP.isInBounds() && Src->isInBounds()) ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000733 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
734 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000735 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +0000736 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000737 }
738
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000739 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000740 Value *StrippedPtr = PtrOp->stripPointerCasts();
741 if (StrippedPtr != PtrOp) {
742 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
Chris Lattner963f4ba2009-08-30 20:36:46 +0000743
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000744 bool HasZeroPointerIndex = false;
745 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
746 HasZeroPointerIndex = C->isZero();
747
Chris Lattner963f4ba2009-08-30 20:36:46 +0000748 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
749 // into : GEP [10 x i8]* X, i32 0, ...
750 //
751 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
752 // into : GEP i8* X, ...
753 //
754 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000755 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +0000756 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000757 if (const ArrayType *CATy =
758 dyn_cast<ArrayType>(CPTy->getElementType())) {
759 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000760 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000761 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000762 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
763 GetElementPtrInst *Res =
764 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
765 Idx.end(), GEP.getName());
766 Res->setIsInBounds(GEP.isInBounds());
767 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000768 }
769
Chris Lattner948cdeb2010-01-05 07:42:10 +0000770 if (const ArrayType *XATy =
771 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000772 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000773 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000774 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000775 // At this point, we know that the cast source type is a pointer
776 // to an array of the same type as the destination pointer
777 // array. Because the array type is never stepped over (there
778 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000779 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000780 return &GEP;
781 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000782 }
783 }
Chris Lattnereed48272005-09-13 00:40:14 +0000784 } else if (GEP.getNumOperands() == 2) {
785 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000786 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
787 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner948cdeb2010-01-05 07:42:10 +0000788 const Type *SrcElTy = StrippedPtrTy->getElementType();
Chris Lattnereed48272005-09-13 00:40:14 +0000789 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000790 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000791 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
792 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000793 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000794 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000795 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000796 Value *NewGEP = GEP.isInBounds() ?
797 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
798 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000799 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000800 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000801 }
Chris Lattner7835cdd2005-09-13 18:36:04 +0000802
803 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000804 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000805 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000806 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +0000807
Duncan Sands1df98592010-02-16 11:11:14 +0000808 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000809 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000810 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000811
812 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
813 // allow either a mul, shift, or constant here.
814 Value *NewIdx = 0;
815 ConstantInt *Scale = 0;
816 if (ArrayEltSize == 1) {
817 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +0000818 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000819 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000820 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000821 Scale = CI;
822 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
823 if (Inst->getOpcode() == Instruction::Shl &&
824 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000825 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
826 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +0000827 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +0000828 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +0000829 NewIdx = Inst->getOperand(0);
830 } else if (Inst->getOpcode() == Instruction::Mul &&
831 isa<ConstantInt>(Inst->getOperand(1))) {
832 Scale = cast<ConstantInt>(Inst->getOperand(1));
833 NewIdx = Inst->getOperand(0);
834 }
835 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000836
Chris Lattner7835cdd2005-09-13 18:36:04 +0000837 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000838 // out, perform the transformation. Note, we don't know whether Scale is
839 // signed or not. We'll use unsigned version of division/modulo
840 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +0000841 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000842 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000843 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000844 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +0000845 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +0000846 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
847 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000848 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +0000849 }
850
851 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +0000852 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000853 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000854 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +0000855 Value *NewGEP = GEP.isInBounds() ?
856 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
857 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000858 // The NewGEP must be pointer typed, so must the old one -> BitCast
859 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +0000860 }
861 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000862 }
Chris Lattner8a2a3112001-12-14 16:52:21 +0000863 }
Chris Lattner58407792009-01-09 04:53:57 +0000864
Chris Lattner46cd5a12009-01-09 05:44:56 +0000865 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +0000866 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +0000867 /// Y = gep X, <...constant indices...>
868 /// into a gep of the original struct. This is important for SROA and alias
869 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +0000870 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000871 if (TD &&
872 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000873 // Determine how much the GEP moves the pointer. We are guaranteed to get
874 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +0000875 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +0000876 int64_t Offset = OffsetV->getSExtValue();
877
878 // If this GEP instruction doesn't move the pointer, just replace the GEP
879 // with a bitcast of the real input to the dest type.
880 if (Offset == 0) {
881 // If the bitcast is of an allocation, and the allocation will be
882 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000883 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +0000884 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000885 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
886 if (Instruction *I = visitBitCast(*BCI)) {
887 if (I != BCI) {
888 I->takeName(BCI);
889 BCI->getParent()->getInstList().insert(BCI, I);
890 ReplaceInstUsesWith(*BCI, I);
891 }
892 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +0000893 }
Chris Lattner58407792009-01-09 04:53:57 +0000894 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000895 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +0000896 }
Chris Lattner46cd5a12009-01-09 05:44:56 +0000897
898 // Otherwise, if the offset is non-zero, we need to find out if there is a
899 // field at Offset in 'A's type. If so, we can pull the cast through the
900 // GEP.
901 SmallVector<Value*, 8> NewIndices;
902 const Type *InTy =
903 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +0000904 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +0000905 Value *NGEP = GEP.isInBounds() ?
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000906 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
907 NewIndices.end()) :
908 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
909 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000910
911 if (NGEP->getType() == GEP.getType())
912 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +0000913 NGEP->takeName(&GEP);
914 return new BitCastInst(NGEP, GEP.getType());
915 }
Chris Lattner58407792009-01-09 04:53:57 +0000916 }
917 }
918
Chris Lattner8a2a3112001-12-14 16:52:21 +0000919 return 0;
920}
921
Duncan Sands1d9b9732010-05-27 19:09:06 +0000922
923
924static bool IsOnlyNullComparedAndFreed(const Value &V) {
925 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
926 UI != UE; ++UI) {
Gabor Greiffc36c0f2010-07-09 15:01:36 +0000927 const User *U = *UI;
928 if (isFreeCall(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +0000929 continue;
Gabor Greiffc36c0f2010-07-09 15:01:36 +0000930 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
Duncan Sands1d9b9732010-05-27 19:09:06 +0000931 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
932 continue;
933 return false;
934 }
935 return true;
936}
937
938Instruction *InstCombiner::visitMalloc(Instruction &MI) {
939 // If we have a malloc call which is only used in any amount of comparisons
940 // to null and free calls, delete the calls and replace the comparisons with
941 // true or false as appropriate.
942 if (IsOnlyNullComparedAndFreed(MI)) {
943 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
944 UI != UE;) {
945 // We can assume that every remaining use is a free call or an icmp eq/ne
946 // to null, so the cast is safe.
947 Instruction *I = cast<Instruction>(*UI);
948
949 // Early increment here, as we're about to get rid of the user.
950 ++UI;
951
952 if (isFreeCall(I)) {
953 EraseInstFromFunction(*cast<CallInst>(I));
954 continue;
955 }
956 // Again, the cast is safe.
957 ICmpInst *C = cast<ICmpInst>(I);
958 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
959 C->isFalseWhenEqual()));
960 EraseInstFromFunction(*C);
961 }
962 return EraseInstFromFunction(MI);
963 }
964 return 0;
965}
966
967
968
Gabor Greif91697372010-06-24 12:21:15 +0000969Instruction *InstCombiner::visitFree(CallInst &FI) {
970 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +0000971
972 // free undef -> unreachable.
973 if (isa<UndefValue>(Op)) {
974 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner4de84762010-01-04 07:02:48 +0000975 new StoreInst(ConstantInt::getTrue(FI.getContext()),
976 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000977 return EraseInstFromFunction(FI);
978 }
979
980 // If we have 'free null' delete the instruction. This can happen in stl code
981 // when lots of inlining happens.
982 if (isa<ConstantPointerNull>(Op))
983 return EraseInstFromFunction(FI);
984
Victor Hernandez66284e02009-10-24 04:23:03 +0000985 return 0;
986}
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000987
Chris Lattner3284d1f2007-04-15 00:07:55 +0000988
Chris Lattner2f503e62005-01-31 05:36:43 +0000989
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000990Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
991 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +0000992 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000993 BasicBlock *TrueDest;
994 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +0000995 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000996 !isa<Constant>(X)) {
997 // Swap Destinations and condition...
998 BI.setCondition(X);
999 BI.setSuccessor(0, FalseDest);
1000 BI.setSuccessor(1, TrueDest);
1001 return &BI;
1002 }
1003
Reid Spencere4d87aa2006-12-23 06:05:41 +00001004 // Cannonicalize fcmp_one -> fcmp_oeq
1005 FCmpInst::Predicate FPred; Value *Y;
1006 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001007 TrueDest, FalseDest)) &&
1008 BI.getCondition()->hasOneUse())
1009 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1010 FPred == FCmpInst::FCMP_OGE) {
1011 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1012 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1013
1014 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001015 BI.setSuccessor(0, FalseDest);
1016 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001017 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001018 return &BI;
1019 }
1020
1021 // Cannonicalize icmp_ne -> icmp_eq
1022 ICmpInst::Predicate IPred;
1023 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001024 TrueDest, FalseDest)) &&
1025 BI.getCondition()->hasOneUse())
1026 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1027 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1028 IPred == ICmpInst::ICMP_SGE) {
1029 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1030 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1031 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +00001032 BI.setSuccessor(0, FalseDest);
1033 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +00001034 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001035 return &BI;
1036 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001037
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001038 return 0;
1039}
Chris Lattner0864acf2002-11-04 16:18:53 +00001040
Chris Lattner46238a62004-07-03 00:26:11 +00001041Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1042 Value *Cond = SI.getCondition();
1043 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1044 if (I->getOpcode() == Instruction::Add)
1045 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1046 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1047 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +00001048 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +00001049 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00001050 AddRHS));
1051 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001052 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001053 return &SI;
1054 }
1055 }
1056 return 0;
1057}
1058
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001059Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001060 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001061
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001062 if (!EV.hasIndices())
1063 return ReplaceInstUsesWith(EV, Agg);
1064
1065 if (Constant *C = dyn_cast<Constant>(Agg)) {
1066 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001067 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001068
1069 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +00001070 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001071
1072 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1073 // Extract the element indexed by the first index out of the constant
1074 Value *V = C->getOperand(*EV.idx_begin());
1075 if (EV.getNumIndices() > 1)
1076 // Extract the remaining indices out of the constant indexed by the
1077 // first index
1078 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1079 else
1080 return ReplaceInstUsesWith(EV, V);
1081 }
1082 return 0; // Can't handle other constants
1083 }
1084 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1085 // We're extracting from an insertvalue instruction, compare the indices
1086 const unsigned *exti, *exte, *insi, *inse;
1087 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1088 exte = EV.idx_end(), inse = IV->idx_end();
1089 exti != exte && insi != inse;
1090 ++exti, ++insi) {
1091 if (*insi != *exti)
1092 // The insert and extract both reference distinctly different elements.
1093 // This means the extract is not influenced by the insert, and we can
1094 // replace the aggregate operand of the extract with the aggregate
1095 // operand of the insert. i.e., replace
1096 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1097 // %E = extractvalue { i32, { i32 } } %I, 0
1098 // with
1099 // %E = extractvalue { i32, { i32 } } %A, 0
1100 return ExtractValueInst::Create(IV->getAggregateOperand(),
1101 EV.idx_begin(), EV.idx_end());
1102 }
1103 if (exti == exte && insi == inse)
1104 // Both iterators are at the end: Index lists are identical. Replace
1105 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1106 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1107 // with "i32 42"
1108 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1109 if (exti == exte) {
1110 // The extract list is a prefix of the insert list. i.e. replace
1111 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1112 // %E = extractvalue { i32, { i32 } } %I, 1
1113 // with
1114 // %X = extractvalue { i32, { i32 } } %A, 1
1115 // %E = insertvalue { i32 } %X, i32 42, 0
1116 // by switching the order of the insert and extract (though the
1117 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001118 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1119 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001120 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1121 insi, inse);
1122 }
1123 if (insi == inse)
1124 // The insert list is a prefix of the extract list
1125 // We can simply remove the common indices from the extract and make it
1126 // operate on the inserted value instead of the insertvalue result.
1127 // i.e., replace
1128 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1129 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1130 // with
1131 // %E extractvalue { i32 } { i32 42 }, 0
1132 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1133 exti, exte);
1134 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001135 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1136 // We're extracting from an intrinsic, see if we're the only user, which
1137 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001138 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001139 if (II->hasOneUse()) {
1140 // Check if we're grabbing the overflow bit or the result of a 'with
1141 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1142 // and replace it with a traditional binary instruction.
1143 switch (II->getIntrinsicID()) {
1144 case Intrinsic::uadd_with_overflow:
1145 case Intrinsic::sadd_with_overflow:
1146 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001147 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001148 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1149 EraseInstFromFunction(*II);
1150 return BinaryOperator::CreateAdd(LHS, RHS);
1151 }
1152 break;
1153 case Intrinsic::usub_with_overflow:
1154 case Intrinsic::ssub_with_overflow:
1155 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001156 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001157 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1158 EraseInstFromFunction(*II);
1159 return BinaryOperator::CreateSub(LHS, RHS);
1160 }
1161 break;
1162 case Intrinsic::umul_with_overflow:
1163 case Intrinsic::smul_with_overflow:
1164 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001165 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner7e606e22009-11-09 07:07:56 +00001166 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1167 EraseInstFromFunction(*II);
1168 return BinaryOperator::CreateMul(LHS, RHS);
1169 }
1170 break;
1171 default:
1172 break;
1173 }
1174 }
1175 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001176 // Can't simplify extracts from other values. Note that nested extracts are
1177 // already simplified implicitely by the above (extract ( extract (insert) )
1178 // will be translated into extract ( insert ( extract ) ) first and then just
1179 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001180 return 0;
1181}
1182
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001183
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001184
Chris Lattnerea1c4542004-12-08 23:43:58 +00001185
1186/// TryToSinkInstruction - Try to move the specified instruction from its
1187/// current block into the beginning of DestBlock, which can only happen if it's
1188/// safe to move the instruction past all of the instructions between it and the
1189/// end of its block.
1190static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1191 assert(I->hasOneUse() && "Invariants didn't hold!");
1192
Chris Lattner108e9022005-10-27 17:13:11 +00001193 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +00001194 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001195 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001196
Chris Lattnerea1c4542004-12-08 23:43:58 +00001197 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001198 if (isa<AllocaInst>(I) && I->getParent() ==
1199 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001200 return false;
1201
Chris Lattner96a52a62004-12-09 07:14:34 +00001202 // We can only sink load instructions if there is nothing between the load and
1203 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001204 if (I->mayReadFromMemory()) {
1205 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001206 Scan != E; ++Scan)
1207 if (Scan->mayWriteToMemory())
1208 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001209 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001210
Dan Gohman02dea8b2008-05-23 21:05:58 +00001211 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +00001212
Chris Lattner4bc5f802005-08-08 19:11:57 +00001213 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001214 ++NumSunkInst;
1215 return true;
1216}
1217
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001218
1219/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1220/// all reachable code to the worklist.
1221///
1222/// This has a couple of tricks to make the code faster and more powerful. In
1223/// particular, we constant fold and DCE instructions as we go, to avoid adding
1224/// them to the worklist (this significantly speeds up instcombine on code where
1225/// many instructions are dead or constant). Additionally, if we find a branch
1226/// whose condition is a known constant, we only visit the reachable successors.
1227///
Chris Lattner2ee743b2009-10-15 04:59:28 +00001228static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001229 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001230 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001231 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001232 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001233 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001234 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001235
Benjamin Kramera53fe602010-10-23 17:10:24 +00001236 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001237 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1238
Dan Gohman321a8132010-01-05 16:27:25 +00001239 do {
1240 BB = Worklist.pop_back_val();
Chris Lattner2c7718a2007-03-23 19:17:18 +00001241
1242 // We have now visited this block! If we've already been here, ignore it.
1243 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001244
Chris Lattner2c7718a2007-03-23 19:17:18 +00001245 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1246 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001247
Chris Lattner2c7718a2007-03-23 19:17:18 +00001248 // DCE instruction if trivially dead.
1249 if (isInstructionTriviallyDead(Inst)) {
1250 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001251 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001252 Inst->eraseFromParent();
1253 continue;
1254 }
1255
1256 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001257 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001258 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001259 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1260 << *Inst << '\n');
1261 Inst->replaceAllUsesWith(C);
1262 ++NumConstProp;
1263 Inst->eraseFromParent();
1264 continue;
1265 }
Chris Lattner2ee743b2009-10-15 04:59:28 +00001266
Chris Lattner2ee743b2009-10-15 04:59:28 +00001267 if (TD) {
1268 // See if we can constant fold its operands.
1269 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1270 i != e; ++i) {
1271 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1272 if (CE == 0) continue;
1273
1274 // If we already folded this constant, don't try again.
1275 if (!FoldedConstants.insert(CE))
1276 continue;
1277
Chris Lattner7b550cc2009-11-06 04:27:31 +00001278 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +00001279 if (NewC && NewC != CE) {
1280 *i = NewC;
1281 MadeIRChange = true;
1282 }
1283 }
1284 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001285
Chris Lattner67f7d542009-10-12 03:58:40 +00001286 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001287 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001288
1289 // Recursively visit successors. If this is a branch or switch on a
1290 // constant, only visit the reachable successor.
1291 TerminatorInst *TI = BB->getTerminator();
1292 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1293 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1294 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001295 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001296 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001297 continue;
1298 }
1299 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1300 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1301 // See if this is an explicit destination.
1302 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1303 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +00001304 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001305 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001306 continue;
1307 }
1308
1309 // Otherwise it is the default destination.
1310 Worklist.push_back(SI->getSuccessor(0));
1311 continue;
1312 }
1313 }
1314
1315 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1316 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001317 } while (!Worklist.empty());
Chris Lattner67f7d542009-10-12 03:58:40 +00001318
1319 // Once we've found all of the instructions to add to instcombine's worklist,
1320 // add them in reverse order. This way instcombine will visit from the top
1321 // of the function down. This jives well with the way that it adds all uses
1322 // of instructions to the worklist after doing a transformation, thus avoiding
1323 // some N^2 behavior in pathological cases.
1324 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1325 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +00001326
1327 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001328}
1329
Chris Lattnerec9c3582007-03-03 02:04:50 +00001330bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001331 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001332
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001333 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1334 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001335
Chris Lattnerb3d59702005-07-07 20:40:38 +00001336 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001337 // Do a depth-first traversal of the function, populate the worklist with
1338 // the reachable instructions. Ignore blocks that are not reachable. Keep
1339 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001340 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001341 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00001342
Chris Lattnerb3d59702005-07-07 20:40:38 +00001343 // Do a quick scan over the function. If we find any blocks that are
1344 // unreachable, remove any instructions inside of them. This prevents
1345 // the instcombine code from having to deal with some bad special cases.
1346 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1347 if (!Visited.count(BB)) {
1348 Instruction *Term = BB->getTerminator();
1349 while (Term != BB->begin()) { // Remove instrs bottom-up
1350 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00001351
Chris Lattnerbdff5482009-08-23 04:37:46 +00001352 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +00001353 // A debug intrinsic shouldn't force another iteration if we weren't
1354 // going to do one without it.
1355 if (!isa<DbgInfoIntrinsic>(I)) {
1356 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001357 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +00001358 }
Devang Patel228ebd02009-10-13 22:56:32 +00001359
Devang Patel228ebd02009-10-13 22:56:32 +00001360 // If I is not void type then replaceAllUsesWith undef.
1361 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +00001362 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +00001363 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +00001364 I->eraseFromParent();
1365 }
1366 }
1367 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001368
Chris Lattner873ff012009-08-30 05:55:36 +00001369 while (!Worklist.isEmpty()) {
1370 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001371 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001372
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001373 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001374 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001375 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001376 EraseInstFromFunction(*I);
1377 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001378 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001379 continue;
1380 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001381
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001382 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001383 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +00001384 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001385 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001386
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001387 // Add operands to the worklist.
1388 ReplaceInstUsesWith(*I, C);
1389 ++NumConstProp;
1390 EraseInstFromFunction(*I);
1391 MadeIRChange = true;
1392 continue;
1393 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001394
Chris Lattnerea1c4542004-12-08 23:43:58 +00001395 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001396 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001397 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001398 Instruction *UserInst = cast<Instruction>(I->use_back());
1399 BasicBlock *UserParent;
1400
1401 // Get the block the use occurs in.
1402 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1403 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1404 else
1405 UserParent = UserInst->getParent();
1406
Chris Lattnerea1c4542004-12-08 23:43:58 +00001407 if (UserParent != BB) {
1408 bool UserIsSuccessor = false;
1409 // See if the user is one of our successors.
1410 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1411 if (*SI == UserParent) {
1412 UserIsSuccessor = true;
1413 break;
1414 }
1415
1416 // If the user is one of our immediate successors, and if that successor
1417 // only has us as a predecessors (we'd have to split the critical edge
1418 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001419 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001420 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001421 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001422 }
1423 }
1424
Chris Lattner74381062009-08-30 07:44:24 +00001425 // Now that we have an instruction, try combining it to simplify it.
1426 Builder->SetInsertPoint(I->getParent(), I);
1427
Reid Spencera9b81012007-03-26 17:44:01 +00001428#ifndef NDEBUG
1429 std::string OrigI;
1430#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00001431 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00001432 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1433
Chris Lattner90ac28c2002-08-02 19:29:35 +00001434 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00001435 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001436 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001437 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001438 DEBUG(errs() << "IC: Old = " << *I << '\n'
1439 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +00001440
Chris Lattnerf523d062004-06-09 05:08:07 +00001441 // Everything uses the new instruction now.
1442 I->replaceAllUsesWith(Result);
1443
1444 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +00001445 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001446 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001447
Chris Lattner6934a042007-02-11 01:23:03 +00001448 // Move the name to the new instruction first.
1449 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001450
1451 // Insert the new instruction into the basic block...
1452 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00001453 BasicBlock::iterator InsertPos = I;
1454
1455 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1456 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1457 ++InsertPos;
1458
1459 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00001460
Chris Lattner7a1e9242009-08-30 06:13:40 +00001461 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00001462 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00001463#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00001464 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1465 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00001466#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00001467
Chris Lattner90ac28c2002-08-02 19:29:35 +00001468 // If the instruction was modified, it's possible that it is now dead.
1469 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00001470 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001471 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00001472 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00001473 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00001474 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00001475 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00001476 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001477 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00001478 }
1479 }
1480
Chris Lattner873ff012009-08-30 05:55:36 +00001481 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001482 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001483}
1484
Chris Lattnerec9c3582007-03-03 02:04:50 +00001485
1486bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +00001487 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001488 TD = getAnalysisIfAvailable<TargetData>();
1489
Chris Lattner74381062009-08-30 07:44:24 +00001490
1491 /// Builder - This is an IRBuilder that automatically inserts new
1492 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001493 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00001494 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00001495 InstCombineIRInserter(Worklist));
1496 Builder = &TheBuilder;
1497
Chris Lattnerec9c3582007-03-03 02:04:50 +00001498 bool EverMadeChange = false;
1499
1500 // Iterate while there is work to do.
1501 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00001502 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00001503 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +00001504
1505 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00001506 return EverMadeChange;
1507}
1508
Brian Gaeke96d4bf72004-07-27 17:43:21 +00001509FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001510 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00001511}