blob: aa6e82fb40dc35d329a2f2c00594cd1bef137f50 [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"
Chad Rosier3d925d22011-11-29 23:57:10 +000044#include "llvm/Target/TargetLibraryInfo.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattner804272c2010-01-05 07:54:43 +000046#include "llvm/Support/CFG.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000047#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000048#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Nick Lewyckyd5061a92011-08-03 00:43:35 +000050#include "llvm/Support/ValueHandle.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000051#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Duncan Sands0ad7b6e2011-09-30 13:12:16 +000053#include "llvm/ADT/StringSwitch.h"
Owen Anderson74cfb0c2010-10-07 20:04:55 +000054#include "llvm-c/Initialization.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000055#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000056#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000057using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000059
Chris Lattner0e5f4992006-12-19 21:40:18 +000060STATISTIC(NumCombined , "Number of insts combined");
61STATISTIC(NumConstProp, "Number of constant folds");
62STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000063STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sands37bf92b2010-12-22 13:36:08 +000064STATISTIC(NumExpand, "Number of expansions");
Duncan Sandsa3c44a52010-12-22 09:40:51 +000065STATISTIC(NumFactor , "Number of factorizations");
66STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnera92f6962002-10-01 22:38:41 +000067
Owen Anderson74cfb0c2010-10-07 20:04:55 +000068// Initialization Routines
69void llvm::initializeInstCombine(PassRegistry &Registry) {
70 initializeInstCombinerPass(Registry);
71}
72
73void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
74 initializeInstCombine(*unwrap(R));
75}
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076
Dan Gohman844731a2008-05-13 00:00:25 +000077char InstCombiner::ID = 0;
Chad Rosier00737bd2011-12-01 21:29:16 +000078INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
79 "Combine redundant instructions", false, false)
80INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
81INITIALIZE_PASS_END(InstCombiner, "instcombine",
Owen Andersonce665bd2010-10-07 22:25:06 +000082 "Combine redundant instructions", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +000083
Chris Lattnere0b4b722010-01-04 07:17:19 +000084void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnere0b4b722010-01-04 07:17:19 +000085 AU.setPreservesCFG();
Chad Rosier3d925d22011-11-29 23:57:10 +000086 AU.addRequired<TargetLibraryInfo>();
Chris Lattnere0b4b722010-01-04 07:17:19 +000087}
88
89
Chris Lattnerc22d4d12009-11-10 07:23:37 +000090/// ShouldChangeType - Return true if it is desirable to convert a computation
91/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
92/// type for example, or from a smaller to a larger illegal type.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000093bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
Duncan Sands1df98592010-02-16 11:11:14 +000094 assert(From->isIntegerTy() && To->isIntegerTy());
Jakub Staszak58c1da82012-05-06 13:52:31 +000095
Chris Lattnerc22d4d12009-11-10 07:23:37 +000096 // If we don't have TD, we don't know if the source/dest are legal.
97 if (!TD) return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +000098
Chris Lattnerc22d4d12009-11-10 07:23:37 +000099 unsigned FromWidth = From->getPrimitiveSizeInBits();
100 unsigned ToWidth = To->getPrimitiveSizeInBits();
101 bool FromLegal = TD->isLegalInteger(FromWidth);
102 bool ToLegal = TD->isLegalInteger(ToWidth);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000103
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
107 return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000108
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
112 return false;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000113
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000114 return true;
115}
116
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000117// Return true, if No Signed Wrap should be maintained for I.
118// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
119// where both B and C should be ConstantInts, results in a constant that does
120// not overflow. This function only handles the Add and Sub opcodes. For
121// all other opcodes, the function conservatively returns false.
122static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
123 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
124 if (!OBO || !OBO->hasNoSignedWrap()) {
125 return false;
126 }
127
128 // We reason about Add and Sub Only.
129 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszak58c1da82012-05-06 13:52:31 +0000130 if (Opcode != Instruction::Add &&
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000131 Opcode != Instruction::Sub) {
132 return false;
133 }
134
135 ConstantInt *CB = dyn_cast<ConstantInt>(B);
136 ConstantInt *CC = dyn_cast<ConstantInt>(C);
137
138 if (!CB || !CC) {
139 return false;
140 }
141
142 const APInt &BVal = CB->getValue();
143 const APInt &CVal = CC->getValue();
144 bool Overflow = false;
145
146 if (Opcode == Instruction::Add) {
147 BVal.sadd_ov(CVal, Overflow);
148 } else {
149 BVal.ssub_ov(CVal, Overflow);
150 }
151
152 return !Overflow;
153}
154
Duncan Sands096aa792010-11-13 15:10:37 +0000155/// SimplifyAssociativeOrCommutative - This performs a few simplifications for
156/// operators which are associative or commutative:
157//
158// Commutative operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000159//
Chris Lattner4f98c562003-03-10 21:43:22 +0000160// 1. Order operands such that they are listed from right (least complex) to
161// left (most complex). This puts constants before unary operators before
162// binary operators.
163//
Duncan Sands096aa792010-11-13 15:10:37 +0000164// Associative operators:
Chris Lattner4f98c562003-03-10 21:43:22 +0000165//
Duncan Sands096aa792010-11-13 15:10:37 +0000166// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
167// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
168//
169// Associative and commutative operators:
170//
171// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
172// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
173// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
174// if C1 and C2 are constants.
175//
176bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000177 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands096aa792010-11-13 15:10:37 +0000178 bool Changed = false;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000179
Duncan Sands096aa792010-11-13 15:10:37 +0000180 do {
181 // Order operands such that they are listed from right (least complex) to
182 // left (most complex). This puts constants before unary operators before
183 // binary operators.
184 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
185 getComplexity(I.getOperand(1)))
186 Changed = !I.swapOperands();
187
188 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
189 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
190
191 if (I.isAssociative()) {
192 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
193 if (Op0 && Op0->getOpcode() == Opcode) {
194 Value *A = Op0->getOperand(0);
195 Value *B = Op0->getOperand(1);
196 Value *C = I.getOperand(1);
197
198 // Does "B op C" simplify?
199 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
200 // It simplifies to V. Form "A op V".
201 I.setOperand(0, A);
202 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000203 // Conservatively clear the optional flags, since they may not be
204 // preserved by the reassociation.
Nick Lewycky7f0170c2011-08-14 03:41:33 +0000205 if (MaintainNoSignedWrap(I, B, C) &&
206 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
207 // Note: this is only valid because SimplifyBinOp doesn't look at
208 // the operands to Op0.
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000209 I.clearSubclassOptionalData();
210 I.setHasNoSignedWrap(true);
211 } else {
212 I.clearSubclassOptionalData();
213 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000214
Duncan Sands096aa792010-11-13 15:10:37 +0000215 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000216 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000217 continue;
Misha Brukmanfd939082005-04-21 23:48:37 +0000218 }
Duncan Sands096aa792010-11-13 15:10:37 +0000219 }
220
221 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
222 if (Op1 && Op1->getOpcode() == Opcode) {
223 Value *A = I.getOperand(0);
224 Value *B = Op1->getOperand(0);
225 Value *C = Op1->getOperand(1);
226
227 // Does "A op B" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
229 // It simplifies to V. Form "V op C".
230 I.setOperand(0, V);
231 I.setOperand(1, C);
Dan Gohman5195b712011-02-02 02:05:46 +0000232 // Conservatively clear the optional flags, since they may not be
233 // preserved by the reassociation.
234 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000235 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000236 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000237 continue;
238 }
239 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000240 }
Duncan Sands096aa792010-11-13 15:10:37 +0000241
242 if (I.isAssociative() && I.isCommutative()) {
243 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
244 if (Op0 && Op0->getOpcode() == Opcode) {
245 Value *A = Op0->getOperand(0);
246 Value *B = Op0->getOperand(1);
247 Value *C = I.getOperand(1);
248
249 // Does "C op A" simplify?
250 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
251 // It simplifies to V. Form "V op B".
252 I.setOperand(0, V);
253 I.setOperand(1, B);
Dan Gohman5195b712011-02-02 02:05:46 +0000254 // Conservatively clear the optional flags, since they may not be
255 // preserved by the reassociation.
256 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000257 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000258 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000259 continue;
260 }
261 }
262
263 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
264 if (Op1 && Op1->getOpcode() == Opcode) {
265 Value *A = I.getOperand(0);
266 Value *B = Op1->getOperand(0);
267 Value *C = Op1->getOperand(1);
268
269 // Does "C op A" simplify?
270 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
271 // It simplifies to V. Form "B op V".
272 I.setOperand(0, B);
273 I.setOperand(1, V);
Dan Gohman5195b712011-02-02 02:05:46 +0000274 // Conservatively clear the optional flags, since they may not be
275 // preserved by the reassociation.
276 I.clearSubclassOptionalData();
Duncan Sands096aa792010-11-13 15:10:37 +0000277 Changed = true;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000278 ++NumReassoc;
Duncan Sands096aa792010-11-13 15:10:37 +0000279 continue;
280 }
281 }
282
283 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
284 // if C1 and C2 are constants.
285 if (Op0 && Op1 &&
286 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
287 isa<Constant>(Op0->getOperand(1)) &&
288 isa<Constant>(Op1->getOperand(1)) &&
289 Op0->hasOneUse() && Op1->hasOneUse()) {
290 Value *A = Op0->getOperand(0);
291 Constant *C1 = cast<Constant>(Op0->getOperand(1));
292 Value *B = Op1->getOperand(0);
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
294
295 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000296 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Eli Friedmana311c342011-05-27 00:19:40 +0000297 InsertNewInstWith(New, I);
Eli Friedmane6f364b2011-05-18 23:58:37 +0000298 New->takeName(Op1);
Duncan Sands096aa792010-11-13 15:10:37 +0000299 I.setOperand(0, New);
300 I.setOperand(1, Folded);
Dan Gohman5195b712011-02-02 02:05:46 +0000301 // Conservatively clear the optional flags, since they may not be
302 // preserved by the reassociation.
Nick Lewycky28b84ff2011-08-14 04:51:49 +0000303 I.clearSubclassOptionalData();
Nick Lewyckydaf27ea2011-08-14 01:45:19 +0000304
Duncan Sands096aa792010-11-13 15:10:37 +0000305 Changed = true;
306 continue;
307 }
308 }
309
310 // No further simplifications.
311 return Changed;
312 } while (1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000313}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000314
Duncan Sands5057f382010-11-23 14:23:47 +0000315/// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
Duncan Sandsc2b1c0b2010-11-23 15:25:34 +0000316/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sands5057f382010-11-23 14:23:47 +0000317static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
318 Instruction::BinaryOps ROp) {
319 switch (LOp) {
320 default:
321 return false;
322
323 case Instruction::And:
324 // And distributes over Or and Xor.
325 switch (ROp) {
326 default:
327 return false;
328 case Instruction::Or:
329 case Instruction::Xor:
330 return true;
331 }
332
333 case Instruction::Mul:
334 // Multiplication distributes over addition and subtraction.
335 switch (ROp) {
336 default:
337 return false;
338 case Instruction::Add:
339 case Instruction::Sub:
340 return true;
341 }
342
343 case Instruction::Or:
344 // Or distributes over And.
345 switch (ROp) {
346 default:
347 return false;
348 case Instruction::And:
349 return true;
350 }
351 }
352}
353
354/// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
355/// "(X ROp Z) LOp (Y ROp Z)".
356static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
357 Instruction::BinaryOps ROp) {
358 if (Instruction::isCommutative(ROp))
359 return LeftDistributesOverRight(ROp, LOp);
360 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
361 // but this requires knowing that the addition does not overflow and other
362 // such subtleties.
363 return false;
364}
365
Duncan Sands37bf92b2010-12-22 13:36:08 +0000366/// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
367/// which some other binary operation distributes over either by factorizing
368/// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
369/// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
370/// a win). Returns the simplified value, or null if it didn't simplify.
371Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
372 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
373 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
374 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
375 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
Duncan Sands5057f382010-11-23 14:23:47 +0000376
Duncan Sands37bf92b2010-12-22 13:36:08 +0000377 // Factorization.
378 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
379 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
380 // a common term.
381 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
382 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
383 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
Duncan Sands5057f382010-11-23 14:23:47 +0000384
Duncan Sands37bf92b2010-12-22 13:36:08 +0000385 // Does "X op' Y" always equal "Y op' X"?
386 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
Duncan Sands5057f382010-11-23 14:23:47 +0000387
Duncan Sands37bf92b2010-12-22 13:36:08 +0000388 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
389 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
390 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
391 // commutative case, "(A op' B) op (C op' A)"?
392 if (A == C || (InnerCommutative && A == D)) {
393 if (A != C)
394 std::swap(C, D);
395 // Consider forming "A op' (B op D)".
396 // If "B op D" simplifies then it can be formed with no cost.
397 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
398 // If "B op D" doesn't simplify then only go on if both of the existing
399 // operations "A op' B" and "C op' D" will be zapped as no longer used.
400 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
401 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
402 if (V) {
403 ++NumFactor;
404 V = Builder->CreateBinOp(InnerOpcode, A, V);
405 V->takeName(&I);
406 return V;
407 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000408 }
Duncan Sands5057f382010-11-23 14:23:47 +0000409
Duncan Sands37bf92b2010-12-22 13:36:08 +0000410 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
411 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
412 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
413 // commutative case, "(A op' B) op (B op' D)"?
414 if (B == D || (InnerCommutative && B == C)) {
415 if (B != D)
416 std::swap(C, D);
417 // Consider forming "(A op C) op' B".
418 // If "A op C" simplifies then it can be formed with no cost.
419 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
420 // If "A op C" doesn't simplify then only go on if both of the existing
421 // operations "A op' B" and "C op' D" will be zapped as no longer used.
422 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
423 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
424 if (V) {
425 ++NumFactor;
426 V = Builder->CreateBinOp(InnerOpcode, V, B);
427 V->takeName(&I);
428 return V;
429 }
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000430 }
Duncan Sands37bf92b2010-12-22 13:36:08 +0000431 }
432
433 // Expansion.
434 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
435 // The instruction has the form "(A op' B) op C". See if expanding it out
436 // to "(A op C) op' (B op C)" results in simplifications.
437 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
438 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
439
440 // Do "A op C" and "B op C" both simplify?
441 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
442 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
443 // They do! Return "L op' R".
444 ++NumExpand;
445 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
446 if ((L == A && R == B) ||
447 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
448 return Op0;
449 // Otherwise return "L op' R" if it simplifies.
450 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
451 return V;
452 // Otherwise, create a new instruction.
453 C = Builder->CreateBinOp(InnerOpcode, L, R);
454 C->takeName(&I);
455 return C;
456 }
457 }
458
459 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
460 // The instruction has the form "A op (B op' C)". See if expanding it out
461 // to "(A op B) op' (A op C)" results in simplifications.
462 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
463 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
464
465 // Do "A op B" and "A op C" both simplify?
466 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
467 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
468 // They do! Return "L op' R".
469 ++NumExpand;
470 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
471 if ((L == B && R == C) ||
472 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
473 return Op1;
474 // Otherwise return "L op' R" if it simplifies.
475 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
476 return V;
477 // Otherwise, create a new instruction.
478 A = Builder->CreateBinOp(InnerOpcode, L, R);
479 A->takeName(&I);
480 return A;
481 }
482 }
Duncan Sands5057f382010-11-23 14:23:47 +0000483
484 return 0;
485}
486
Chris Lattner8d969642003-03-10 23:06:50 +0000487// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
488// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000489//
Chris Lattner02446fc2010-01-04 07:37:31 +0000490Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000491 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000492 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000493
Chris Lattner0ce85802004-12-14 20:08:06 +0000494 // Constants can be considered to be negated values if they can be folded.
495 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000496 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000497
Chris Lattner7302d802012-02-06 21:56:39 +0000498 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
499 if (C->getType()->getElementType()->isIntegerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000500 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000501
Chris Lattner8d969642003-03-10 23:06:50 +0000502 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000503}
504
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000505// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
506// instruction if the LHS is a constant negative zero (which is the 'negate'
507// form).
508//
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000509Value *InstCombiner::dyn_castFNegVal(Value *V) const {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000510 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000511 return BinaryOperator::getFNegArgument(V);
512
513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000515 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000516
Chris Lattner7302d802012-02-06 21:56:39 +0000517 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
518 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000519 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000520
521 return 0;
522}
523
Chris Lattner6e7ba452005-01-01 16:22:27 +0000524static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000525 InstCombiner *IC) {
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000526 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +0000527 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000528 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000529
Chris Lattner2eefe512004-04-09 19:05:30 +0000530 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000531 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
532 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000533
Chris Lattner2eefe512004-04-09 19:05:30 +0000534 if (Constant *SOC = dyn_cast<Constant>(SO)) {
535 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000536 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
537 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000538 }
539
540 Value *Op0 = SO, *Op1 = ConstOperand;
541 if (!ConstIsRHS)
542 std::swap(Op0, Op1);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000543
Chris Lattner6e7ba452005-01-01 16:22:27 +0000544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +0000545 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
546 SO->getName()+".op");
547 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
548 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
549 SO->getName()+".cmp");
550 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
551 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
552 SO->getName()+".cmp");
553 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +0000554}
555
556// FoldOpIntoSelect - Given an instruction with a select as one operand and a
557// constant as the other operand, try to fold the binary operator into the
558// select arguments. This also works for Cast instructions, which obviously do
559// not have a second operand.
Chris Lattner80f43d32010-01-04 07:53:58 +0000560Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000561 // Don't modify shared select instructions
562 if (!SI->hasOneUse()) return 0;
563 Value *TV = SI->getOperand(1);
564 Value *FV = SI->getOperand(2);
565
566 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000567 // Bool selects with constant operands can be folded to logical ops.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000568 if (SI->getType()->isIntegerTy(1)) return 0;
Chris Lattner956db272005-04-21 05:43:13 +0000569
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000570 // If it's a bitcast involving vectors, make sure it has the same number of
571 // elements on both sides.
572 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000573 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
574 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000575
576 // Verify that either both or neither are vectors.
577 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
578 // If vectors, verify that they have the same number of elements.
579 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
580 return 0;
581 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000582
Chris Lattner80f43d32010-01-04 07:53:58 +0000583 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
584 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000585
Nick Lewyckyacf4a7c2011-01-21 02:30:43 +0000586 return SelectInst::Create(SI->getCondition(),
587 SelectTrueVal, SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +0000588 }
589 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000590}
591
Chris Lattner4e998b22004-09-29 05:07:12 +0000592
Chris Lattner5d1704d2009-09-27 19:57:57 +0000593/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
594/// has a PHI node as operand #0, see if we can fold the instruction into the
595/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000596///
Chris Lattner9922ccf2011-01-16 05:14:26 +0000597Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000598 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000599 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner5aac8322011-01-16 04:37:29 +0000600 if (NumPHIValues == 0)
Chris Lattner213cd612009-09-27 20:46:36 +0000601 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000602
Chris Lattner084fe622011-01-21 05:08:26 +0000603 // We normally only transform phis with a single use. However, if a PHI has
604 // multiple uses and they are all the same operation, we can fold *all* of the
605 // uses into the PHI.
Chris Lattner192228e2011-01-16 05:28:59 +0000606 if (!PN->hasOneUse()) {
607 // Walk the use list for the instruction, comparing them to I.
608 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnercd151d22011-01-21 05:29:50 +0000609 UI != E; ++UI) {
610 Instruction *User = cast<Instruction>(*UI);
611 if (User != &I && !I.isIdenticalTo(User))
Chris Lattner192228e2011-01-16 05:28:59 +0000612 return 0;
Chris Lattnercd151d22011-01-21 05:29:50 +0000613 }
Chris Lattner192228e2011-01-16 05:28:59 +0000614 // Otherwise, we can replace *all* users with the new PHI we form.
615 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000616
Chris Lattner5d1704d2009-09-27 19:57:57 +0000617 // Check to see if all of the operands of the PHI are simple constants
618 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000619 // remember the BB it is in. If there is more than one or if *it* is a PHI,
620 // bail out. We don't do arbitrary constant expressions here because moving
621 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000622 BasicBlock *NonConstBB = 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000623 for (unsigned i = 0; i != NumPHIValues; ++i) {
624 Value *InVal = PN->getIncomingValue(i);
625 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
626 continue;
627
628 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
629 if (NonConstBB) return 0; // More than one non-const value.
Jakub Staszak58c1da82012-05-06 13:52:31 +0000630
Chris Lattner5aac8322011-01-16 04:37:29 +0000631 NonConstBB = PN->getIncomingBlock(i);
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000632
633 // If the InVal is an invoke at the end of the pred block, then we can't
634 // insert a computation after it without breaking the edge.
635 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
636 if (II->getParent() == NonConstBB)
637 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000638
Chris Lattnercd151d22011-01-21 05:29:50 +0000639 // If the incoming non-constant value is in I's block, we will remove one
640 // instruction, but insert another equivalent one, leading to infinite
641 // instcombine.
642 if (NonConstBB == I.getParent())
643 return 0;
Chris Lattner5aac8322011-01-16 04:37:29 +0000644 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000645
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000646 // If there is exactly one non-constant value, we can insert a copy of the
647 // operation in that block. However, if this is a critical edge, we would be
648 // inserting the computation one some other paths (e.g. inside a loop). Only
649 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner9922ccf2011-01-16 05:14:26 +0000650 if (NonConstBB != 0) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000651 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
652 if (!BI || !BI->isUnconditional()) return 0;
653 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000654
655 // Okay, we can do the transformation: create the new PHI node.
Eli Friedmane6f364b2011-05-18 23:58:37 +0000656 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner857eb572009-10-21 23:41:58 +0000657 InsertNewInstBefore(NewPN, *PN);
658 NewPN->takeName(PN);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000659
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000660 // If we are going to have to insert a new computation, do so right before the
661 // predecessors terminator.
662 if (NonConstBB)
663 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszak58c1da82012-05-06 13:52:31 +0000664
Chris Lattner4e998b22004-09-29 05:07:12 +0000665 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +0000666 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
667 // We only currently try to fold the condition of a select when it is a phi,
668 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000669 Value *TrueV = SI->getTrueValue();
670 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +0000671 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +0000672 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000673 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +0000674 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
675 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000676 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000677 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000678 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000679 else
680 InV = Builder->CreateSelect(PN->getIncomingValue(i),
681 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerc6df8f42009-09-27 20:18:49 +0000682 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +0000683 }
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000684 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
685 Constant *C = cast<Constant>(I.getOperand(1));
686 for (unsigned i = 0; i != NumPHIValues; ++i) {
687 Value *InV = 0;
688 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
689 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
690 else if (isa<ICmpInst>(CI))
691 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
692 C, "phitmp");
693 else
694 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
695 C, "phitmp");
696 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
697 }
Chris Lattner5d1704d2009-09-27 19:57:57 +0000698 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000699 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000700 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000701 Value *InV = 0;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000702 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
703 InV = ConstantExpr::get(I.getOpcode(), InC, C);
704 else
705 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
706 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000707 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000708 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000709 } else {
Reid Spencer3da59db2006-11-27 01:05:10 +0000710 CastInst *CI = cast<CastInst>(&I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000711 Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000712 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000713 Value *InV;
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000714 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000715 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszak58c1da82012-05-06 13:52:31 +0000716 else
Chris Lattner7dfe8fd2011-01-16 05:08:00 +0000717 InV = Builder->CreateCast(CI->getOpcode(),
718 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner2a86f3b2006-09-09 22:02:56 +0000719 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +0000720 }
721 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000722
Chris Lattner192228e2011-01-16 05:28:59 +0000723 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
724 UI != E; ) {
725 Instruction *User = cast<Instruction>(*UI++);
726 if (User == &I) continue;
727 ReplaceInstUsesWith(*User, NewPN);
728 EraseInstFromFunction(*User);
729 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000730 return ReplaceInstUsesWith(I, NewPN);
731}
732
Chris Lattner46cd5a12009-01-09 05:44:56 +0000733/// FindElementAtOffset - Given a type and a constant offset, determine whether
734/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +0000735/// the specified offset. If so, fill them into NewIndices and return the
736/// resultant element type, otherwise return null.
Jakub Staszak58c1da82012-05-06 13:52:31 +0000737Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
Chris Lattner80f43d32010-01-04 07:53:58 +0000738 SmallVectorImpl<Value*> &NewIndices) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000739 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +0000740 if (!Ty->isSized()) return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000741
Chris Lattner46cd5a12009-01-09 05:44:56 +0000742 // Start with the index over the outer type. Note that the type size
743 // might be zero (even if the offset isn't zero) if the indexed type
744 // is something like [0 x {int, int}]
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000745 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
Chris Lattner46cd5a12009-01-09 05:44:56 +0000746 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +0000747 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000748 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +0000749 Offset -= FirstIdx*TySize;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000750
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000751 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +0000752 if (Offset < 0) {
753 --FirstIdx;
754 Offset += TySize;
755 assert(Offset >= 0);
756 }
757 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
758 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000759
Owen Andersoneed707b2009-07-24 23:12:02 +0000760 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszak58c1da82012-05-06 13:52:31 +0000761
Chris Lattner46cd5a12009-01-09 05:44:56 +0000762 // Index into the types. If we fail, set OrigBase to null.
763 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000764 // Indexing into tail padding between struct/array elements.
765 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +0000766 return 0;
Jakub Staszak58c1da82012-05-06 13:52:31 +0000767
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000768 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +0000769 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000770 assert(Offset < (int64_t)SL->getSizeInBytes() &&
771 "Offset must stay within the indexed type");
Jakub Staszak58c1da82012-05-06 13:52:31 +0000772
Chris Lattner46cd5a12009-01-09 05:44:56 +0000773 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattner4de84762010-01-04 07:02:48 +0000774 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
775 Elt));
Jakub Staszak58c1da82012-05-06 13:52:31 +0000776
Chris Lattner46cd5a12009-01-09 05:44:56 +0000777 Offset -= SL->getElementOffset(Elt);
778 Ty = STy->getElementType(Elt);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000779 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +0000780 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000781 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +0000782 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000783 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +0000784 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +0000785 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +0000786 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +0000787 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000788 }
789 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000790
Chris Lattner3914f722009-01-24 01:00:13 +0000791 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +0000792}
793
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000794static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
795 // If this GEP has only 0 indices, it is the same pointer as
796 // Src. If Src is not a trivial GEP too, don't combine
797 // the indices.
798 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
799 !Src.hasOneUse())
800 return false;
801 return true;
802}
Chris Lattner473945d2002-05-06 18:06:38 +0000803
Chris Lattner7e708292002-06-25 16:13:24 +0000804Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000805 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
806
Jay Foadb9b54eb2011-07-19 15:07:52 +0000807 if (Value *V = SimplifyGEPInst(Ops, TD))
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000808 return ReplaceInstUsesWith(GEP, V);
809
Chris Lattner620ce142004-05-07 22:09:22 +0000810 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000811
Duncan Sandsa63395a2010-11-22 16:32:50 +0000812 // Eliminate unneeded casts for indices, and replace indices which displace
813 // by multiples of a zero size type with zero.
Chris Lattnerccf4b342009-08-30 04:49:01 +0000814 if (TD) {
815 bool MadeChange = false;
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000816 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
Duncan Sandsa63395a2010-11-22 16:32:50 +0000817
Chris Lattnerccf4b342009-08-30 04:49:01 +0000818 gep_type_iterator GTI = gep_type_begin(GEP);
819 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
820 I != E; ++I, ++GTI) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000821 // Skip indices into struct types.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000822 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
Duncan Sandsa63395a2010-11-22 16:32:50 +0000823 if (!SeqTy) continue;
824
825 // If the element type has zero size then any index over it is equivalent
826 // to an index of zero, so replace it with zero if it is not zero already.
827 if (SeqTy->getElementType()->isSized() &&
828 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
829 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
830 *I = Constant::getNullValue(IntPtrTy);
831 MadeChange = true;
832 }
833
Nadav Rotem16087692011-12-05 06:29:09 +0000834 Type *IndexTy = (*I)->getType();
835 if (IndexTy != IntPtrTy && !IndexTy->isVectorTy()) {
Duncan Sandsa63395a2010-11-22 16:32:50 +0000836 // If we are using a wider index than needed for this platform, shrink
837 // it to what we need. If narrower, sign-extend it to what we need.
838 // This explicit cast can make subsequent optimizations more obvious.
839 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
840 MadeChange = true;
841 }
Chris Lattner28977af2004-04-05 01:30:19 +0000842 }
Chris Lattnerccf4b342009-08-30 04:49:01 +0000843 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +0000844 }
Chris Lattner28977af2004-04-05 01:30:19 +0000845
Chris Lattner90ac28c2002-08-02 19:29:35 +0000846 // Combine Indices - If the source pointer to this getelementptr instruction
847 // is a getelementptr instruction, combine the indices of the two
848 // getelementptr instructions into a single instruction.
849 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000850 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000851 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Rafael Espindolab5a12dd2011-07-11 03:43:47 +0000852 return 0;
853
Chris Lattner620ce142004-05-07 22:09:22 +0000854 // Note that if our source is a gep chain itself that we wait for that
855 // chain to be resolved before we perform this transformation. This
856 // avoids us creating a TON of code in some cases.
Rafael Espindola592ad6a2011-07-31 04:43:41 +0000857 if (GEPOperator *SrcGEP =
858 dyn_cast<GEPOperator>(Src->getOperand(0)))
859 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000860 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +0000861
Chris Lattner72588fc2007-02-15 22:48:32 +0000862 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +0000863
864 // Find out whether the last index in the source GEP is a sequential idx.
865 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +0000866 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
867 I != E; ++I)
Duncan Sands1df98592010-02-16 11:11:14 +0000868 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanfd939082005-04-21 23:48:37 +0000869
Chris Lattner90ac28c2002-08-02 19:29:35 +0000870 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +0000871 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +0000872 // Replace: gep (gep %P, long B), long A, ...
873 // With: T = long A+B; gep %P, T, ...
874 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000875 Value *Sum;
876 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
877 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +0000878 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000879 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +0000880 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +0000881 Sum = SO1;
882 } else {
Chris Lattnerab984842009-08-30 05:30:55 +0000883 // If they aren't the same type, then the input hasn't been processed
884 // by the loop above yet (which canonicalizes sequential index types to
885 // intptr_t). Just avoid transforming this until the input has been
886 // normalized.
887 if (SO1->getType() != GO1->getType())
888 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000889 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +0000890 }
Chris Lattner620ce142004-05-07 22:09:22 +0000891
Chris Lattnerab984842009-08-30 05:30:55 +0000892 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000893 if (Src->getNumOperands() == 2) {
894 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +0000895 GEP.setOperand(1, Sum);
896 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +0000897 }
Chris Lattnerab984842009-08-30 05:30:55 +0000898 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +0000899 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +0000900 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000901 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +0000902 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000903 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +0000904 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +0000905 Indices.append(Src->op_begin()+1, Src->op_end());
906 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +0000907 }
908
Dan Gohmanf8dbee72009-09-07 23:54:19 +0000909 if (!Indices.empty())
Chris Lattner948cdeb2010-01-05 07:42:10 +0000910 return (GEP.isInBounds() && Src->isInBounds()) ?
Jay Foada9203102011-07-25 09:48:08 +0000911 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
912 GEP.getName()) :
913 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +0000914 }
Nadav Rotem0286ca82011-04-05 14:29:52 +0000915
Chris Lattnerf9b91bb2009-08-30 05:08:50 +0000916 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattner948cdeb2010-01-05 07:42:10 +0000917 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Rotemc71108b2012-03-26 20:39:18 +0000918 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
919
Nadav Rotem02f0a492012-03-26 21:00:53 +0000920 // We do not handle pointer-vector geps here.
921 if (!StrippedPtrTy)
922 return 0;
923
Nadav Rotem0286ca82011-04-05 14:29:52 +0000924 if (StrippedPtr != PtrOp &&
925 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
Chris Lattner963f4ba2009-08-30 20:36:46 +0000926
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000927 bool HasZeroPointerIndex = false;
928 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
929 HasZeroPointerIndex = C->isZero();
Nadav Rotem0286ca82011-04-05 14:29:52 +0000930
Chris Lattner963f4ba2009-08-30 20:36:46 +0000931 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
932 // into : GEP [10 x i8]* X, i32 0, ...
933 //
934 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
935 // into : GEP i8* X, ...
Nadav Rotem0286ca82011-04-05 14:29:52 +0000936 //
Chris Lattner963f4ba2009-08-30 20:36:46 +0000937 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +0000938 if (HasZeroPointerIndex) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000939 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
940 if (ArrayType *CATy =
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000941 dyn_cast<ArrayType>(CPTy->getElementType())) {
942 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattner948cdeb2010-01-05 07:42:10 +0000943 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000944 // -> GEP i8* X, ...
Chris Lattner948cdeb2010-01-05 07:42:10 +0000945 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
946 GetElementPtrInst *Res =
Jay Foada9203102011-07-25 09:48:08 +0000947 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
Chris Lattner948cdeb2010-01-05 07:42:10 +0000948 Res->setIsInBounds(GEP.isInBounds());
949 return Res;
Chris Lattner963f4ba2009-08-30 20:36:46 +0000950 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000951
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000952 if (ArrayType *XATy =
Chris Lattner948cdeb2010-01-05 07:42:10 +0000953 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000954 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +0000955 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000956 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +0000957 // At this point, we know that the cast source type is a pointer
958 // to an array of the same type as the destination pointer
959 // array. Because the array type is never stepped over (there
960 // is a leading zero) we can fold the cast into this GEP.
Chris Lattner948cdeb2010-01-05 07:42:10 +0000961 GEP.setOperand(0, StrippedPtr);
Chris Lattnereed48272005-09-13 00:40:14 +0000962 return &GEP;
963 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +0000964 }
965 }
Chris Lattnereed48272005-09-13 00:40:14 +0000966 } else if (GEP.getNumOperands() == 2) {
967 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000968 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
969 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000970 Type *SrcElTy = StrippedPtrTy->getElementType();
971 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Duncan Sands1df98592010-02-16 11:11:14 +0000972 if (TD && SrcElTy->isArrayTy() &&
Duncan Sands777d2302009-05-09 07:06:46 +0000973 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
974 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +0000975 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +0000976 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +0000977 Idx[1] = GEP.getOperand(1);
Chris Lattner948cdeb2010-01-05 07:42:10 +0000978 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +0000979 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
980 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +0000981 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000982 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +0000983 }
Jakub Staszak58c1da82012-05-06 13:52:31 +0000984
Chris Lattner7835cdd2005-09-13 18:36:04 +0000985 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000986 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +0000987 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +0000988 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Jakub Staszak58c1da82012-05-06 13:52:31 +0000989
Duncan Sands1df98592010-02-16 11:11:14 +0000990 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +0000991 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +0000992 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Jakub Staszak58c1da82012-05-06 13:52:31 +0000993
Chris Lattner7835cdd2005-09-13 18:36:04 +0000994 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
995 // allow either a mul, shift, or constant here.
996 Value *NewIdx = 0;
997 ConstantInt *Scale = 0;
998 if (ArrayEltSize == 1) {
999 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +00001000 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00001001 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001002 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00001003 Scale = CI;
1004 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
1005 if (Inst->getOpcode() == Instruction::Shl &&
1006 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001007 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
1008 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +00001009 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +00001010 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00001011 NewIdx = Inst->getOperand(0);
1012 } else if (Inst->getOpcode() == Instruction::Mul &&
1013 isa<ConstantInt>(Inst->getOperand(1))) {
1014 Scale = cast<ConstantInt>(Inst->getOperand(1));
1015 NewIdx = Inst->getOperand(0);
1016 }
1017 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001018
Chris Lattner7835cdd2005-09-13 18:36:04 +00001019 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001020 // out, perform the transformation. Note, we don't know whether Scale is
1021 // signed or not. We'll use unsigned version of division/modulo
1022 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +00001023 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001024 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001025 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00001026 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00001027 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +00001028 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
1029 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001030 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +00001031 }
1032
1033 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00001034 Value *Idx[2];
Chris Lattner4de84762010-01-04 07:02:48 +00001035 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
David Greeneb8f74792007-09-04 15:46:09 +00001036 Idx[1] = NewIdx;
Chris Lattner948cdeb2010-01-05 07:42:10 +00001037 Value *NewGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001038 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
1039 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00001040 // The NewGEP must be pointer typed, so must the old one -> BitCast
1041 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00001042 }
1043 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00001044 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001045 }
Nadav Rotem0286ca82011-04-05 14:29:52 +00001046
Chris Lattner46cd5a12009-01-09 05:44:56 +00001047 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +00001048 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +00001049 /// Y = gep X, <...constant indices...>
1050 /// into a gep of the original struct. This is important for SROA and alias
1051 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +00001052 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00001053 if (TD &&
Nadav Rotem0286ca82011-04-05 14:29:52 +00001054 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
1055 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1056
Chris Lattner46cd5a12009-01-09 05:44:56 +00001057 // Determine how much the GEP moves the pointer. We are guaranteed to get
1058 // a constant back from EmitGEPOffset.
Chris Lattner02446fc2010-01-04 07:37:31 +00001059 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
Chris Lattner46cd5a12009-01-09 05:44:56 +00001060 int64_t Offset = OffsetV->getSExtValue();
Nadav Rotem0286ca82011-04-05 14:29:52 +00001061
Chris Lattner46cd5a12009-01-09 05:44:56 +00001062 // If this GEP instruction doesn't move the pointer, just replace the GEP
1063 // with a bitcast of the real input to the dest type.
1064 if (Offset == 0) {
1065 // If the bitcast is of an allocation, and the allocation will be
1066 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001067 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +00001068 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00001069 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1070 if (Instruction *I = visitBitCast(*BCI)) {
1071 if (I != BCI) {
1072 I->takeName(BCI);
1073 BCI->getParent()->getInstList().insert(BCI, I);
1074 ReplaceInstUsesWith(*BCI, I);
1075 }
1076 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +00001077 }
Chris Lattner58407792009-01-09 04:53:57 +00001078 }
Chris Lattner46cd5a12009-01-09 05:44:56 +00001079 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +00001080 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001081
Chris Lattner46cd5a12009-01-09 05:44:56 +00001082 // Otherwise, if the offset is non-zero, we need to find out if there is a
1083 // field at Offset in 'A's type. If so, we can pull the cast through the
1084 // GEP.
1085 SmallVector<Value*, 8> NewIndices;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001086 Type *InTy =
Chris Lattner46cd5a12009-01-09 05:44:56 +00001087 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Chris Lattner80f43d32010-01-04 07:53:58 +00001088 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
Chris Lattner948cdeb2010-01-05 07:42:10 +00001089 Value *NGEP = GEP.isInBounds() ?
Jay Foad0a2a60a2011-07-22 08:16:57 +00001090 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1091 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
Jakub Staszak58c1da82012-05-06 13:52:31 +00001092
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001093 if (NGEP->getType() == GEP.getType())
1094 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +00001095 NGEP->takeName(&GEP);
1096 return new BitCastInst(NGEP, GEP.getType());
1097 }
Chris Lattner58407792009-01-09 04:53:57 +00001098 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001099 }
1100
Chris Lattner8a2a3112001-12-14 16:52:21 +00001101 return 0;
1102}
1103
Duncan Sands1d9b9732010-05-27 19:09:06 +00001104
1105
Nick Lewyckydbd22552011-08-03 01:11:40 +00001106static bool IsOnlyNullComparedAndFreed(Value *V, SmallVectorImpl<WeakVH> &Users,
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001107 int Depth = 0) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001108 if (Depth == 8)
1109 return false;
1110
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001111 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
Duncan Sands1d9b9732010-05-27 19:09:06 +00001112 UI != UE; ++UI) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001113 User *U = *UI;
1114 if (isFreeCall(U)) {
1115 Users.push_back(U);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001116 continue;
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001117 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001118 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
1119 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) {
1120 Users.push_back(ICI);
1121 continue;
1122 }
1123 }
1124 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1125 if (IsOnlyNullComparedAndFreed(BCI, Users, Depth+1)) {
1126 Users.push_back(BCI);
1127 continue;
1128 }
1129 }
1130 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
Nick Lewyckydbd22552011-08-03 01:11:40 +00001131 if (IsOnlyNullComparedAndFreed(GEPI, Users, Depth+1)) {
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001132 Users.push_back(GEPI);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001133 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001134 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001135 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001136 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001137 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001138 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1139 Users.push_back(II);
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001140 continue;
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001141 }
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001142 }
Duncan Sands1d9b9732010-05-27 19:09:06 +00001143 return false;
1144 }
1145 return true;
1146}
1147
1148Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1149 // If we have a malloc call which is only used in any amount of comparisons
1150 // to null and free calls, delete the calls and replace the comparisons with
1151 // true or false as appropriate.
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001152 SmallVector<WeakVH, 64> Users;
1153 if (IsOnlyNullComparedAndFreed(&MI, Users)) {
1154 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1155 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1156 if (!I) continue;
Duncan Sands1d9b9732010-05-27 19:09:06 +00001157
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001158 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001159 ReplaceInstUsesWith(*C,
1160 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1161 C->isFalseWhenEqual()));
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001162 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckyd8030c72011-08-02 22:08:01 +00001163 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sands1d9b9732010-05-27 19:09:06 +00001164 }
Nick Lewyckyd5061a92011-08-03 00:43:35 +00001165 EraseInstFromFunction(*I);
Duncan Sands1d9b9732010-05-27 19:09:06 +00001166 }
1167 return EraseInstFromFunction(MI);
1168 }
1169 return 0;
1170}
1171
1172
1173
Gabor Greif91697372010-06-24 12:21:15 +00001174Instruction *InstCombiner::visitFree(CallInst &FI) {
1175 Value *Op = FI.getArgOperand(0);
Victor Hernandez66284e02009-10-24 04:23:03 +00001176
1177 // free undef -> unreachable.
1178 if (isa<UndefValue>(Op)) {
1179 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedmane6f364b2011-05-18 23:58:37 +00001180 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1181 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandez66284e02009-10-24 04:23:03 +00001182 return EraseInstFromFunction(FI);
1183 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001184
Victor Hernandez66284e02009-10-24 04:23:03 +00001185 // If we have 'free null' delete the instruction. This can happen in stl code
1186 // when lots of inlining happens.
1187 if (isa<ConstantPointerNull>(Op))
1188 return EraseInstFromFunction(FI);
1189
Victor Hernandez66284e02009-10-24 04:23:03 +00001190 return 0;
1191}
Chris Lattner67b1e1b2003-12-07 01:24:23 +00001192
Chris Lattner3284d1f2007-04-15 00:07:55 +00001193
Chris Lattner2f503e62005-01-31 05:36:43 +00001194
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001195Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1196 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00001197 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001198 BasicBlock *TrueDest;
1199 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +00001200 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001201 !isa<Constant>(X)) {
1202 // Swap Destinations and condition...
1203 BI.setCondition(X);
Chandler Carruth602650c2011-10-17 01:11:57 +00001204 BI.swapSuccessors();
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001205 return &BI;
1206 }
1207
Reid Spencere4d87aa2006-12-23 06:05:41 +00001208 // Cannonicalize fcmp_one -> fcmp_oeq
1209 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001210 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001211 TrueDest, FalseDest)) &&
1212 BI.getCondition()->hasOneUse())
1213 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1214 FPred == FCmpInst::FCMP_OGE) {
1215 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1216 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszak58c1da82012-05-06 13:52:31 +00001217
Chris Lattner7a1e9242009-08-30 06:13:40 +00001218 // Swap Destinations and condition.
Chandler Carruth602650c2011-10-17 01:11:57 +00001219 BI.swapSuccessors();
Chris Lattner7a1e9242009-08-30 06:13:40 +00001220 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001221 return &BI;
1222 }
1223
1224 // Cannonicalize icmp_ne -> icmp_eq
1225 ICmpInst::Predicate IPred;
1226 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +00001227 TrueDest, FalseDest)) &&
1228 BI.getCondition()->hasOneUse())
1229 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1230 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1231 IPred == ICmpInst::ICMP_SGE) {
1232 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1233 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1234 // Swap Destinations and condition.
Chandler Carruth602650c2011-10-17 01:11:57 +00001235 BI.swapSuccessors();
Chris Lattner7a1e9242009-08-30 06:13:40 +00001236 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +00001237 return &BI;
1238 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001239
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00001240 return 0;
1241}
Chris Lattner0864acf2002-11-04 16:18:53 +00001242
Chris Lattner46238a62004-07-03 00:26:11 +00001243Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1244 Value *Cond = SI.getCondition();
1245 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1246 if (I->getOpcode() == Instruction::Add)
1247 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1248 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001249 // Skip the first item since that's the default case.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001250 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001251 i != e; ++i) {
1252 ConstantInt* CaseVal = i.getCaseValue();
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001253 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1254 AddRHS);
1255 assert(isa<ConstantInt>(NewCaseVal) &&
1256 "Result of expression should be constant");
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001257 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedmanbb5a7442011-09-29 20:21:17 +00001258 }
1259 SI.setCondition(I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00001260 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +00001261 return &SI;
1262 }
1263 }
1264 return 0;
1265}
1266
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001267Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001268 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001269
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001270 if (!EV.hasIndices())
1271 return ReplaceInstUsesWith(EV, Agg);
1272
1273 if (Constant *C = dyn_cast<Constant>(Agg)) {
Chris Lattnerd59ae902012-01-26 02:32:04 +00001274 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1275 if (EV.getNumIndices() == 0)
1276 return ReplaceInstUsesWith(EV, C2);
1277 // Extract the remaining indices out of the constant indexed by the
1278 // first index
1279 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001280 }
1281 return 0; // Can't handle other constants
Chris Lattnerd59ae902012-01-26 02:32:04 +00001282 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001283
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001284 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1285 // We're extracting from an insertvalue instruction, compare the indices
1286 const unsigned *exti, *exte, *insi, *inse;
1287 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1288 exte = EV.idx_end(), inse = IV->idx_end();
1289 exti != exte && insi != inse;
1290 ++exti, ++insi) {
1291 if (*insi != *exti)
1292 // The insert and extract both reference distinctly different elements.
1293 // This means the extract is not influenced by the insert, and we can
1294 // replace the aggregate operand of the extract with the aggregate
1295 // operand of the insert. i.e., replace
1296 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1297 // %E = extractvalue { i32, { i32 } } %I, 0
1298 // with
1299 // %E = extractvalue { i32, { i32 } } %A, 0
1300 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001301 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001302 }
1303 if (exti == exte && insi == inse)
1304 // Both iterators are at the end: Index lists are identical. Replace
1305 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1306 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1307 // with "i32 42"
1308 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1309 if (exti == exte) {
1310 // The extract list is a prefix of the insert list. i.e. replace
1311 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1312 // %E = extractvalue { i32, { i32 } } %I, 1
1313 // with
1314 // %X = extractvalue { i32, { i32 } } %A, 1
1315 // %E = insertvalue { i32 } %X, i32 42, 0
1316 // by switching the order of the insert and extract (though the
1317 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +00001318 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +00001319 EV.getIndices());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001320 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001321 makeArrayRef(insi, inse));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001322 }
1323 if (insi == inse)
1324 // The insert list is a prefix of the extract list
1325 // We can simply remove the common indices from the extract and make it
1326 // operate on the inserted value instead of the insertvalue result.
1327 // i.e., replace
1328 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1329 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1330 // with
1331 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszak58c1da82012-05-06 13:52:31 +00001332 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel39b5abf2011-07-18 12:00:32 +00001333 makeArrayRef(exti, exte));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001334 }
Chris Lattner7e606e22009-11-09 07:07:56 +00001335 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1336 // We're extracting from an intrinsic, see if we're the only user, which
1337 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif91697372010-06-24 12:21:15 +00001338 // just get one value.
Chris Lattner7e606e22009-11-09 07:07:56 +00001339 if (II->hasOneUse()) {
1340 // Check if we're grabbing the overflow bit or the result of a 'with
1341 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1342 // and replace it with a traditional binary instruction.
1343 switch (II->getIntrinsicID()) {
1344 case Intrinsic::uadd_with_overflow:
1345 case Intrinsic::sadd_with_overflow:
1346 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001347 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001348 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001349 EraseInstFromFunction(*II);
1350 return BinaryOperator::CreateAdd(LHS, RHS);
1351 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001352
Chris Lattner74b64612010-12-19 19:43:52 +00001353 // If the normal result of the add is dead, and the RHS is a constant,
1354 // we can transform this into a range comparison.
1355 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattnerf2a97ed2010-12-19 23:24:04 +00001356 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1357 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1358 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1359 ConstantExpr::getNot(CI));
Chris Lattner7e606e22009-11-09 07:07:56 +00001360 break;
1361 case Intrinsic::usub_with_overflow:
1362 case Intrinsic::ssub_with_overflow:
1363 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001364 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001365 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001366 EraseInstFromFunction(*II);
1367 return BinaryOperator::CreateSub(LHS, RHS);
1368 }
1369 break;
1370 case Intrinsic::umul_with_overflow:
1371 case Intrinsic::smul_with_overflow:
1372 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif91697372010-06-24 12:21:15 +00001373 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedman3e22cb92011-05-18 00:32:01 +00001374 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner7e606e22009-11-09 07:07:56 +00001375 EraseInstFromFunction(*II);
1376 return BinaryOperator::CreateMul(LHS, RHS);
1377 }
1378 break;
1379 default:
1380 break;
1381 }
1382 }
1383 }
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001384 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1385 // If the (non-volatile) load only has one use, we can rewrite this to a
1386 // load from a GEP. This reduces the size of the load.
1387 // FIXME: If a load is used only by extractvalue instructions then this
1388 // could be done regardless of having multiple uses.
Eli Friedmancc4a0432011-08-15 22:09:40 +00001389 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001390 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1391 SmallVector<Value*, 4> Indices;
1392 // Prefix an i32 0 since we need the first element.
1393 Indices.push_back(Builder->getInt32(0));
1394 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1395 I != E; ++I)
1396 Indices.push_back(Builder->getInt32(*I));
1397
1398 // We need to insert these at the location of the old load, not at that of
1399 // the extractvalue.
1400 Builder->SetInsertPoint(L->getParent(), L);
Jay Foad0a2a60a2011-07-22 08:16:57 +00001401 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001402 // Returning the load directly will cause the main loop to insert it in
1403 // the wrong spot, so use ReplaceInstUsesWith().
1404 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1405 }
1406 // We could simplify extracts from other values. Note that nested extracts may
1407 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +00001408 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel34ceb4d2010-11-29 21:56:20 +00001409 // the value inserted, if appropriate. Similarly for extracts from single-use
1410 // loads: extract (extract (load)) will be translated to extract (load (gep))
1411 // and if again single-use then via load (gep (gep)) to load (gep).
1412 // However, double extracts from e.g. function arguments or return values
1413 // aren't handled yet.
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +00001414 return 0;
1415}
1416
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001417enum Personality_Type {
1418 Unknown_Personality,
1419 GNU_Ada_Personality,
Bill Wendling76f267d2011-10-17 21:20:24 +00001420 GNU_CXX_Personality,
1421 GNU_ObjC_Personality
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001422};
1423
1424/// RecognizePersonality - See if the given exception handling personality
1425/// function is one that we understand. If so, return a description of it;
1426/// otherwise return Unknown_Personality.
1427static Personality_Type RecognizePersonality(Value *Pers) {
1428 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1429 if (!F)
1430 return Unknown_Personality;
1431 return StringSwitch<Personality_Type>(F->getName())
1432 .Case("__gnat_eh_personality", GNU_Ada_Personality)
Bill Wendling76f267d2011-10-17 21:20:24 +00001433 .Case("__gxx_personality_v0", GNU_CXX_Personality)
1434 .Case("__objc_personality_v0", GNU_ObjC_Personality)
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001435 .Default(Unknown_Personality);
1436}
1437
1438/// isCatchAll - Return 'true' if the given typeinfo will match anything.
1439static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1440 switch (Personality) {
1441 case Unknown_Personality:
1442 return false;
1443 case GNU_Ada_Personality:
1444 // While __gnat_all_others_value will match any Ada exception, it doesn't
1445 // match foreign exceptions (or didn't, before gcc-4.7).
1446 return false;
1447 case GNU_CXX_Personality:
Bill Wendling76f267d2011-10-17 21:20:24 +00001448 case GNU_ObjC_Personality:
Duncan Sands0ad7b6e2011-09-30 13:12:16 +00001449 return TypeInfo->isNullValue();
1450 }
1451 llvm_unreachable("Unknown personality!");
1452}
1453
1454static bool shorter_filter(const Value *LHS, const Value *RHS) {
1455 return
1456 cast<ArrayType>(LHS->getType())->getNumElements()
1457 <
1458 cast<ArrayType>(RHS->getType())->getNumElements();
1459}
1460
1461Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1462 // The logic here should be correct for any real-world personality function.
1463 // However if that turns out not to be true, the offending logic can always
1464 // be conditioned on the personality function, like the catch-all logic is.
1465 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1466
1467 // Simplify the list of clauses, eg by removing repeated catch clauses
1468 // (these are often created by inlining).
1469 bool MakeNewInstruction = false; // If true, recreate using the following:
1470 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1471 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
1472
1473 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1474 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1475 bool isLastClause = i + 1 == e;
1476 if (LI.isCatch(i)) {
1477 // A catch clause.
1478 Value *CatchClause = LI.getClause(i);
1479 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1480
1481 // If we already saw this clause, there is no point in having a second
1482 // copy of it.
1483 if (AlreadyCaught.insert(TypeInfo)) {
1484 // This catch clause was not already seen.
1485 NewClauses.push_back(CatchClause);
1486 } else {
1487 // Repeated catch clause - drop the redundant copy.
1488 MakeNewInstruction = true;
1489 }
1490
1491 // If this is a catch-all then there is no point in keeping any following
1492 // clauses or marking the landingpad as having a cleanup.
1493 if (isCatchAll(Personality, TypeInfo)) {
1494 if (!isLastClause)
1495 MakeNewInstruction = true;
1496 CleanupFlag = false;
1497 break;
1498 }
1499 } else {
1500 // A filter clause. If any of the filter elements were already caught
1501 // then they can be dropped from the filter. It is tempting to try to
1502 // exploit the filter further by saying that any typeinfo that does not
1503 // occur in the filter can't be caught later (and thus can be dropped).
1504 // However this would be wrong, since typeinfos can match without being
1505 // equal (for example if one represents a C++ class, and the other some
1506 // class derived from it).
1507 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1508 Value *FilterClause = LI.getClause(i);
1509 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1510 unsigned NumTypeInfos = FilterType->getNumElements();
1511
1512 // An empty filter catches everything, so there is no point in keeping any
1513 // following clauses or marking the landingpad as having a cleanup. By
1514 // dealing with this case here the following code is made a bit simpler.
1515 if (!NumTypeInfos) {
1516 NewClauses.push_back(FilterClause);
1517 if (!isLastClause)
1518 MakeNewInstruction = true;
1519 CleanupFlag = false;
1520 break;
1521 }
1522
1523 bool MakeNewFilter = false; // If true, make a new filter.
1524 SmallVector<Constant *, 16> NewFilterElts; // New elements.
1525 if (isa<ConstantAggregateZero>(FilterClause)) {
1526 // Not an empty filter - it contains at least one null typeinfo.
1527 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1528 Constant *TypeInfo =
1529 Constant::getNullValue(FilterType->getElementType());
1530 // If this typeinfo is a catch-all then the filter can never match.
1531 if (isCatchAll(Personality, TypeInfo)) {
1532 // Throw the filter away.
1533 MakeNewInstruction = true;
1534 continue;
1535 }
1536
1537 // There is no point in having multiple copies of this typeinfo, so
1538 // discard all but the first copy if there is more than one.
1539 NewFilterElts.push_back(TypeInfo);
1540 if (NumTypeInfos > 1)
1541 MakeNewFilter = true;
1542 } else {
1543 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1544 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1545 NewFilterElts.reserve(NumTypeInfos);
1546
1547 // Remove any filter elements that were already caught or that already
1548 // occurred in the filter. While there, see if any of the elements are
1549 // catch-alls. If so, the filter can be discarded.
1550 bool SawCatchAll = false;
1551 for (unsigned j = 0; j != NumTypeInfos; ++j) {
1552 Value *Elt = Filter->getOperand(j);
1553 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1554 if (isCatchAll(Personality, TypeInfo)) {
1555 // This element is a catch-all. Bail out, noting this fact.
1556 SawCatchAll = true;
1557 break;
1558 }
1559 if (AlreadyCaught.count(TypeInfo))
1560 // Already caught by an earlier clause, so having it in the filter
1561 // is pointless.
1562 continue;
1563 // There is no point in having multiple copies of the same typeinfo in
1564 // a filter, so only add it if we didn't already.
1565 if (SeenInFilter.insert(TypeInfo))
1566 NewFilterElts.push_back(cast<Constant>(Elt));
1567 }
1568 // A filter containing a catch-all cannot match anything by definition.
1569 if (SawCatchAll) {
1570 // Throw the filter away.
1571 MakeNewInstruction = true;
1572 continue;
1573 }
1574
1575 // If we dropped something from the filter, make a new one.
1576 if (NewFilterElts.size() < NumTypeInfos)
1577 MakeNewFilter = true;
1578 }
1579 if (MakeNewFilter) {
1580 FilterType = ArrayType::get(FilterType->getElementType(),
1581 NewFilterElts.size());
1582 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1583 MakeNewInstruction = true;
1584 }
1585
1586 NewClauses.push_back(FilterClause);
1587
1588 // If the new filter is empty then it will catch everything so there is
1589 // no point in keeping any following clauses or marking the landingpad
1590 // as having a cleanup. The case of the original filter being empty was
1591 // already handled above.
1592 if (MakeNewFilter && !NewFilterElts.size()) {
1593 assert(MakeNewInstruction && "New filter but not a new instruction!");
1594 CleanupFlag = false;
1595 break;
1596 }
1597 }
1598 }
1599
1600 // If several filters occur in a row then reorder them so that the shortest
1601 // filters come first (those with the smallest number of elements). This is
1602 // advantageous because shorter filters are more likely to match, speeding up
1603 // unwinding, but mostly because it increases the effectiveness of the other
1604 // filter optimizations below.
1605 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1606 unsigned j;
1607 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1608 for (j = i; j != e; ++j)
1609 if (!isa<ArrayType>(NewClauses[j]->getType()))
1610 break;
1611
1612 // Check whether the filters are already sorted by length. We need to know
1613 // if sorting them is actually going to do anything so that we only make a
1614 // new landingpad instruction if it does.
1615 for (unsigned k = i; k + 1 < j; ++k)
1616 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
1617 // Not sorted, so sort the filters now. Doing an unstable sort would be
1618 // correct too but reordering filters pointlessly might confuse users.
1619 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
1620 shorter_filter);
1621 MakeNewInstruction = true;
1622 break;
1623 }
1624
1625 // Look for the next batch of filters.
1626 i = j + 1;
1627 }
1628
1629 // If typeinfos matched if and only if equal, then the elements of a filter L
1630 // that occurs later than a filter F could be replaced by the intersection of
1631 // the elements of F and L. In reality two typeinfos can match without being
1632 // equal (for example if one represents a C++ class, and the other some class
1633 // derived from it) so it would be wrong to perform this transform in general.
1634 // However the transform is correct and useful if F is a subset of L. In that
1635 // case L can be replaced by F, and thus removed altogether since repeating a
1636 // filter is pointless. So here we look at all pairs of filters F and L where
1637 // L follows F in the list of clauses, and remove L if every element of F is
1638 // an element of L. This can occur when inlining C++ functions with exception
1639 // specifications.
1640 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
1641 // Examine each filter in turn.
1642 Value *Filter = NewClauses[i];
1643 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
1644 if (!FTy)
1645 // Not a filter - skip it.
1646 continue;
1647 unsigned FElts = FTy->getNumElements();
1648 // Examine each filter following this one. Doing this backwards means that
1649 // we don't have to worry about filters disappearing under us when removed.
1650 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
1651 Value *LFilter = NewClauses[j];
1652 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
1653 if (!LTy)
1654 // Not a filter - skip it.
1655 continue;
1656 // If Filter is a subset of LFilter, i.e. every element of Filter is also
1657 // an element of LFilter, then discard LFilter.
1658 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
1659 // If Filter is empty then it is a subset of LFilter.
1660 if (!FElts) {
1661 // Discard LFilter.
1662 NewClauses.erase(J);
1663 MakeNewInstruction = true;
1664 // Move on to the next filter.
1665 continue;
1666 }
1667 unsigned LElts = LTy->getNumElements();
1668 // If Filter is longer than LFilter then it cannot be a subset of it.
1669 if (FElts > LElts)
1670 // Move on to the next filter.
1671 continue;
1672 // At this point we know that LFilter has at least one element.
1673 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
1674 // Filter is a subset of LFilter iff Filter contains only zeros (as we
1675 // already know that Filter is not longer than LFilter).
1676 if (isa<ConstantAggregateZero>(Filter)) {
1677 assert(FElts <= LElts && "Should have handled this case earlier!");
1678 // Discard LFilter.
1679 NewClauses.erase(J);
1680 MakeNewInstruction = true;
1681 }
1682 // Move on to the next filter.
1683 continue;
1684 }
1685 ConstantArray *LArray = cast<ConstantArray>(LFilter);
1686 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
1687 // Since Filter is non-empty and contains only zeros, it is a subset of
1688 // LFilter iff LFilter contains a zero.
1689 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
1690 for (unsigned l = 0; l != LElts; ++l)
1691 if (LArray->getOperand(l)->isNullValue()) {
1692 // LFilter contains a zero - discard it.
1693 NewClauses.erase(J);
1694 MakeNewInstruction = true;
1695 break;
1696 }
1697 // Move on to the next filter.
1698 continue;
1699 }
1700 // At this point we know that both filters are ConstantArrays. Loop over
1701 // operands to see whether every element of Filter is also an element of
1702 // LFilter. Since filters tend to be short this is probably faster than
1703 // using a method that scales nicely.
1704 ConstantArray *FArray = cast<ConstantArray>(Filter);
1705 bool AllFound = true;
1706 for (unsigned f = 0; f != FElts; ++f) {
1707 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
1708 AllFound = false;
1709 for (unsigned l = 0; l != LElts; ++l) {
1710 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
1711 if (LTypeInfo == FTypeInfo) {
1712 AllFound = true;
1713 break;
1714 }
1715 }
1716 if (!AllFound)
1717 break;
1718 }
1719 if (AllFound) {
1720 // Discard LFilter.
1721 NewClauses.erase(J);
1722 MakeNewInstruction = true;
1723 }
1724 // Move on to the next filter.
1725 }
1726 }
1727
1728 // If we changed any of the clauses, replace the old landingpad instruction
1729 // with a new one.
1730 if (MakeNewInstruction) {
1731 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
1732 LI.getPersonalityFn(),
1733 NewClauses.size());
1734 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
1735 NLI->addClause(NewClauses[i]);
1736 // A landing pad with no clauses must have the cleanup flag set. It is
1737 // theoretically possible, though highly unlikely, that we eliminated all
1738 // clauses. If so, force the cleanup flag to true.
1739 if (NewClauses.empty())
1740 CleanupFlag = true;
1741 NLI->setCleanup(CleanupFlag);
1742 return NLI;
1743 }
1744
1745 // Even if none of the clauses changed, we may nonetheless have understood
1746 // that the cleanup flag is pointless. Clear it if so.
1747 if (LI.isCleanup() != CleanupFlag) {
1748 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
1749 LI.setCleanup(CleanupFlag);
1750 return &LI;
1751 }
1752
1753 return 0;
1754}
1755
Chris Lattnera844fc4c2006-04-10 22:45:52 +00001756
Robert Bocchino1d7456d2006-01-13 22:48:06 +00001757
Chris Lattnerea1c4542004-12-08 23:43:58 +00001758
1759/// TryToSinkInstruction - Try to move the specified instruction from its
1760/// current block into the beginning of DestBlock, which can only happen if it's
1761/// safe to move the instruction past all of the instructions between it and the
1762/// end of its block.
1763static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1764 assert(I->hasOneUse() && "Invariants didn't hold!");
1765
Bill Wendling9d6070f2011-08-15 21:14:31 +00001766 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Bill Wendlingc9b2a982011-08-17 20:36:44 +00001767 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
1768 isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +00001769 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00001770
Chris Lattnerea1c4542004-12-08 23:43:58 +00001771 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00001772 if (isa<AllocaInst>(I) && I->getParent() ==
1773 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001774 return false;
1775
Chris Lattner96a52a62004-12-09 07:14:34 +00001776 // We can only sink load instructions if there is nothing between the load and
1777 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +00001778 if (I->mayReadFromMemory()) {
1779 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +00001780 Scan != E; ++Scan)
1781 if (Scan->mayWriteToMemory())
1782 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00001783 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00001784
Bill Wendling5b6f42f2011-08-16 20:45:24 +00001785 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Chris Lattner4bc5f802005-08-08 19:11:57 +00001786 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00001787 ++NumSunkInst;
1788 return true;
1789}
1790
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001791
1792/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1793/// all reachable code to the worklist.
1794///
1795/// This has a couple of tricks to make the code faster and more powerful. In
1796/// particular, we constant fold and DCE instructions as we go, to avoid adding
1797/// them to the worklist (this significantly speeds up instcombine on code where
1798/// many instructions are dead or constant). Additionally, if we find a branch
1799/// whose condition is a known constant, we only visit the reachable successors.
1800///
Jakub Staszak58c1da82012-05-06 13:52:31 +00001801static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +00001802 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +00001803 InstCombiner &IC,
Chad Rosier00737bd2011-12-01 21:29:16 +00001804 const TargetData *TD,
1805 const TargetLibraryInfo *TLI) {
Chris Lattner2ee743b2009-10-15 04:59:28 +00001806 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +00001807 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +00001808 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001809
Benjamin Kramera53fe602010-10-23 17:10:24 +00001810 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001811 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1812
Dan Gohman321a8132010-01-05 16:27:25 +00001813 do {
1814 BB = Worklist.pop_back_val();
Jakub Staszak58c1da82012-05-06 13:52:31 +00001815
Chris Lattner2c7718a2007-03-23 19:17:18 +00001816 // We have now visited this block! If we've already been here, ignore it.
1817 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +00001818
Chris Lattner2c7718a2007-03-23 19:17:18 +00001819 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1820 Instruction *Inst = BBI++;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001821
Chris Lattner2c7718a2007-03-23 19:17:18 +00001822 // DCE instruction if trivially dead.
1823 if (isInstructionTriviallyDead(Inst)) {
1824 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00001825 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +00001826 Inst->eraseFromParent();
1827 continue;
1828 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001829
Chris Lattner2c7718a2007-03-23 19:17:18 +00001830 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001831 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chad Rosier00737bd2011-12-01 21:29:16 +00001832 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001833 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1834 << *Inst << '\n');
1835 Inst->replaceAllUsesWith(C);
1836 ++NumConstProp;
1837 Inst->eraseFromParent();
1838 continue;
1839 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001840
Chris Lattner2ee743b2009-10-15 04:59:28 +00001841 if (TD) {
1842 // See if we can constant fold its operands.
1843 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1844 i != e; ++i) {
1845 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1846 if (CE == 0) continue;
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001847
1848 Constant*& FoldRes = FoldedConstants[CE];
1849 if (!FoldRes)
Chad Rosieraab8e282011-12-02 01:26:24 +00001850 FoldRes = ConstantFoldConstantExpression(CE, TD, TLI);
Eli Friedmana4d4aeb2011-05-24 18:52:07 +00001851 if (!FoldRes)
1852 FoldRes = CE;
1853
1854 if (FoldRes != CE) {
1855 *i = FoldRes;
Chris Lattner2ee743b2009-10-15 04:59:28 +00001856 MadeIRChange = true;
1857 }
1858 }
1859 }
Devang Patel7fe1dec2008-11-19 18:56:50 +00001860
Chris Lattner67f7d542009-10-12 03:58:40 +00001861 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001862 }
Chris Lattner2c7718a2007-03-23 19:17:18 +00001863
1864 // Recursively visit successors. If this is a branch or switch on a
1865 // constant, only visit the reachable successor.
1866 TerminatorInst *TI = BB->getTerminator();
1867 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1868 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1869 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +00001870 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +00001871 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001872 continue;
1873 }
1874 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1875 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1876 // See if this is an explicit destination.
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00001877 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00001878 i != e; ++i)
1879 if (i.getCaseValue() == Cond) {
1880 BasicBlock *ReachableBB = i.getCaseSuccessor();
Nick Lewycky280a6e62008-04-25 16:53:59 +00001881 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +00001882 continue;
1883 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001884
Chris Lattner2c7718a2007-03-23 19:17:18 +00001885 // Otherwise it is the default destination.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00001886 Worklist.push_back(SI->getDefaultDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +00001887 continue;
1888 }
1889 }
Jakub Staszak58c1da82012-05-06 13:52:31 +00001890
Chris Lattner2c7718a2007-03-23 19:17:18 +00001891 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1892 Worklist.push_back(TI->getSuccessor(i));
Dan Gohman321a8132010-01-05 16:27:25 +00001893 } while (!Worklist.empty());
Jakub Staszak58c1da82012-05-06 13:52:31 +00001894
Chris Lattner67f7d542009-10-12 03:58:40 +00001895 // Once we've found all of the instructions to add to instcombine's worklist,
1896 // add them in reverse order. This way instcombine will visit from the top
1897 // of the function down. This jives well with the way that it adds all uses
1898 // of instructions to the worklist after doing a transformation, thus avoiding
1899 // some N^2 behavior in pathological cases.
1900 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1901 InstrsForInstCombineWorklist.size());
Jakub Staszak58c1da82012-05-06 13:52:31 +00001902
Chris Lattner2ee743b2009-10-15 04:59:28 +00001903 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001904}
1905
Chris Lattnerec9c3582007-03-03 02:04:50 +00001906bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001907 MadeIRChange = false;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001908
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001909 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
Benjamin Kramera7b0cb72011-11-15 16:27:03 +00001910 << F.getName() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +00001911
Chris Lattnerb3d59702005-07-07 20:40:38 +00001912 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00001913 // Do a depth-first traversal of the function, populate the worklist with
1914 // the reachable instructions. Ignore blocks that are not reachable. Keep
1915 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +00001916 SmallPtrSet<BasicBlock*, 64> Visited;
Chad Rosier00737bd2011-12-01 21:29:16 +00001917 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
1918 TLI);
Jeff Cohen00b168892005-07-27 06:12:32 +00001919
Chris Lattnerb3d59702005-07-07 20:40:38 +00001920 // Do a quick scan over the function. If we find any blocks that are
1921 // unreachable, remove any instructions inside of them. This prevents
1922 // the instcombine code from having to deal with some bad special cases.
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001923 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1924 if (Visited.count(BB)) continue;
1925
Bill Wendlinga2684682011-09-04 09:43:36 +00001926 // Delete the instructions backwards, as it has a reduced likelihood of
1927 // having to update as many def-use and use-def chains.
1928 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1929 while (EndInst != BB->begin()) {
1930 // Delete the next to last instruction.
1931 BasicBlock::iterator I = EndInst;
1932 Instruction *Inst = --I;
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001933 if (!Inst->use_empty())
1934 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Bill Wendlinga2684682011-09-04 09:43:36 +00001935 if (isa<LandingPadInst>(Inst)) {
1936 EndInst = Inst;
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001937 continue;
Bill Wendlinga2684682011-09-04 09:43:36 +00001938 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001939 if (!isa<DbgInfoIntrinsic>(Inst)) {
1940 ++NumDeadInst;
1941 MadeIRChange = true;
Chris Lattnerb3d59702005-07-07 20:40:38 +00001942 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001943 Inst->eraseFromParent();
Chris Lattnerb3d59702005-07-07 20:40:38 +00001944 }
Bill Wendling6bb4e7e2011-09-01 21:29:49 +00001945 }
Chris Lattnerb3d59702005-07-07 20:40:38 +00001946 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00001947
Chris Lattner873ff012009-08-30 05:55:36 +00001948 while (!Worklist.isEmpty()) {
1949 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +00001950 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +00001951
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001952 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00001953 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001954 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +00001955 EraseInstFromFunction(*I);
1956 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +00001957 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +00001958 continue;
1959 }
Chris Lattner62b14df2002-09-02 04:59:56 +00001960
Chris Lattner8c8c66a2006-05-11 17:11:52 +00001961 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001962 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chad Rosier00737bd2011-12-01 21:29:16 +00001963 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001964 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +00001965
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00001966 // Add operands to the worklist.
1967 ReplaceInstUsesWith(*I, C);
1968 ++NumConstProp;
1969 EraseInstFromFunction(*I);
1970 MadeIRChange = true;
1971 continue;
1972 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00001973
Chris Lattnerea1c4542004-12-08 23:43:58 +00001974 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +00001975 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +00001976 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +00001977 Instruction *UserInst = cast<Instruction>(I->use_back());
1978 BasicBlock *UserParent;
Jakub Staszak58c1da82012-05-06 13:52:31 +00001979
Chris Lattner8db2cd12009-10-14 15:21:58 +00001980 // Get the block the use occurs in.
1981 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1982 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1983 else
1984 UserParent = UserInst->getParent();
Jakub Staszak58c1da82012-05-06 13:52:31 +00001985
Chris Lattnerea1c4542004-12-08 23:43:58 +00001986 if (UserParent != BB) {
1987 bool UserIsSuccessor = false;
1988 // See if the user is one of our successors.
1989 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1990 if (*SI == UserParent) {
1991 UserIsSuccessor = true;
1992 break;
1993 }
1994
1995 // If the user is one of our immediate successors, and if that successor
1996 // only has us as a predecessors (we'd have to split the critical edge
1997 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +00001998 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +00001999 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002000 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +00002001 }
2002 }
2003
Chris Lattner74381062009-08-30 07:44:24 +00002004 // Now that we have an instruction, try combining it to simplify it.
2005 Builder->SetInsertPoint(I->getParent(), I);
Eli Friedmanef819d02011-05-18 01:28:27 +00002006 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszak58c1da82012-05-06 13:52:31 +00002007
Reid Spencera9b81012007-03-26 17:44:01 +00002008#ifndef NDEBUG
2009 std::string OrigI;
2010#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +00002011 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +00002012 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2013
Chris Lattner90ac28c2002-08-02 19:29:35 +00002014 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00002015 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002016 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002017 if (Result != I) {
Jim Grosbache2999b42011-10-05 20:44:29 +00002018 DEBUG(errs() << "IC: Old = " << *I << '\n'
2019 << " New = " << *Result << '\n');
2020
Eli Friedmana311c342011-05-27 00:19:40 +00002021 if (!I->getDebugLoc().isUnknown())
2022 Result->setDebugLoc(I->getDebugLoc());
Chris Lattnerf523d062004-06-09 05:08:07 +00002023 // Everything uses the new instruction now.
2024 I->replaceAllUsesWith(Result);
2025
Jim Grosbach35d9da32011-10-05 20:53:43 +00002026 // Move the name to the new instruction first.
2027 Result->takeName(I);
2028
Jim Grosbache2999b42011-10-05 20:44:29 +00002029 // Push the new instruction and any users onto the worklist.
2030 Worklist.Add(Result);
2031 Worklist.AddUsersToWorkList(*Result);
2032
Chris Lattner4bb7c022003-10-06 17:11:01 +00002033 // Insert the new instruction into the basic block...
2034 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00002035 BasicBlock::iterator InsertPos = I;
2036
Eli Friedman049260d2011-11-01 04:49:29 +00002037 // If we replace a PHI with something that isn't a PHI, fix up the
2038 // insertion point.
2039 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2040 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattnerbac32862004-11-14 19:13:23 +00002041
2042 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00002043
Chris Lattner7a1e9242009-08-30 06:13:40 +00002044 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +00002045 } else {
Evan Chengc7baf682007-03-27 16:44:48 +00002046#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +00002047 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2048 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +00002049#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +00002050
Chris Lattner90ac28c2002-08-02 19:29:35 +00002051 // If the instruction was modified, it's possible that it is now dead.
2052 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00002053 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00002054 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +00002055 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +00002056 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +00002057 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +00002058 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00002059 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002060 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002061 }
2062 }
2063
Chris Lattner873ff012009-08-30 05:55:36 +00002064 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +00002065 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002066}
2067
Chris Lattnerec9c3582007-03-03 02:04:50 +00002068
2069bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +00002070 TD = getAnalysisIfAvailable<TargetData>();
Chad Rosier00737bd2011-12-01 21:29:16 +00002071 TLI = &getAnalysis<TargetLibraryInfo>();
Jakub Staszak58c1da82012-05-06 13:52:31 +00002072
Chris Lattner74381062009-08-30 07:44:24 +00002073 /// Builder - This is an IRBuilder that automatically inserts new
2074 /// instructions into the worklist when they are created.
Jakub Staszak58c1da82012-05-06 13:52:31 +00002075 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +00002076 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +00002077 InstCombineIRInserter(Worklist));
2078 Builder = &TheBuilder;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002079
Chris Lattnerec9c3582007-03-03 02:04:50 +00002080 bool EverMadeChange = false;
2081
Devang Patel813c9a02011-03-17 22:18:16 +00002082 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2083 // by instcombiner.
2084 EverMadeChange = LowerDbgDeclare(F);
2085
Chris Lattnerec9c3582007-03-03 02:04:50 +00002086 // Iterate while there is work to do.
2087 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +00002088 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +00002089 EverMadeChange = true;
Jakub Staszak58c1da82012-05-06 13:52:31 +00002090
Chris Lattner74381062009-08-30 07:44:24 +00002091 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +00002092 return EverMadeChange;
2093}
2094
Brian Gaeke96d4bf72004-07-27 17:43:21 +00002095FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002096 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00002097}