blob: c872e0809506c2b057c31175289862b988c1f4c6 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohmand78c4002008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner07418422007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattner07418422007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-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 Lattnerdeaa0dd2003-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 Spencer266e42b2006-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 Lattnerede3fe02003-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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chandler Carruth83ba2692015-01-24 04:19:17 +000036#include "llvm/Transforms/InstCombine/InstCombine.h"
Chandler Carrutha9174582015-01-22 05:25:13 +000037#include "InstCombineInternal.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm-c/Initialization.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Statistic.h"
41#include "llvm/ADT/StringSwitch.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000042#include "llvm/Analysis/AssumptionCache.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000043#include "llvm/Analysis/CFG.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
David Majnemer70497c62015-12-02 23:06:39 +000045#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000046#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattnerc1f19072009-11-09 23:28:39 +000047#include "llvm/Analysis/InstructionSimplify.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000048#include "llvm/Analysis/LoopInfo.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000049#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000050#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjay Patel58814442014-07-09 16:34:54 +000051#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000052#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000055#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000057#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000058#include "llvm/IR/ValueHandle.h"
Meador Inge193e0352012-11-13 04:16:17 +000059#include "llvm/Support/CommandLine.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000060#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000061#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000062#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/Transforms/Utils/Local.h"
Chris Lattner053c0932002-05-14 15:24:07 +000064#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000065#include <climits>
Chris Lattner8427bff2003-12-07 01:24:23 +000066using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000067using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000068
Chandler Carruth964daaa2014-04-22 02:55:47 +000069#define DEBUG_TYPE "instcombine"
70
Chris Lattner79a42ac2006-12-19 21:40:18 +000071STATISTIC(NumCombined , "Number of insts combined");
72STATISTIC(NumConstProp, "Number of constant folds");
73STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000074STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsfbb9ac32010-12-22 13:36:08 +000075STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000076STATISTIC(NumFactor , "Number of factorizations");
77STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000078
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000079Value *InstCombiner::EmitGEPOffset(User *GEP) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000080 return llvm::EmitGEPOffset(Builder, DL, GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000081}
82
Sanjay Patel55dcd402015-09-21 16:09:37 +000083/// Return true if it is desirable to convert an integer computation from a
84/// given bit width to a new bit width.
Sanjay Patel84dca492015-09-21 15:33:26 +000085/// We don't want to convert from a legal to an illegal type for example or from
86/// a smaller to a larger illegal type.
Sanjay Patel55dcd402015-09-21 16:09:37 +000087bool InstCombiner::ShouldChangeType(unsigned FromWidth,
88 unsigned ToWidth) const {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000089 bool FromLegal = DL.isLegalInteger(FromWidth);
90 bool ToLegal = DL.isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +000091
Chris Lattner1559bed2009-11-10 07:23:37 +000092 // If this is a legal integer from type, and the result would be an illegal
93 // type, don't do the transformation.
94 if (FromLegal && !ToLegal)
95 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +000096
Chris Lattner1559bed2009-11-10 07:23:37 +000097 // Otherwise, if both are illegal, do not increase the size of the result. We
98 // do allow things like i160 -> i64, but not i64 -> i160.
99 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
100 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000101
Chris Lattner1559bed2009-11-10 07:23:37 +0000102 return true;
103}
104
Sanjay Patel55dcd402015-09-21 16:09:37 +0000105/// Return true if it is desirable to convert a computation from 'From' to 'To'.
106/// We don't want to convert from a legal to an illegal type for example or from
107/// a smaller to a larger illegal type.
108bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
109 assert(From->isIntegerTy() && To->isIntegerTy());
110
111 unsigned FromWidth = From->getPrimitiveSizeInBits();
112 unsigned ToWidth = To->getPrimitiveSizeInBits();
113 return ShouldChangeType(FromWidth, ToWidth);
114}
115
Nick Lewyckyde492782011-08-14 01:45:19 +0000116// Return true, if No Signed Wrap should be maintained for I.
117// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
118// where both B and C should be ConstantInts, results in a constant that does
119// not overflow. This function only handles the Add and Sub opcodes. For
120// all other opcodes, the function conservatively returns false.
121static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
122 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
123 if (!OBO || !OBO->hasNoSignedWrap()) {
124 return false;
125 }
126
127 // We reason about Add and Sub Only.
128 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000129 if (Opcode != Instruction::Add &&
Nick Lewyckyde492782011-08-14 01:45:19 +0000130 Opcode != Instruction::Sub) {
131 return false;
132 }
133
134 ConstantInt *CB = dyn_cast<ConstantInt>(B);
135 ConstantInt *CC = dyn_cast<ConstantInt>(C);
136
137 if (!CB || !CC) {
138 return false;
139 }
140
141 const APInt &BVal = CB->getValue();
142 const APInt &CVal = CC->getValue();
143 bool Overflow = false;
144
145 if (Opcode == Instruction::Add) {
146 BVal.sadd_ov(CVal, Overflow);
147 } else {
148 BVal.ssub_ov(CVal, Overflow);
149 }
150
151 return !Overflow;
152}
153
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000154/// Conservatively clears subclassOptionalData after a reassociation or
155/// commutation. We preserve fast-math flags when applicable as they can be
156/// preserved.
157static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
158 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
159 if (!FPMO) {
160 I.clearSubclassOptionalData();
161 return;
162 }
163
164 FastMathFlags FMF = I.getFastMathFlags();
165 I.clearSubclassOptionalData();
166 I.setFastMathFlags(FMF);
167}
168
Sanjay Patel84dca492015-09-21 15:33:26 +0000169/// This performs a few simplifications for operators that are associative or
170/// commutative:
171///
172/// Commutative operators:
173///
174/// 1. Order operands such that they are listed from right (least complex) to
175/// left (most complex). This puts constants before unary operators before
176/// binary operators.
177///
178/// Associative operators:
179///
180/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
181/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
182///
183/// Associative and commutative operators:
184///
185/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
186/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
187/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
188/// if C1 and C2 are constants.
Duncan Sands641baf12010-11-13 15:10:37 +0000189bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000190 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000191 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000192
Duncan Sands641baf12010-11-13 15:10:37 +0000193 do {
194 // Order operands such that they are listed from right (least complex) to
195 // left (most complex). This puts constants before unary operators before
196 // binary operators.
197 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
198 getComplexity(I.getOperand(1)))
199 Changed = !I.swapOperands();
200
201 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
202 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
203
204 if (I.isAssociative()) {
205 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
206 if (Op0 && Op0->getOpcode() == Opcode) {
207 Value *A = Op0->getOperand(0);
208 Value *B = Op0->getOperand(1);
209 Value *C = I.getOperand(1);
210
211 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000212 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000213 // It simplifies to V. Form "A op V".
214 I.setOperand(0, A);
215 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000216 // Conservatively clear the optional flags, since they may not be
217 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000218 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000219 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000220 // Note: this is only valid because SimplifyBinOp doesn't look at
221 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000222 I.clearSubclassOptionalData();
223 I.setHasNoSignedWrap(true);
224 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000225 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000226 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000227
Duncan Sands641baf12010-11-13 15:10:37 +0000228 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000229 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000230 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000231 }
Duncan Sands641baf12010-11-13 15:10:37 +0000232 }
233
234 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
235 if (Op1 && Op1->getOpcode() == Opcode) {
236 Value *A = I.getOperand(0);
237 Value *B = Op1->getOperand(0);
238 Value *C = Op1->getOperand(1);
239
240 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000241 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000242 // It simplifies to V. Form "V op C".
243 I.setOperand(0, V);
244 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000245 // Conservatively clear the optional flags, since they may not be
246 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000247 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000248 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000249 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000250 continue;
251 }
252 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000253 }
Duncan Sands641baf12010-11-13 15:10:37 +0000254
255 if (I.isAssociative() && I.isCommutative()) {
256 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
257 if (Op0 && Op0->getOpcode() == Opcode) {
258 Value *A = Op0->getOperand(0);
259 Value *B = Op0->getOperand(1);
260 Value *C = I.getOperand(1);
261
262 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000263 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000264 // It simplifies to V. Form "V op B".
265 I.setOperand(0, V);
266 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000267 // Conservatively clear the optional flags, since they may not be
268 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000269 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000270 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000271 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000272 continue;
273 }
274 }
275
276 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
277 if (Op1 && Op1->getOpcode() == Opcode) {
278 Value *A = I.getOperand(0);
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
281
282 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000283 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000284 // It simplifies to V. Form "B op V".
285 I.setOperand(0, B);
286 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000287 // Conservatively clear the optional flags, since they may not be
288 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000289 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000290 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000291 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000292 continue;
293 }
294 }
295
296 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
297 // if C1 and C2 are constants.
298 if (Op0 && Op1 &&
299 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
300 isa<Constant>(Op0->getOperand(1)) &&
301 isa<Constant>(Op1->getOperand(1)) &&
302 Op0->hasOneUse() && Op1->hasOneUse()) {
303 Value *A = Op0->getOperand(0);
304 Constant *C1 = cast<Constant>(Op0->getOperand(1));
305 Value *B = Op1->getOperand(0);
306 Constant *C2 = cast<Constant>(Op1->getOperand(1));
307
308 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000309 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000310 if (isa<FPMathOperator>(New)) {
311 FastMathFlags Flags = I.getFastMathFlags();
312 Flags &= Op0->getFastMathFlags();
313 Flags &= Op1->getFastMathFlags();
314 New->setFastMathFlags(Flags);
315 }
Eli Friedman35211c62011-05-27 00:19:40 +0000316 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000317 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000318 I.setOperand(0, New);
319 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000320 // Conservatively clear the optional flags, since they may not be
321 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000322 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000323
Duncan Sands641baf12010-11-13 15:10:37 +0000324 Changed = true;
325 continue;
326 }
327 }
328
329 // No further simplifications.
330 return Changed;
331 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000332}
Chris Lattnerca081252001-12-14 16:52:21 +0000333
Sanjay Patel84dca492015-09-21 15:33:26 +0000334/// Return whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000335/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000336static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
337 Instruction::BinaryOps ROp) {
338 switch (LOp) {
339 default:
340 return false;
341
342 case Instruction::And:
343 // And distributes over Or and Xor.
344 switch (ROp) {
345 default:
346 return false;
347 case Instruction::Or:
348 case Instruction::Xor:
349 return true;
350 }
351
352 case Instruction::Mul:
353 // Multiplication distributes over addition and subtraction.
354 switch (ROp) {
355 default:
356 return false;
357 case Instruction::Add:
358 case Instruction::Sub:
359 return true;
360 }
361
362 case Instruction::Or:
363 // Or distributes over And.
364 switch (ROp) {
365 default:
366 return false;
367 case Instruction::And:
368 return true;
369 }
370 }
371}
372
Sanjay Patel84dca492015-09-21 15:33:26 +0000373/// Return whether "(X LOp Y) ROp Z" is always equal to
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000374/// "(X ROp Z) LOp (Y ROp Z)".
375static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
376 Instruction::BinaryOps ROp) {
377 if (Instruction::isCommutative(ROp))
378 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000379
380 switch (LOp) {
381 default:
382 return false;
383 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
384 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
385 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
386 case Instruction::And:
387 case Instruction::Or:
388 case Instruction::Xor:
389 switch (ROp) {
390 default:
391 return false;
392 case Instruction::Shl:
393 case Instruction::LShr:
394 case Instruction::AShr:
395 return true;
396 }
397 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000398 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
399 // but this requires knowing that the addition does not overflow and other
400 // such subtleties.
401 return false;
402}
403
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000404/// This function returns identity value for given opcode, which can be used to
405/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
406static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
407 if (isa<Constant>(V))
408 return nullptr;
409
410 if (OpCode == Instruction::Mul)
411 return ConstantInt::get(V->getType(), 1);
412
413 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
414
415 return nullptr;
416}
417
418/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000419/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
420/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
421/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
422/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
423/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000424static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000425getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
426 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000427 if (!Op)
428 return Instruction::BinaryOpsEnd;
429
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000430 LHS = Op->getOperand(0);
431 RHS = Op->getOperand(1);
432
433 switch (TopLevelOpcode) {
434 default:
435 return Op->getOpcode();
436
437 case Instruction::Add:
438 case Instruction::Sub:
439 if (Op->getOpcode() == Instruction::Shl) {
440 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
441 // The multiplier is really 1 << CST.
442 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
443 return Instruction::Mul;
444 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000445 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000446 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000447 }
448
449 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000450}
451
452/// This tries to simplify binary operations by factorizing out common terms
453/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
454static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000456 Instruction::BinaryOps InnerOpcode, Value *A,
457 Value *B, Value *C, Value *D) {
458
459 // If any of A, B, C, D are null, we can not factor I, return early.
460 // Checking A and C should be enough.
461 if (!A || !C || !B || !D)
462 return nullptr;
463
David Majnemer4c3753c2015-05-22 23:02:11 +0000464 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000465 Value *SimplifiedInst = nullptr;
466 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
467 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
468
469 // Does "X op' Y" always equal "Y op' X"?
470 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
471
472 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
473 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
474 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
475 // commutative case, "(A op' B) op (C op' A)"?
476 if (A == C || (InnerCommutative && A == D)) {
477 if (A != C)
478 std::swap(C, D);
479 // Consider forming "A op' (B op D)".
480 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000481 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000482 // If "B op D" doesn't simplify then only go on if both of the existing
483 // operations "A op' B" and "C op' D" will be zapped as no longer used.
484 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
485 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
486 if (V) {
487 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
488 }
489 }
490
491 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
492 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
493 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
494 // commutative case, "(A op' B) op (B op' D)"?
495 if (B == D || (InnerCommutative && B == C)) {
496 if (B != D)
497 std::swap(C, D);
498 // Consider forming "(A op C) op' B".
499 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000500 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000501
502 // If "A op C" doesn't simplify then only go on if both of the existing
503 // operations "A op' B" and "C op' D" will be zapped as no longer used.
504 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
505 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
506 if (V) {
507 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
508 }
509 }
510
511 if (SimplifiedInst) {
512 ++NumFactor;
513 SimplifiedInst->takeName(&I);
514
515 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
516 // TODO: Check for NUW.
517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
518 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
519 bool HasNSW = false;
520 if (isa<OverflowingBinaryOperator>(&I))
521 HasNSW = I.hasNoSignedWrap();
522
523 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
524 if (isa<OverflowingBinaryOperator>(Op0))
525 HasNSW &= Op0->hasNoSignedWrap();
526
527 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
528 if (isa<OverflowingBinaryOperator>(Op1))
529 HasNSW &= Op1->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000530
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000531 // We can propagate 'nsw' if we know that
David Majnemer4c3753c2015-05-22 23:02:11 +0000532 // %Y = mul nsw i16 %X, C
533 // %Z = add nsw i16 %Y, %X
534 // =>
535 // %Z = mul nsw i16 %X, C+1
536 //
537 // iff C+1 isn't INT_MIN
538 const APInt *CInt;
539 if (TopLevelOpcode == Instruction::Add &&
540 InnerOpcode == Instruction::Mul)
541 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
542 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000543 }
544 }
545 }
546 return SimplifiedInst;
547}
548
Sanjay Patel84dca492015-09-21 15:33:26 +0000549/// This tries to simplify binary operations which some other binary operation
550/// distributes over either by factorizing out common terms
551/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
552/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
553/// Returns the simplified value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000554Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
555 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
556 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
557 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000558
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000559 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000560 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000561 auto TopLevelOpcode = I.getOpcode();
562 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
563 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000564
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000565 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
566 // a common term.
567 if (LHSOpcode == RHSOpcode) {
568 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
569 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000570 }
571
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000572 // The instruction has the form "(A op' B) op (C)". Try to factorize common
573 // term.
574 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
575 getIdentityValue(LHSOpcode, RHS)))
576 return V;
577
578 // The instruction has the form "(B) op (C op' D)". Try to factorize common
579 // term.
580 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
581 getIdentityValue(RHSOpcode, LHS), C, D))
582 return V;
583
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000584 // Expansion.
585 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
586 // The instruction has the form "(A op' B) op C". See if expanding it out
587 // to "(A op C) op' (B op C)" results in simplifications.
588 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
589 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
590
591 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000592 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
593 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000594 // They do! Return "L op' R".
595 ++NumExpand;
596 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
597 if ((L == A && R == B) ||
598 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
599 return Op0;
600 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000601 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000602 return V;
603 // Otherwise, create a new instruction.
604 C = Builder->CreateBinOp(InnerOpcode, L, R);
605 C->takeName(&I);
606 return C;
607 }
608 }
609
610 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
611 // The instruction has the form "A op (B op' C)". See if expanding it out
612 // to "(A op B) op' (A op C)" results in simplifications.
613 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
614 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
615
616 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000617 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
618 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000619 // They do! Return "L op' R".
620 ++NumExpand;
621 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
622 if ((L == B && R == C) ||
623 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
624 return Op1;
625 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000626 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000627 return V;
628 // Otherwise, create a new instruction.
629 A = Builder->CreateBinOp(InnerOpcode, L, R);
630 A->takeName(&I);
631 return A;
632 }
633 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000634
David Majnemer33b6f822015-07-14 22:39:23 +0000635 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
636 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
637 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
638 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
639 if (SI0->getCondition() == SI1->getCondition()) {
640 Value *SI = nullptr;
641 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
642 SI1->getFalseValue(), DL, TLI, DT, AC))
643 SI = Builder->CreateSelect(SI0->getCondition(),
644 Builder->CreateBinOp(TopLevelOpcode,
645 SI0->getTrueValue(),
646 SI1->getTrueValue()),
647 V);
648 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
649 SI1->getTrueValue(), DL, TLI, DT, AC))
650 SI = Builder->CreateSelect(
651 SI0->getCondition(), V,
652 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
653 SI1->getFalseValue()));
654 if (SI) {
655 SI->takeName(&I);
656 return SI;
657 }
658 }
659 }
660 }
661
Craig Topperf40110f2014-04-25 05:29:35 +0000662 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000663}
664
Sanjay Patel84dca492015-09-21 15:33:26 +0000665/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
666/// constant zero (which is the 'negate' form).
Chris Lattner2188e402010-01-04 07:37:31 +0000667Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000668 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000669 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000670
Chris Lattner9ad0d552004-12-14 20:08:06 +0000671 // Constants can be considered to be negated values if they can be folded.
672 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000673 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000674
Chris Lattner8213c8a2012-02-06 21:56:39 +0000675 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
676 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000677 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000678
Craig Topperf40110f2014-04-25 05:29:35 +0000679 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000680}
681
Sanjay Patel84dca492015-09-21 15:33:26 +0000682/// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
683/// a constant negative zero (which is the 'negate' form).
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000684Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
685 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000686 return BinaryOperator::getFNegArgument(V);
687
688 // Constants can be considered to be negated values if they can be folded.
689 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000690 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000691
Chris Lattner8213c8a2012-02-06 21:56:39 +0000692 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
693 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000694 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000695
Craig Topperf40110f2014-04-25 05:29:35 +0000696 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000697}
698
Chris Lattner86102b82005-01-01 16:22:27 +0000699static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000700 InstCombiner *IC) {
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000701 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattnerc8565392009-08-30 20:01:10 +0000702 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000703 }
Chris Lattner86102b82005-01-01 16:22:27 +0000704
Chris Lattner183b3362004-04-09 19:05:30 +0000705 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000706 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
707 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000708
Chris Lattner183b3362004-04-09 19:05:30 +0000709 if (Constant *SOC = dyn_cast<Constant>(SO)) {
710 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000711 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
712 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000713 }
714
715 Value *Op0 = SO, *Op1 = ConstOperand;
716 if (!ConstIsRHS)
717 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000718
Owen Anderson1664dc82014-01-20 07:44:53 +0000719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
720 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
Chris Lattner022a5822009-08-30 07:44:24 +0000721 SO->getName()+".op");
Owen Anderson1664dc82014-01-20 07:44:53 +0000722 Instruction *FPInst = dyn_cast<Instruction>(RI);
723 if (FPInst && isa<FPMathOperator>(FPInst))
724 FPInst->copyFastMathFlags(BO);
725 return RI;
726 }
Chris Lattner022a5822009-08-30 07:44:24 +0000727 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
728 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
729 SO->getName()+".cmp");
730 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
731 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
732 SO->getName()+".cmp");
733 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner86102b82005-01-01 16:22:27 +0000734}
735
Sanjay Patel84dca492015-09-21 15:33:26 +0000736/// Given an instruction with a select as one operand and a constant as the
737/// other operand, try to fold the binary operator into the select arguments.
738/// This also works for Cast instructions, which obviously do not have a second
739/// operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000740Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner86102b82005-01-01 16:22:27 +0000741 // Don't modify shared select instructions
Craig Topperf40110f2014-04-25 05:29:35 +0000742 if (!SI->hasOneUse()) return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000743 Value *TV = SI->getOperand(1);
744 Value *FV = SI->getOperand(2);
745
746 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000747 // Bool selects with constant operands can be folded to logical ops.
Craig Topperf40110f2014-04-25 05:29:35 +0000748 if (SI->getType()->isIntegerTy(1)) return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000749
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000750 // If it's a bitcast involving vectors, make sure it has the same number of
751 // elements on both sides.
752 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000753 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
754 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000755
756 // Verify that either both or neither are vectors.
Craig Topperf40110f2014-04-25 05:29:35 +0000757 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000758 // If vectors, verify that they have the same number of elements.
759 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +0000760 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000761 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000762
James Molloy2b21a7c2015-05-20 18:41:25 +0000763 // Test if a CmpInst instruction is used exclusively by a select as
764 // part of a minimum or maximum operation. If so, refrain from doing
765 // any other folding. This helps out other analyses which understand
766 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
767 // and CodeGen. And in this case, at least one of the comparison
768 // operands has at least one user besides the compare (the select),
769 // which would often largely negate the benefit of folding anyway.
770 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
771 if (CI->hasOneUse()) {
772 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
773 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
774 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
775 return nullptr;
776 }
777 }
778
Chris Lattner2b295a02010-01-04 07:53:58 +0000779 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
780 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner86102b82005-01-01 16:22:27 +0000781
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000782 return SelectInst::Create(SI->getCondition(),
783 SelectTrueVal, SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +0000784 }
Craig Topperf40110f2014-04-25 05:29:35 +0000785 return nullptr;
Chris Lattner183b3362004-04-09 19:05:30 +0000786}
787
Sanjay Patel84dca492015-09-21 15:33:26 +0000788/// Given a binary operator, cast instruction, or select which has a PHI node as
789/// operand #0, see if we can fold the instruction into the PHI (which is only
790/// possible if all operands to the PHI are constants).
Chris Lattnerea7131a2011-01-16 05:14:26 +0000791Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000792 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000793 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000794 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000795 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000796
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000797 // We normally only transform phis with a single use. However, if a PHI has
798 // multiple uses and they are all the same operation, we can fold *all* of the
799 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000800 if (!PN->hasOneUse()) {
801 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000802 for (User *U : PN->users()) {
803 Instruction *UI = cast<Instruction>(U);
804 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000805 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000806 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000807 // Otherwise, we can replace *all* users with the new PHI we form.
808 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000809
Chris Lattnerfacb8672009-09-27 19:57:57 +0000810 // Check to see if all of the operands of the PHI are simple constants
811 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000812 // remember the BB it is in. If there is more than one or if *it* is a PHI,
813 // bail out. We don't do arbitrary constant expressions here because moving
814 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000815 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000816 for (unsigned i = 0; i != NumPHIValues; ++i) {
817 Value *InVal = PN->getIncomingValue(i);
818 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
819 continue;
820
Craig Topperf40110f2014-04-25 05:29:35 +0000821 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
822 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000823
Chris Lattner25ce2802011-01-16 04:37:29 +0000824 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000825
826 // If the InVal is an invoke at the end of the pred block, then we can't
827 // insert a computation after it without breaking the edge.
828 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
829 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000830 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000831
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000832 // If the incoming non-constant value is in I's block, we will remove one
833 // instruction, but insert another equivalent one, leading to infinite
834 // instcombine.
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000835 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000836 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000837 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000838
Chris Lattner04689872006-09-09 22:02:56 +0000839 // If there is exactly one non-constant value, we can insert a copy of the
840 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000841 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000842 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000844 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000845 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000846 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000847
848 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000849 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000850 InsertNewInstBefore(NewPN, *PN);
851 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000852
Chris Lattnerff2e7372011-01-16 05:08:00 +0000853 // If we are going to have to insert a new computation, do so right before the
Sanjay Patel41c739b2015-09-11 19:29:18 +0000854 // predecessor's terminator.
Chris Lattnerff2e7372011-01-16 05:08:00 +0000855 if (NonConstBB)
856 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000857
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000858 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000859 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
860 // We only currently try to fold the condition of a select when it is a phi,
861 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000862 Value *TrueV = SI->getTrueValue();
863 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000864 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000865 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000866 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000867 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
868 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000869 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000870 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
871 // even if currently isNullValue gives false.
872 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
873 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000874 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000875 else
876 InV = Builder->CreateSelect(PN->getIncomingValue(i),
877 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000878 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000879 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000880 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
881 Constant *C = cast<Constant>(I.getOperand(1));
882 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000883 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000884 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
885 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
886 else if (isa<ICmpInst>(CI))
887 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
888 C, "phitmp");
889 else
890 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
891 C, "phitmp");
892 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
893 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000894 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000895 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000896 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000897 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000898 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
899 InV = ConstantExpr::get(I.getOpcode(), InC, C);
900 else
901 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
902 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000903 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000904 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000905 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000907 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000908 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000909 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000910 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000911 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000912 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000913 InV = Builder->CreateCast(CI->getOpcode(),
914 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000915 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000916 }
917 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000918
Chandler Carruthcdf47882014-03-09 03:16:01 +0000919 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000920 Instruction *User = cast<Instruction>(*UI++);
921 if (User == &I) continue;
922 ReplaceInstUsesWith(*User, NewPN);
923 EraseInstFromFunction(*User);
924 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000925 return ReplaceInstUsesWith(I, NewPN);
926}
927
Sanjay Patel84dca492015-09-21 15:33:26 +0000928/// Given a pointer type and a constant offset, determine whether or not there
929/// is a sequence of GEP indices into the pointed type that will land us at the
930/// specified offset. If so, fill them into NewIndices and return the resultant
931/// element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000932Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000933 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000934 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000935 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000936 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000937
Chris Lattnerfef138b2009-01-09 05:44:56 +0000938 // Start with the index over the outer type. Note that the type size
939 // might be zero (even if the offset isn't zero) if the indexed type
940 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000941 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000942 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000943 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000944 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000945 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000946
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000947 // Handle hosts where % returns negative instead of values [0..TySize).
948 if (Offset < 0) {
949 --FirstIdx;
950 Offset += TySize;
951 assert(Offset >= 0);
952 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000953 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
954 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000955
Owen Andersonedb4a702009-07-24 23:12:02 +0000956 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000957
Chris Lattnerfef138b2009-01-09 05:44:56 +0000958 // Index into the types. If we fail, set OrigBase to null.
959 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000960 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000961 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +0000962 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000963
Chris Lattner229907c2011-07-18 04:54:35 +0000964 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +0000966 assert(Offset < (int64_t)SL->getSizeInBytes() &&
967 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000968
Chris Lattnerfef138b2009-01-09 05:44:56 +0000969 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +0000970 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
971 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000972
Chris Lattnerfef138b2009-01-09 05:44:56 +0000973 Offset -= SL->getElementOffset(Elt);
974 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +0000975 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000976 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +0000977 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +0000978 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +0000979 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +0000980 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +0000981 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +0000982 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +0000983 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000984 }
985 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000986
Chris Lattner72cd68f2009-01-24 01:00:13 +0000987 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000988}
989
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +0000990static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
991 // If this GEP has only 0 indices, it is the same pointer as
992 // Src. If Src is not a trivial GEP too, don't combine
993 // the indices.
994 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
995 !Src.hasOneUse())
996 return false;
997 return true;
998}
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000999
Sanjay Patel84dca492015-09-21 15:33:26 +00001000/// Return a value X such that Val = X * Scale, or null if none.
1001/// If the multiplication is known not to overflow, then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001002Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1003 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1004 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1005 Scale.getBitWidth() && "Scale not compatible with value!");
1006
1007 // If Val is zero or Scale is one then Val = Val * Scale.
1008 if (match(Val, m_Zero()) || Scale == 1) {
1009 NoSignedWrap = true;
1010 return Val;
1011 }
1012
1013 // If Scale is zero then it does not divide Val.
1014 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001015 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001016
1017 // Look through chains of multiplications, searching for a constant that is
1018 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1019 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1020 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1021 // down from Val:
1022 //
1023 // Val = M1 * X || Analysis starts here and works down
1024 // M1 = M2 * Y || Doesn't descend into terms with more
1025 // M2 = Z * 4 \/ than one use
1026 //
1027 // Then to modify a term at the bottom:
1028 //
1029 // Val = M1 * X
1030 // M1 = Z * Y || Replaced M2 with Z
1031 //
1032 // Then to work back up correcting nsw flags.
1033
1034 // Op - the term we are currently analyzing. Starts at Val then drills down.
1035 // Replaced with its descaled value before exiting from the drill down loop.
1036 Value *Op = Val;
1037
1038 // Parent - initially null, but after drilling down notes where Op came from.
1039 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1040 // 0'th operand of Val.
1041 std::pair<Instruction*, unsigned> Parent;
1042
Sanjay Patel84dca492015-09-21 15:33:26 +00001043 // Set if the transform requires a descaling at deeper levels that doesn't
1044 // overflow.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001045 bool RequireNoSignedWrap = false;
1046
Sanjay Patel84dca492015-09-21 15:33:26 +00001047 // Log base 2 of the scale. Negative if not a power of 2.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001048 int32_t logScale = Scale.exactLogBase2();
1049
1050 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1051
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1053 // If Op is a constant divisible by Scale then descale to the quotient.
1054 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1055 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1056 if (!Remainder.isMinValue())
1057 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001058 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001059 // Replace with the quotient in the parent.
1060 Op = ConstantInt::get(CI->getType(), Quotient);
1061 NoSignedWrap = true;
1062 break;
1063 }
1064
1065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1066
1067 if (BO->getOpcode() == Instruction::Mul) {
1068 // Multiplication.
1069 NoSignedWrap = BO->hasNoSignedWrap();
1070 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001071 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001072
1073 // There are three cases for multiplication: multiplication by exactly
1074 // the scale, multiplication by a constant different to the scale, and
1075 // multiplication by something else.
1076 Value *LHS = BO->getOperand(0);
1077 Value *RHS = BO->getOperand(1);
1078
1079 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1080 // Multiplication by a constant.
1081 if (CI->getValue() == Scale) {
1082 // Multiplication by exactly the scale, replace the multiplication
1083 // by its left-hand side in the parent.
1084 Op = LHS;
1085 break;
1086 }
1087
1088 // Otherwise drill down into the constant.
1089 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001090 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001091
1092 Parent = std::make_pair(BO, 1);
1093 continue;
1094 }
1095
1096 // Multiplication by something else. Drill down into the left-hand side
1097 // since that's where the reassociate pass puts the good stuff.
1098 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001099 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001100
1101 Parent = std::make_pair(BO, 0);
1102 continue;
1103 }
1104
1105 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1106 isa<ConstantInt>(BO->getOperand(1))) {
1107 // Multiplication by a power of 2.
1108 NoSignedWrap = BO->hasNoSignedWrap();
1109 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001110 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001111
1112 Value *LHS = BO->getOperand(0);
1113 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1114 getLimitedValue(Scale.getBitWidth());
1115 // Op = LHS << Amt.
1116
1117 if (Amt == logScale) {
1118 // Multiplication by exactly the scale, replace the multiplication
1119 // by its left-hand side in the parent.
1120 Op = LHS;
1121 break;
1122 }
1123 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001124 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001125
1126 // Multiplication by more than the scale. Reduce the multiplying amount
1127 // by the scale in the parent.
1128 Parent = std::make_pair(BO, 1);
1129 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1130 break;
1131 }
1132 }
1133
1134 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001135 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001136
1137 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1138 if (Cast->getOpcode() == Instruction::SExt) {
1139 // Op is sign-extended from a smaller type, descale in the smaller type.
1140 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1141 APInt SmallScale = Scale.trunc(SmallSize);
1142 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1143 // descale Op as (sext Y) * Scale. In order to have
1144 // sext (Y * SmallScale) = (sext Y) * Scale
1145 // some conditions need to hold however: SmallScale must sign-extend to
1146 // Scale and the multiplication Y * SmallScale should not overflow.
1147 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1148 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001149 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001150 assert(SmallScale.exactLogBase2() == logScale);
1151 // Require that Y * SmallScale must not overflow.
1152 RequireNoSignedWrap = true;
1153
1154 // Drill down through the cast.
1155 Parent = std::make_pair(Cast, 0);
1156 Scale = SmallScale;
1157 continue;
1158 }
1159
Duncan Sands5ed39002012-10-23 09:07:02 +00001160 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001161 // Op is truncated from a larger type, descale in the larger type.
1162 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1163 // trunc (Y * sext Scale) = (trunc Y) * Scale
1164 // always holds. However (trunc Y) * Scale may overflow even if
1165 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1166 // from this point up in the expression (see later).
1167 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001168 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001169
1170 // Drill down through the cast.
1171 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1172 Parent = std::make_pair(Cast, 0);
1173 Scale = Scale.sext(LargeSize);
1174 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1175 logScale = -1;
1176 assert(Scale.exactLogBase2() == logScale);
1177 continue;
1178 }
1179 }
1180
1181 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001182 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001183 }
1184
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001185 // If Op is zero then Val = Op * Scale.
1186 if (match(Op, m_Zero())) {
1187 NoSignedWrap = true;
1188 return Op;
1189 }
1190
Duncan Sands533c8ae2012-10-23 08:28:26 +00001191 // We know that we can successfully descale, so from here on we can safely
1192 // modify the IR. Op holds the descaled version of the deepest term in the
1193 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1194 // not to overflow.
1195
1196 if (!Parent.first)
1197 // The expression only had one term.
1198 return Op;
1199
1200 // Rewrite the parent using the descaled version of its operand.
1201 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1202 assert(Op != Parent.first->getOperand(Parent.second) &&
1203 "Descaling was a no-op?");
1204 Parent.first->setOperand(Parent.second, Op);
1205 Worklist.Add(Parent.first);
1206
1207 // Now work back up the expression correcting nsw flags. The logic is based
1208 // on the following observation: if X * Y is known not to overflow as a signed
1209 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1210 // then X * Z will not overflow as a signed multiplication either. As we work
1211 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1212 // current level has strictly smaller absolute value than the original.
1213 Instruction *Ancestor = Parent.first;
1214 do {
1215 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1216 // If the multiplication wasn't nsw then we can't say anything about the
1217 // value of the descaled multiplication, and we have to clear nsw flags
1218 // from this point on up.
1219 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1220 NoSignedWrap &= OpNoSignedWrap;
1221 if (NoSignedWrap != OpNoSignedWrap) {
1222 BO->setHasNoSignedWrap(NoSignedWrap);
1223 Worklist.Add(Ancestor);
1224 }
1225 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1226 // The fact that the descaled input to the trunc has smaller absolute
1227 // value than the original input doesn't tell us anything useful about
1228 // the absolute values of the truncations.
1229 NoSignedWrap = false;
1230 }
1231 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1232 "Failed to keep proper track of nsw flags while drilling down?");
1233
1234 if (Ancestor == Val)
1235 // Got to the top, all done!
1236 return Val;
1237
1238 // Move up one level in the expression.
1239 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001240 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001241 } while (1);
1242}
1243
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001244/// \brief Creates node of binary operation with the same attributes as the
1245/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001246static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1247 InstCombiner::BuilderTy *B) {
Sanjay Patel968e91a2015-11-24 17:51:20 +00001248 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1249 // If LHS and RHS are constant, BO won't be a binary operator.
1250 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1251 NewBO->copyIRFlags(&Inst);
1252 return BO;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001253}
1254
1255/// \brief Makes transformation of binary operation specific for vector types.
1256/// \param Inst Binary operator to transform.
1257/// \return Pointer to node that must replace the original binary operator, or
1258/// null pointer if no transformation was made.
1259Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1260 if (!Inst.getType()->isVectorTy()) return nullptr;
1261
Sanjay Patel58814442014-07-09 16:34:54 +00001262 // It may not be safe to reorder shuffles and things like div, urem, etc.
1263 // because we may trap when executing those ops on unknown vector elements.
1264 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001265 if (!isSafeToSpeculativelyExecute(&Inst))
1266 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001267
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001268 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1269 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1270 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1271 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1272
1273 // If both arguments of binary operation are shuffles, which use the same
1274 // mask and shuffle within a single vector, it is worthwhile to move the
1275 // shuffle after binary operation:
1276 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1277 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1278 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1279 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1280 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1281 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001282 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001283 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001284 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001285 RShuf->getOperand(0), Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001286 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001287 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001288 }
1289 }
1290
1291 // If one argument is a shuffle within one vector, the other is a constant,
1292 // try moving the shuffle after the binary operation.
1293 ShuffleVectorInst *Shuffle = nullptr;
1294 Constant *C1 = nullptr;
1295 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1296 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1297 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1298 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001299 if (Shuffle && C1 &&
1300 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1301 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001302 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1303 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1304 // Find constant C2 that has property:
1305 // shuffle(C2, ShMask) = C1
1306 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1307 // reorder is not possible.
1308 SmallVector<Constant*, 16> C2M(VWidth,
1309 UndefValue::get(C1->getType()->getScalarType()));
1310 bool MayChange = true;
1311 for (unsigned I = 0; I < VWidth; ++I) {
1312 if (ShMask[I] >= 0) {
1313 assert(ShMask[I] < (int)VWidth);
1314 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1315 MayChange = false;
1316 break;
1317 }
1318 C2M[ShMask[I]] = C1->getAggregateElement(I);
1319 }
1320 }
1321 if (MayChange) {
1322 Constant *C2 = ConstantVector::get(C2M);
Sanjay Patel04df5832015-11-21 16:51:19 +00001323 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1324 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
Serge Pavlove6de9e32014-05-14 09:05:09 +00001325 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001326 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001327 UndefValue::get(Inst.getType()), Shuffle->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001328 }
1329 }
1330
1331 return nullptr;
1332}
1333
Chris Lattner113f4f42002-06-25 16:13:24 +00001334Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001335 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1336
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00001337 if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, TLI, DT, AC))
Chris Lattner8574aba2009-11-27 00:29:05 +00001338 return ReplaceInstUsesWith(GEP, V);
1339
Chris Lattner5f667a62004-05-07 22:09:22 +00001340 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001341
Duncan Sandsc133c542010-11-22 16:32:50 +00001342 // Eliminate unneeded casts for indices, and replace indices which displace
1343 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001344 bool MadeChange = false;
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001345 Type *IntPtrTy =
1346 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001347
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001348 gep_type_iterator GTI = gep_type_begin(GEP);
1349 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1350 ++I, ++GTI) {
1351 // Skip indices into struct types.
1352 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1353 if (!SeqTy)
1354 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001355
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001356 // Index type should have the same width as IntPtr
1357 Type *IndexTy = (*I)->getType();
1358 Type *NewIndexType = IndexTy->isVectorTy() ?
1359 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
1360
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001361 // If the element type has zero size then any index over it is equivalent
1362 // to an index of zero, so replace it with zero if it is not zero already.
1363 if (SeqTy->getElementType()->isSized() &&
1364 DL.getTypeAllocSize(SeqTy->getElementType()) == 0)
1365 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001366 *I = Constant::getNullValue(NewIndexType);
Duncan Sandsc133c542010-11-22 16:32:50 +00001367 MadeChange = true;
1368 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001369
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001370 if (IndexTy != NewIndexType) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001371 // If we are using a wider index than needed for this platform, shrink
1372 // it to what we need. If narrower, sign-extend it to what we need.
1373 // This explicit cast can make subsequent optimizations more obvious.
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001374 *I = Builder->CreateIntCast(*I, NewIndexType, true);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001375 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001376 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001377 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001378 if (MadeChange)
1379 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001380
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001381 // Check to see if the inputs to the PHI node are getelementptr instructions.
1382 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1383 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1384 if (!Op1)
1385 return nullptr;
1386
Daniel Jasper5add63f2015-03-19 11:05:08 +00001387 // Don't fold a GEP into itself through a PHI node. This can only happen
1388 // through the back-edge of a loop. Folding a GEP into itself means that
1389 // the value of the previous iteration needs to be stored in the meantime,
1390 // thus requiring an additional register variable to be live, but not
1391 // actually achieving anything (the GEP still needs to be executed once per
1392 // loop iteration).
1393 if (Op1 == &GEP)
1394 return nullptr;
1395
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001396 signed DI = -1;
1397
1398 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1399 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1400 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1401 return nullptr;
1402
Daniel Jasper5add63f2015-03-19 11:05:08 +00001403 // As for Op1 above, don't try to fold a GEP into itself.
1404 if (Op2 == &GEP)
1405 return nullptr;
1406
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001407 // Keep track of the type as we walk the GEP.
1408 Type *CurTy = Op1->getOperand(0)->getType()->getScalarType();
1409
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001410 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1411 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1412 return nullptr;
1413
1414 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1415 if (DI == -1) {
1416 // We have not seen any differences yet in the GEPs feeding the
1417 // PHI yet, so we record this one if it is allowed to be a
1418 // variable.
1419
1420 // The first two arguments can vary for any GEP, the rest have to be
1421 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001422 if (J > 1 && CurTy->isStructTy())
1423 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001424
1425 DI = J;
1426 } else {
1427 // The GEP is different by more than one input. While this could be
1428 // extended to support GEPs that vary by more than one variable it
1429 // doesn't make sense since it greatly increases the complexity and
1430 // would result in an R+R+R addressing mode which no backend
1431 // directly supports and would need to be broken into several
1432 // simpler instructions anyway.
1433 return nullptr;
1434 }
1435 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001436
1437 // Sink down a layer of the type for the next iteration.
1438 if (J > 0) {
1439 if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
1440 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1441 } else {
1442 CurTy = nullptr;
1443 }
1444 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001445 }
1446 }
1447
Silviu Barangab892e352015-10-26 10:25:05 +00001448 // If not all GEPs are identical we'll have to create a new PHI node.
1449 // Check that the old PHI node has only one use so that it will get
1450 // removed.
1451 if (DI != -1 && !PN->hasOneUse())
1452 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001453
Silviu Barangab892e352015-10-26 10:25:05 +00001454 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001455 if (DI == -1) {
1456 // All the GEPs feeding the PHI are identical. Clone one down into our
1457 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001458 GEP.getParent()->getInstList().insert(
1459 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001460 } else {
1461 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1462 // into the current block so it can be merged, and create a new PHI to
1463 // set that index.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001464 PHINode *NewPN;
1465 {
1466 IRBuilderBase::InsertPointGuard Guard(*Builder);
1467 Builder->SetInsertPoint(PN);
1468 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1469 PN->getNumOperands());
1470 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001471
1472 for (auto &I : PN->operands())
1473 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1474 PN->getIncomingBlock(I));
1475
1476 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001477 GEP.getParent()->getInstList().insert(
1478 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001479 NewGEP->setOperand(DI, NewPN);
1480 }
1481
1482 GEP.setOperand(0, NewGEP);
1483 PtrOp = NewGEP;
1484 }
1485
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001486 // Combine Indices - If the source pointer to this getelementptr instruction
1487 // is a getelementptr instruction, combine the indices of the two
1488 // getelementptr instructions into a single instruction.
1489 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001490 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001491 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001492 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001493
Duncan Sands533c8ae2012-10-23 08:28:26 +00001494 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001495 // chain to be resolved before we perform this transformation. This
1496 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001497 if (GEPOperator *SrcGEP =
1498 dyn_cast<GEPOperator>(Src->getOperand(0)))
1499 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001500 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001501
Chris Lattneraf6094f2007-02-15 22:48:32 +00001502 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001503
1504 // Find out whether the last index in the source GEP is a sequential idx.
1505 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001506 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1507 I != E; ++I)
Duncan Sands19d0b472010-02-16 11:11:14 +00001508 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001509
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001510 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001511 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001512 // Replace: gep (gep %P, long B), long A, ...
1513 // With: T = long A+B; gep %P, T, ...
1514 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001515 Value *Sum;
1516 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1517 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001518 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001519 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001520 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001521 Sum = SO1;
1522 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001523 // If they aren't the same type, then the input hasn't been processed
1524 // by the loop above yet (which canonicalizes sequential index types to
1525 // intptr_t). Just avoid transforming this until the input has been
1526 // normalized.
1527 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001528 return nullptr;
Wei Mia0adf9f2015-04-21 23:02:15 +00001529 // Only do the combine when GO1 and SO1 are both constants. Only in
1530 // this case, we are sure the cost after the merge is never more than
1531 // that before the merge.
1532 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1533 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001534 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001535 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001536
Chris Lattnerb2995e12009-08-30 05:30:55 +00001537 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001538 if (Src->getNumOperands() == 2) {
1539 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001540 GEP.setOperand(1, Sum);
1541 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001542 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001543 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001544 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001545 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001546 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001547 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001548 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001549 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001550 Indices.append(Src->op_begin()+1, Src->op_end());
1551 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001552 }
1553
Dan Gohman1b849082009-09-07 23:54:19 +00001554 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001555 return GEP.isInBounds() && Src->isInBounds()
1556 ? GetElementPtrInst::CreateInBounds(
1557 Src->getSourceElementType(), Src->getOperand(0), Indices,
1558 GEP.getName())
1559 : GetElementPtrInst::Create(Src->getSourceElementType(),
1560 Src->getOperand(0), Indices,
1561 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001562 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001563
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001564 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001565 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001566 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 DL.getPointerSizeInBits(AS)) {
David Majnemerd2df5012014-09-01 21:10:02 +00001568 Type *PtrTy = GEP.getPointerOperandType();
1569 Type *Ty = PtrTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001570 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001571
1572 bool Matched = false;
1573 uint64_t C;
1574 Value *V = nullptr;
1575 if (TyAllocSize == 1) {
1576 V = GEP.getOperand(1);
1577 Matched = true;
1578 } else if (match(GEP.getOperand(1),
1579 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1580 if (TyAllocSize == 1ULL << C)
1581 Matched = true;
1582 } else if (match(GEP.getOperand(1),
1583 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1584 if (TyAllocSize == C)
1585 Matched = true;
1586 }
1587
1588 if (Matched) {
1589 // Canonicalize (gep i8* X, -(ptrtoint Y))
1590 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1591 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1592 // pointer arithmetic.
1593 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1594 Operator *Index = cast<Operator>(V);
1595 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1596 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1597 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1598 }
1599 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1600 // to (bitcast Y)
1601 Value *Y;
1602 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1603 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1604 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1605 GEP.getType());
1606 }
1607 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001608 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001609 }
1610
Chris Lattner06c687b2009-08-30 05:08:50 +00001611 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001612 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001613 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1614
Nadav Rotema8f35622012-03-26 21:00:53 +00001615 // We do not handle pointer-vector geps here.
1616 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001617 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001618
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001619 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001620 bool HasZeroPointerIndex = false;
1621 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1622 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001623
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001624 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1625 // into : GEP [10 x i8]* X, i32 0, ...
1626 //
1627 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1628 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001629 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001630 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001631 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001632 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1633 if (ArrayType *CATy =
Duncan Sands5795a602009-03-02 09:18:21 +00001634 dyn_cast<ArrayType>(CPTy->getElementType())) {
1635 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001636 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001637 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001638 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001639 GetElementPtrInst *Res = GetElementPtrInst::Create(
1640 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001641 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001642 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1643 return Res;
1644 // Insert Res, and create an addrspacecast.
1645 // e.g.,
1646 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1647 // ->
1648 // %0 = GEP i8 addrspace(1)* X, ...
1649 // addrspacecast i8 addrspace(1)* %0 to i8*
1650 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001651 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001652
Chris Lattner229907c2011-07-18 04:54:35 +00001653 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001654 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001655 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001656 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001657 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001658 // At this point, we know that the cast source type is a pointer
1659 // to an array of the same type as the destination pointer
1660 // array. Because the array type is never stepped over (there
1661 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001662 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1663 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001664 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001665 return &GEP;
1666 }
1667 // Cannot replace the base pointer directly because StrippedPtr's
1668 // address space is different. Instead, create a new GEP followed by
1669 // an addrspacecast.
1670 // e.g.,
1671 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1672 // i32 0, ...
1673 // ->
1674 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1675 // addrspacecast i8 addrspace(1)* %0 to i8*
1676 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001677 Value *NewGEP = GEP.isInBounds()
1678 ? Builder->CreateInBoundsGEP(
1679 nullptr, StrippedPtr, Idx, GEP.getName())
1680 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1681 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001682 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001683 }
Duncan Sands5795a602009-03-02 09:18:21 +00001684 }
1685 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001686 } else if (GEP.getNumOperands() == 2) {
1687 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001688 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1689 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001690 Type *SrcElTy = StrippedPtrTy->getElementType();
Matt Arsenaultfc00f7e2013-08-14 00:24:34 +00001691 Type *ResElTy = PtrOp->getType()->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001692 if (SrcElTy->isArrayTy() &&
1693 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1694 DL.getTypeAllocSize(ResElTy)) {
1695 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001696 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001697 Value *NewGEP =
1698 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001699 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1700 GEP.getName())
1701 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001702
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001703 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001704 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1705 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001706 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001707
Chris Lattner2a893292005-09-13 18:36:04 +00001708 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001709 // %V = mul i64 %N, 4
1710 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1711 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001712 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001713 // Check that changing the type amounts to dividing the index by a scale
1714 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001715 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1716 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001717 if (ResSize && SrcSize % ResSize == 0) {
1718 Value *Idx = GEP.getOperand(1);
1719 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1720 uint64_t Scale = SrcSize / ResSize;
1721
1722 // Earlier transforms ensure that the index has type IntPtrType, which
1723 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001724 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001725 "Index not cast to pointer width?");
1726
1727 bool NSW;
1728 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1729 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1730 // If the multiplication NewIdx * Scale may overflow then the new
1731 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001732 Value *NewGEP =
1733 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001734 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001735 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001736 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1737 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001738
Duncan Sands533c8ae2012-10-23 08:28:26 +00001739 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001740 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1741 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001742 }
1743 }
1744 }
1745
1746 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001747 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001748 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001749 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001750 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001751 // Check that changing to the array element type amounts to dividing the
1752 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001753 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1754 uint64_t ArrayEltSize =
1755 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001756 if (ResSize && ArrayEltSize % ResSize == 0) {
1757 Value *Idx = GEP.getOperand(1);
1758 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1759 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001760
Duncan Sands533c8ae2012-10-23 08:28:26 +00001761 // Earlier transforms ensure that the index has type IntPtrType, which
1762 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001763 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001764 "Index not cast to pointer width?");
1765
1766 bool NSW;
1767 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1768 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1769 // If the multiplication NewIdx * Scale may overflow then the new
1770 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001771 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001772 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1773 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001774
David Blaikieaa41cd52015-04-03 21:33:42 +00001775 Value *NewGEP = GEP.isInBounds() && NSW
1776 ? Builder->CreateInBoundsGEP(
1777 SrcElTy, StrippedPtr, Off, GEP.getName())
1778 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1779 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001780 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001781 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1782 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001783 }
1784 }
Chris Lattner2a893292005-09-13 18:36:04 +00001785 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001786 }
Chris Lattnerca081252001-12-14 16:52:21 +00001787 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001788
Matt Arsenault4815f092014-08-12 19:46:13 +00001789 // addrspacecast between types is canonicalized as a bitcast, then an
1790 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1791 // through the addrspacecast.
1792 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1793 // X = bitcast A addrspace(1)* to B addrspace(1)*
1794 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1795 // Z = gep Y, <...constant indices...>
1796 // Into an addrspacecasted GEP of the struct.
1797 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1798 PtrOp = BC;
1799 }
1800
Chris Lattnerfef138b2009-01-09 05:44:56 +00001801 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001802 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001803 /// Y = gep X, <...constant indices...>
1804 /// into a gep of the original struct. This is important for SROA and alias
1805 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001806 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001807 Value *Operand = BCI->getOperand(0);
1808 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001809 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001810 APInt Offset(OffsetBits, 0);
1811 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001812 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001813
Chris Lattnerfef138b2009-01-09 05:44:56 +00001814 // If this GEP instruction doesn't move the pointer, just replace the GEP
1815 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001816 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001817 // If the bitcast is of an allocation, and the allocation will be
1818 // converted to match the type of the cast, don't touch this.
Matt Arsenault98f34e32013-08-19 22:17:34 +00001819 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001820 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1821 if (Instruction *I = visitBitCast(*BCI)) {
1822 if (I != BCI) {
1823 I->takeName(BCI);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001824 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001825 ReplaceInstUsesWith(*BCI, I);
1826 }
1827 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001828 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001829 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001830
1831 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1832 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001833 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001834 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001835
Chris Lattnerfef138b2009-01-09 05:44:56 +00001836 // Otherwise, if the offset is non-zero, we need to find out if there is a
1837 // field at Offset in 'A's type. If so, we can pull the cast through the
1838 // GEP.
1839 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001840 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001841 Value *NGEP =
1842 GEP.isInBounds()
1843 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1844 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001845
Chris Lattner59663412009-08-30 18:50:58 +00001846 if (NGEP->getType() == GEP.getType())
1847 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001848 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001849
1850 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1851 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001852 return new BitCastInst(NGEP, GEP.getType());
1853 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001854 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001855 }
1856
Craig Topperf40110f2014-04-25 05:29:35 +00001857 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001858}
1859
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001860static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001861isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1862 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001863 SmallVector<Instruction*, 4> Worklist;
1864 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001865
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001866 do {
1867 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001868 for (User *U : PI->users()) {
1869 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001870 switch (I->getOpcode()) {
1871 default:
1872 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001873 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001874
1875 case Instruction::BitCast:
1876 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001877 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001878 Worklist.push_back(I);
1879 continue;
1880
1881 case Instruction::ICmp: {
1882 ICmpInst *ICI = cast<ICmpInst>(I);
1883 // We can fold eq/ne comparisons with null to false/true, respectively.
1884 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1885 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001886 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001887 continue;
1888 }
1889
1890 case Instruction::Call:
1891 // Ignore no-op and store intrinsics.
1892 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1893 switch (II->getIntrinsicID()) {
1894 default:
1895 return false;
1896
1897 case Intrinsic::memmove:
1898 case Intrinsic::memcpy:
1899 case Intrinsic::memset: {
1900 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1901 if (MI->isVolatile() || MI->getRawDest() != PI)
1902 return false;
1903 }
1904 // fall through
1905 case Intrinsic::dbg_declare:
1906 case Intrinsic::dbg_value:
1907 case Intrinsic::invariant_start:
1908 case Intrinsic::invariant_end:
1909 case Intrinsic::lifetime_start:
1910 case Intrinsic::lifetime_end:
1911 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001912 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001913 continue;
1914 }
1915 }
1916
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001917 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001918 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001919 continue;
1920 }
1921 return false;
1922
1923 case Instruction::Store: {
1924 StoreInst *SI = cast<StoreInst>(I);
1925 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1926 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001927 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001928 continue;
1929 }
1930 }
1931 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001932 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001933 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00001934 return true;
1935}
1936
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001937Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00001938 // If we have a malloc call which is only used in any amount of comparisons
1939 // to null and free calls, delete the calls and replace the comparisons with
1940 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00001941 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001942 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00001943 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1944 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1945 if (!I) continue;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001946
Nick Lewycky50f49662011-08-03 00:43:35 +00001947 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001948 ReplaceInstUsesWith(*C,
1949 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1950 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00001951 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001952 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001953 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1954 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1955 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1956 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1957 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1958 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001959 }
Nick Lewycky50f49662011-08-03 00:43:35 +00001960 EraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001961 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001962
1963 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00001964 // Replace invoke with a NOP intrinsic to maintain the original CFG
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001965 Module *M = II->getModule();
Nuno Lopes9ac46612012-06-28 22:31:24 +00001966 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1967 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00001968 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00001969 }
Duncan Sandsf162eac2010-05-27 19:09:06 +00001970 return EraseInstFromFunction(MI);
1971 }
Craig Topperf40110f2014-04-25 05:29:35 +00001972 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00001973}
1974
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00001975/// \brief Move the call to free before a NULL test.
1976///
1977/// Check if this free is accessed after its argument has been test
1978/// against NULL (property 0).
1979/// If yes, it is legal to move this call in its predecessor block.
1980///
1981/// The move is performed only if the block containing the call to free
1982/// will be removed, i.e.:
1983/// 1. it has only one predecessor P, and P has two successors
1984/// 2. it contains the call and an unconditional branch
1985/// 3. its successor is the same as its predecessor's successor
1986///
1987/// The profitability is out-of concern here and this function should
1988/// be called only if the caller knows this transformation would be
1989/// profitable (e.g., for code size).
1990static Instruction *
1991tryToMoveFreeBeforeNullTest(CallInst &FI) {
1992 Value *Op = FI.getArgOperand(0);
1993 BasicBlock *FreeInstrBB = FI.getParent();
1994 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1995
1996 // Validate part of constraint #1: Only one predecessor
1997 // FIXME: We can extend the number of predecessor, but in that case, we
1998 // would duplicate the call to free in each predecessor and it may
1999 // not be profitable even for code size.
2000 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00002001 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002002
2003 // Validate constraint #2: Does this block contains only the call to
2004 // free and an unconditional branch?
2005 // FIXME: We could check if we can speculate everything in the
2006 // predecessor block
2007 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002008 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002009 BasicBlock *SuccBB;
2010 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002011 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002012
2013 // Validate the rest of constraint #1 by matching on the pred branch.
2014 TerminatorInst *TI = PredBB->getTerminator();
2015 BasicBlock *TrueBB, *FalseBB;
2016 ICmpInst::Predicate Pred;
2017 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002018 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002019 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002020 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002021
2022 // Validate constraint #3: Ensure the null case just falls through.
2023 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002024 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002025 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2026 "Broken CFG: missing edge from predecessor to successor");
2027
2028 FI.moveBefore(TI);
2029 return &FI;
2030}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002031
2032
Gabor Greif75f69432010-06-24 12:21:15 +00002033Instruction *InstCombiner::visitFree(CallInst &FI) {
2034 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002035
2036 // free undef -> unreachable.
2037 if (isa<UndefValue>(Op)) {
2038 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002039 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2040 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Victor Hernandeze2971492009-10-24 04:23:03 +00002041 return EraseInstFromFunction(FI);
2042 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002043
Victor Hernandeze2971492009-10-24 04:23:03 +00002044 // If we have 'free null' delete the instruction. This can happen in stl code
2045 // when lots of inlining happens.
2046 if (isa<ConstantPointerNull>(Op))
2047 return EraseInstFromFunction(FI);
2048
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002049 // If we optimize for code size, try to move the call to free before the null
2050 // test so that simplify cfg can remove the empty block and dead code
2051 // elimination the branch. I.e., helps to turn something like:
2052 // if (foo) free(foo);
2053 // into
2054 // free(foo);
2055 if (MinimizeSize)
2056 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2057 return I;
2058
Craig Topperf40110f2014-04-25 05:29:35 +00002059 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002060}
Chris Lattner8427bff2003-12-07 01:24:23 +00002061
Hal Finkel93873cc12014-09-07 21:28:34 +00002062Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2063 if (RI.getNumOperands() == 0) // ret void
2064 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002065
Hal Finkel93873cc12014-09-07 21:28:34 +00002066 Value *ResultOp = RI.getOperand(0);
2067 Type *VTy = ResultOp->getType();
2068 if (!VTy->isIntegerTy())
2069 return nullptr;
2070
2071 // There might be assume intrinsics dominating this return that completely
2072 // determine the value. If so, constant fold it.
2073 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2074 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2075 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2076 if ((KnownZero|KnownOne).isAllOnesValue())
2077 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2078
2079 return nullptr;
2080}
Chris Lattner31f486c2005-01-31 05:36:43 +00002081
Chris Lattner9eef8a72003-06-04 04:46:00 +00002082Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2083 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002084 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002085 BasicBlock *TrueDest;
2086 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002087 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002088 !isa<Constant>(X)) {
2089 // Swap Destinations and condition...
2090 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002091 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002092 return &BI;
2093 }
2094
Philip Reames71c40352015-03-10 22:52:37 +00002095 // If the condition is irrelevant, remove the use so that other
2096 // transforms on the condition become more effective.
2097 if (BI.isConditional() &&
2098 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2099 !isa<UndefValue>(BI.getCondition())) {
2100 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2101 return &BI;
2102 }
2103
Alp Tokercb402912014-01-24 17:20:08 +00002104 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002105 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002106 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002107 TrueDest, FalseDest)) &&
2108 BI.getCondition()->hasOneUse())
2109 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2110 FPred == FCmpInst::FCMP_OGE) {
2111 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2112 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002113
Chris Lattner905976b2009-08-30 06:13:40 +00002114 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002115 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002116 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002117 return &BI;
2118 }
2119
Alp Tokercb402912014-01-24 17:20:08 +00002120 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002121 ICmpInst::Predicate IPred;
2122 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002123 TrueDest, FalseDest)) &&
2124 BI.getCondition()->hasOneUse())
2125 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2126 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2127 IPred == ICmpInst::ICMP_SGE) {
2128 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2129 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2130 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002131 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002132 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002133 return &BI;
2134 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002135
Craig Topperf40110f2014-04-25 05:29:35 +00002136 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002137}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002138
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002139Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2140 Value *Cond = SI.getCondition();
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002141 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2142 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002143 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002144 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2145 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2146
2147 // Compute the number of leading bits we can ignore.
2148 for (auto &C : SI.cases()) {
2149 LeadingKnownZeros = std::min(
2150 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2151 LeadingKnownOnes = std::min(
2152 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2153 }
2154
2155 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2156
2157 // Truncate the condition operand if the new type is equal to or larger than
2158 // the largest legal integer type. We need to be conservative here since
Sanjay Patel6a248112015-06-23 23:26:22 +00002159 // x86 generates redundant zero-extension instructions if the operand is
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002160 // truncated to i8 or i16.
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002161 bool TruncCond = false;
Owen Anderson58364dc2015-03-10 06:51:39 +00002162 if (NewWidth > 0 && BitWidth > NewWidth &&
2163 NewWidth >= DL.getLargestLegalIntTypeSize()) {
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002164 TruncCond = true;
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002165 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2166 Builder->SetInsertPoint(&SI);
2167 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2168 SI.setCondition(NewCond);
2169
2170 for (auto &C : SI.cases())
2171 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2172 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2173 }
2174
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002175 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2176 if (I->getOpcode() == Instruction::Add)
2177 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2178 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedman95031ed2011-09-29 20:21:17 +00002179 // Skip the first item since that's the default case.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002180 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002181 i != e; ++i) {
2182 ConstantInt* CaseVal = i.getCaseValue();
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002183 Constant *LHS = CaseVal;
2184 if (TruncCond)
2185 LHS = LeadingKnownZeros
2186 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2187 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2188 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
Eli Friedman95031ed2011-09-29 20:21:17 +00002189 assert(isa<ConstantInt>(NewCaseVal) &&
2190 "Result of expression should be constant");
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002191 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedman95031ed2011-09-29 20:21:17 +00002192 }
2193 SI.setCondition(I->getOperand(0));
Chris Lattner905976b2009-08-30 06:13:40 +00002194 Worklist.Add(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002195 return &SI;
2196 }
2197 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002198
2199 return TruncCond ? &SI : nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002200}
2201
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002202Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002203 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002204
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002205 if (!EV.hasIndices())
2206 return ReplaceInstUsesWith(EV, Agg);
2207
David Majnemer25a796e2015-07-13 01:15:46 +00002208 if (Value *V =
2209 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
2210 return ReplaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002211
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002212 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2213 // We're extracting from an insertvalue instruction, compare the indices
2214 const unsigned *exti, *exte, *insi, *inse;
2215 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2216 exte = EV.idx_end(), inse = IV->idx_end();
2217 exti != exte && insi != inse;
2218 ++exti, ++insi) {
2219 if (*insi != *exti)
2220 // The insert and extract both reference distinctly different elements.
2221 // This means the extract is not influenced by the insert, and we can
2222 // replace the aggregate operand of the extract with the aggregate
2223 // operand of the insert. i.e., replace
2224 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2225 // %E = extractvalue { i32, { i32 } } %I, 0
2226 // with
2227 // %E = extractvalue { i32, { i32 } } %A, 0
2228 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002229 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002230 }
2231 if (exti == exte && insi == inse)
2232 // Both iterators are at the end: Index lists are identical. Replace
2233 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2234 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2235 // with "i32 42"
2236 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
2237 if (exti == exte) {
2238 // The extract list is a prefix of the insert list. i.e. replace
2239 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2240 // %E = extractvalue { i32, { i32 } } %I, 1
2241 // with
2242 // %X = extractvalue { i32, { i32 } } %A, 1
2243 // %E = insertvalue { i32 } %X, i32 42, 0
2244 // by switching the order of the insert and extract (though the
2245 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002246 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002247 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002248 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002249 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002250 }
2251 if (insi == inse)
2252 // The insert list is a prefix of the extract list
2253 // We can simply remove the common indices from the extract and make it
2254 // operate on the inserted value instead of the insertvalue result.
2255 // i.e., replace
2256 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2257 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2258 // with
2259 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002260 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002261 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002262 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002263 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2264 // We're extracting from an intrinsic, see if we're the only user, which
2265 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002266 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002267 if (II->hasOneUse()) {
2268 // Check if we're grabbing the overflow bit or the result of a 'with
2269 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2270 // and replace it with a traditional binary instruction.
2271 switch (II->getIntrinsicID()) {
2272 case Intrinsic::uadd_with_overflow:
2273 case Intrinsic::sadd_with_overflow:
2274 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002275 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002276 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002277 EraseInstFromFunction(*II);
2278 return BinaryOperator::CreateAdd(LHS, RHS);
2279 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002280
Chris Lattner3e635d22010-12-19 19:43:52 +00002281 // If the normal result of the add is dead, and the RHS is a constant,
2282 // we can transform this into a range comparison.
2283 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002284 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2285 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2286 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2287 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002288 break;
2289 case Intrinsic::usub_with_overflow:
2290 case Intrinsic::ssub_with_overflow:
2291 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002292 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002293 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002294 EraseInstFromFunction(*II);
2295 return BinaryOperator::CreateSub(LHS, RHS);
2296 }
2297 break;
2298 case Intrinsic::umul_with_overflow:
2299 case Intrinsic::smul_with_overflow:
2300 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002301 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002302 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
Chris Lattner39c07b22009-11-09 07:07:56 +00002303 EraseInstFromFunction(*II);
2304 return BinaryOperator::CreateMul(LHS, RHS);
2305 }
2306 break;
2307 default:
2308 break;
2309 }
2310 }
2311 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002312 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2313 // If the (non-volatile) load only has one use, we can rewrite this to a
Mehdi Amini1c131b32015-12-15 01:44:07 +00002314 // load from a GEP. This reduces the size of the load. If a load is used
2315 // only by extractvalue instructions then this either must have been
2316 // optimized before, or it is a struct with padding, in which case we
2317 // don't want to do the transformation as it loses padding knowledge.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002318 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002319 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2320 SmallVector<Value*, 4> Indices;
2321 // Prefix an i32 0 since we need the first element.
2322 Indices.push_back(Builder->getInt32(0));
2323 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2324 I != E; ++I)
2325 Indices.push_back(Builder->getInt32(*I));
2326
2327 // We need to insert these at the location of the old load, not at that of
2328 // the extractvalue.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002329 Builder->SetInsertPoint(L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002330 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2331 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002332 // Returning the load directly will cause the main loop to insert it in
2333 // the wrong spot, so use ReplaceInstUsesWith().
2334 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
2335 }
2336 // We could simplify extracts from other values. Note that nested extracts may
2337 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002338 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002339 // the value inserted, if appropriate. Similarly for extracts from single-use
2340 // loads: extract (extract (load)) will be translated to extract (load (gep))
2341 // and if again single-use then via load (gep (gep)) to load (gep).
2342 // However, double extracts from e.g. function arguments or return values
2343 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002344 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002345}
2346
Sanjay Patel84dca492015-09-21 15:33:26 +00002347/// Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002348static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002349 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002350 case EHPersonality::GNU_C:
2351 // The GCC C EH personality only exists to support cleanups, so it's not
2352 // clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002353 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002354 case EHPersonality::Unknown:
2355 return false;
2356 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002357 // While __gnat_all_others_value will match any Ada exception, it doesn't
2358 // match foreign exceptions (or didn't, before gcc-4.7).
2359 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002360 case EHPersonality::GNU_CXX:
2361 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002362 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002363 case EHPersonality::MSVC_Win64SEH:
2364 case EHPersonality::MSVC_CXX:
Joseph Tremoulet2afea542015-10-06 20:28:16 +00002365 case EHPersonality::CoreCLR:
Duncan Sands5c055792011-09-30 13:12:16 +00002366 return TypeInfo->isNullValue();
2367 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002368 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002369}
2370
2371static bool shorter_filter(const Value *LHS, const Value *RHS) {
2372 return
2373 cast<ArrayType>(LHS->getType())->getNumElements()
2374 <
2375 cast<ArrayType>(RHS->getType())->getNumElements();
2376}
2377
2378Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2379 // The logic here should be correct for any real-world personality function.
2380 // However if that turns out not to be true, the offending logic can always
2381 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002382 EHPersonality Personality =
2383 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002384
2385 // Simplify the list of clauses, eg by removing repeated catch clauses
2386 // (these are often created by inlining).
2387 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002388 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002389 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2390
2391 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2392 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2393 bool isLastClause = i + 1 == e;
2394 if (LI.isCatch(i)) {
2395 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002396 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002397 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002398
2399 // If we already saw this clause, there is no point in having a second
2400 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002401 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002402 // This catch clause was not already seen.
2403 NewClauses.push_back(CatchClause);
2404 } else {
2405 // Repeated catch clause - drop the redundant copy.
2406 MakeNewInstruction = true;
2407 }
2408
2409 // If this is a catch-all then there is no point in keeping any following
2410 // clauses or marking the landingpad as having a cleanup.
2411 if (isCatchAll(Personality, TypeInfo)) {
2412 if (!isLastClause)
2413 MakeNewInstruction = true;
2414 CleanupFlag = false;
2415 break;
2416 }
2417 } else {
2418 // A filter clause. If any of the filter elements were already caught
2419 // then they can be dropped from the filter. It is tempting to try to
2420 // exploit the filter further by saying that any typeinfo that does not
2421 // occur in the filter can't be caught later (and thus can be dropped).
2422 // However this would be wrong, since typeinfos can match without being
2423 // equal (for example if one represents a C++ class, and the other some
2424 // class derived from it).
2425 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002426 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002427 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2428 unsigned NumTypeInfos = FilterType->getNumElements();
2429
2430 // An empty filter catches everything, so there is no point in keeping any
2431 // following clauses or marking the landingpad as having a cleanup. By
2432 // dealing with this case here the following code is made a bit simpler.
2433 if (!NumTypeInfos) {
2434 NewClauses.push_back(FilterClause);
2435 if (!isLastClause)
2436 MakeNewInstruction = true;
2437 CleanupFlag = false;
2438 break;
2439 }
2440
2441 bool MakeNewFilter = false; // If true, make a new filter.
2442 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2443 if (isa<ConstantAggregateZero>(FilterClause)) {
2444 // Not an empty filter - it contains at least one null typeinfo.
2445 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2446 Constant *TypeInfo =
2447 Constant::getNullValue(FilterType->getElementType());
2448 // If this typeinfo is a catch-all then the filter can never match.
2449 if (isCatchAll(Personality, TypeInfo)) {
2450 // Throw the filter away.
2451 MakeNewInstruction = true;
2452 continue;
2453 }
2454
2455 // There is no point in having multiple copies of this typeinfo, so
2456 // discard all but the first copy if there is more than one.
2457 NewFilterElts.push_back(TypeInfo);
2458 if (NumTypeInfos > 1)
2459 MakeNewFilter = true;
2460 } else {
2461 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2462 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2463 NewFilterElts.reserve(NumTypeInfos);
2464
2465 // Remove any filter elements that were already caught or that already
2466 // occurred in the filter. While there, see if any of the elements are
2467 // catch-alls. If so, the filter can be discarded.
2468 bool SawCatchAll = false;
2469 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002470 Constant *Elt = Filter->getOperand(j);
2471 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002472 if (isCatchAll(Personality, TypeInfo)) {
2473 // This element is a catch-all. Bail out, noting this fact.
2474 SawCatchAll = true;
2475 break;
2476 }
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002477
2478 // Even if we've seen a type in a catch clause, we don't want to
2479 // remove it from the filter. An unexpected type handler may be
2480 // set up for a call site which throws an exception of the same
2481 // type caught. In order for the exception thrown by the unexpected
2482 // handler to propogate correctly, the filter must be correctly
2483 // described for the call site.
2484 //
2485 // Example:
2486 //
2487 // void unexpected() { throw 1;}
2488 // void foo() throw (int) {
2489 // std::set_unexpected(unexpected);
2490 // try {
2491 // throw 2.0;
2492 // } catch (int i) {}
2493 // }
2494
Duncan Sands5c055792011-09-30 13:12:16 +00002495 // There is no point in having multiple copies of the same typeinfo in
2496 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002497 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002498 NewFilterElts.push_back(cast<Constant>(Elt));
2499 }
2500 // A filter containing a catch-all cannot match anything by definition.
2501 if (SawCatchAll) {
2502 // Throw the filter away.
2503 MakeNewInstruction = true;
2504 continue;
2505 }
2506
2507 // If we dropped something from the filter, make a new one.
2508 if (NewFilterElts.size() < NumTypeInfos)
2509 MakeNewFilter = true;
2510 }
2511 if (MakeNewFilter) {
2512 FilterType = ArrayType::get(FilterType->getElementType(),
2513 NewFilterElts.size());
2514 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2515 MakeNewInstruction = true;
2516 }
2517
2518 NewClauses.push_back(FilterClause);
2519
2520 // If the new filter is empty then it will catch everything so there is
2521 // no point in keeping any following clauses or marking the landingpad
2522 // as having a cleanup. The case of the original filter being empty was
2523 // already handled above.
2524 if (MakeNewFilter && !NewFilterElts.size()) {
2525 assert(MakeNewInstruction && "New filter but not a new instruction!");
2526 CleanupFlag = false;
2527 break;
2528 }
2529 }
2530 }
2531
2532 // If several filters occur in a row then reorder them so that the shortest
2533 // filters come first (those with the smallest number of elements). This is
2534 // advantageous because shorter filters are more likely to match, speeding up
2535 // unwinding, but mostly because it increases the effectiveness of the other
2536 // filter optimizations below.
2537 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2538 unsigned j;
2539 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2540 for (j = i; j != e; ++j)
2541 if (!isa<ArrayType>(NewClauses[j]->getType()))
2542 break;
2543
2544 // Check whether the filters are already sorted by length. We need to know
2545 // if sorting them is actually going to do anything so that we only make a
2546 // new landingpad instruction if it does.
2547 for (unsigned k = i; k + 1 < j; ++k)
2548 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2549 // Not sorted, so sort the filters now. Doing an unstable sort would be
2550 // correct too but reordering filters pointlessly might confuse users.
2551 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2552 shorter_filter);
2553 MakeNewInstruction = true;
2554 break;
2555 }
2556
2557 // Look for the next batch of filters.
2558 i = j + 1;
2559 }
2560
2561 // If typeinfos matched if and only if equal, then the elements of a filter L
2562 // that occurs later than a filter F could be replaced by the intersection of
2563 // the elements of F and L. In reality two typeinfos can match without being
2564 // equal (for example if one represents a C++ class, and the other some class
2565 // derived from it) so it would be wrong to perform this transform in general.
2566 // However the transform is correct and useful if F is a subset of L. In that
2567 // case L can be replaced by F, and thus removed altogether since repeating a
2568 // filter is pointless. So here we look at all pairs of filters F and L where
2569 // L follows F in the list of clauses, and remove L if every element of F is
2570 // an element of L. This can occur when inlining C++ functions with exception
2571 // specifications.
2572 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2573 // Examine each filter in turn.
2574 Value *Filter = NewClauses[i];
2575 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2576 if (!FTy)
2577 // Not a filter - skip it.
2578 continue;
2579 unsigned FElts = FTy->getNumElements();
2580 // Examine each filter following this one. Doing this backwards means that
2581 // we don't have to worry about filters disappearing under us when removed.
2582 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2583 Value *LFilter = NewClauses[j];
2584 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2585 if (!LTy)
2586 // Not a filter - skip it.
2587 continue;
2588 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2589 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002590 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002591 // If Filter is empty then it is a subset of LFilter.
2592 if (!FElts) {
2593 // Discard LFilter.
2594 NewClauses.erase(J);
2595 MakeNewInstruction = true;
2596 // Move on to the next filter.
2597 continue;
2598 }
2599 unsigned LElts = LTy->getNumElements();
2600 // If Filter is longer than LFilter then it cannot be a subset of it.
2601 if (FElts > LElts)
2602 // Move on to the next filter.
2603 continue;
2604 // At this point we know that LFilter has at least one element.
2605 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002606 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002607 // already know that Filter is not longer than LFilter).
2608 if (isa<ConstantAggregateZero>(Filter)) {
2609 assert(FElts <= LElts && "Should have handled this case earlier!");
2610 // Discard LFilter.
2611 NewClauses.erase(J);
2612 MakeNewInstruction = true;
2613 }
2614 // Move on to the next filter.
2615 continue;
2616 }
2617 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2618 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2619 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002620 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002621 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2622 for (unsigned l = 0; l != LElts; ++l)
2623 if (LArray->getOperand(l)->isNullValue()) {
2624 // LFilter contains a zero - discard it.
2625 NewClauses.erase(J);
2626 MakeNewInstruction = true;
2627 break;
2628 }
2629 // Move on to the next filter.
2630 continue;
2631 }
2632 // At this point we know that both filters are ConstantArrays. Loop over
2633 // operands to see whether every element of Filter is also an element of
2634 // LFilter. Since filters tend to be short this is probably faster than
2635 // using a method that scales nicely.
2636 ConstantArray *FArray = cast<ConstantArray>(Filter);
2637 bool AllFound = true;
2638 for (unsigned f = 0; f != FElts; ++f) {
2639 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2640 AllFound = false;
2641 for (unsigned l = 0; l != LElts; ++l) {
2642 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2643 if (LTypeInfo == FTypeInfo) {
2644 AllFound = true;
2645 break;
2646 }
2647 }
2648 if (!AllFound)
2649 break;
2650 }
2651 if (AllFound) {
2652 // Discard LFilter.
2653 NewClauses.erase(J);
2654 MakeNewInstruction = true;
2655 }
2656 // Move on to the next filter.
2657 }
2658 }
2659
2660 // If we changed any of the clauses, replace the old landingpad instruction
2661 // with a new one.
2662 if (MakeNewInstruction) {
2663 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002664 NewClauses.size());
2665 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2666 NLI->addClause(NewClauses[i]);
2667 // A landing pad with no clauses must have the cleanup flag set. It is
2668 // theoretically possible, though highly unlikely, that we eliminated all
2669 // clauses. If so, force the cleanup flag to true.
2670 if (NewClauses.empty())
2671 CleanupFlag = true;
2672 NLI->setCleanup(CleanupFlag);
2673 return NLI;
2674 }
2675
2676 // Even if none of the clauses changed, we may nonetheless have understood
2677 // that the cleanup flag is pointless. Clear it if so.
2678 if (LI.isCleanup() != CleanupFlag) {
2679 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2680 LI.setCleanup(CleanupFlag);
2681 return &LI;
2682 }
2683
Craig Topperf40110f2014-04-25 05:29:35 +00002684 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002685}
2686
Sanjay Patel84dca492015-09-21 15:33:26 +00002687/// Try to move the specified instruction from its current block into the
2688/// beginning of DestBlock, which can only happen if it's safe to move the
2689/// instruction past all of the instructions between it and the end of its
2690/// block.
Chris Lattner39c98bb2004-12-08 23:43:58 +00002691static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2692 assert(I->hasOneUse() && "Invariants didn't hold!");
2693
Bill Wendlinge86965e2011-08-15 21:14:31 +00002694 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002695 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002696 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002697 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002698
Chris Lattner39c98bb2004-12-08 23:43:58 +00002699 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002700 if (isa<AllocaInst>(I) && I->getParent() ==
2701 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002702 return false;
2703
Fiona Glasera8b653a2015-11-03 22:23:39 +00002704 // Do not sink convergent call instructions.
2705 if (auto *CI = dyn_cast<CallInst>(I)) {
2706 if (CI->isConvergent())
2707 return false;
2708 }
2709
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002710 // We can only sink load instructions if there is nothing between the load and
2711 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002712 if (I->mayReadFromMemory()) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002713 for (BasicBlock::iterator Scan = I->getIterator(),
2714 E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002715 Scan != E; ++Scan)
2716 if (Scan->mayWriteToMemory())
2717 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002718 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002719
Bill Wendling8ddfc092011-08-16 20:45:24 +00002720 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002721 I->moveBefore(&*InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002722 ++NumSunkInst;
2723 return true;
2724}
2725
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002726bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002727 while (!Worklist.isEmpty()) {
2728 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002729 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002730
Chris Lattner1443bc52006-05-11 17:11:52 +00002731 // Check to see if we can DCE the instruction.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002732 if (isInstructionTriviallyDead(I, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002733 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Chris Lattner905976b2009-08-30 06:13:40 +00002734 EraseInstFromFunction(*I);
2735 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002736 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002737 continue;
2738 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002739
Chris Lattner1443bc52006-05-11 17:11:52 +00002740 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002741 if (!I->use_empty() &&
2742 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002743 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002744 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002745
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002746 // Add operands to the worklist.
2747 ReplaceInstUsesWith(*I, C);
2748 ++NumConstProp;
2749 EraseInstFromFunction(*I);
2750 MadeIRChange = true;
2751 continue;
2752 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002753 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002754
Hal Finkelf2199b22015-10-23 20:37:08 +00002755 // In general, it is possible for computeKnownBits to determine all bits in a
2756 // value even when the operands are not all constants.
2757 if (!I->use_empty() && I->getType()->isIntegerTy()) {
2758 unsigned BitWidth = I->getType()->getScalarSizeInBits();
2759 APInt KnownZero(BitWidth, 0);
2760 APInt KnownOne(BitWidth, 0);
2761 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2762 if ((KnownZero | KnownOne).isAllOnesValue()) {
2763 Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2764 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2765 " from: " << *I << '\n');
2766
2767 // Add operands to the worklist.
2768 ReplaceInstUsesWith(*I, C);
2769 ++NumConstProp;
2770 EraseInstFromFunction(*I);
2771 MadeIRChange = true;
2772 continue;
2773 }
2774 }
2775
Chris Lattner39c98bb2004-12-08 23:43:58 +00002776 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002777 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002778 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002779 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002780 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002781
Chris Lattner6b9044d2009-10-14 15:21:58 +00002782 // Get the block the use occurs in.
2783 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002784 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002785 else
2786 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002787
Chris Lattner39c98bb2004-12-08 23:43:58 +00002788 if (UserParent != BB) {
2789 bool UserIsSuccessor = false;
2790 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002791 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2792 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002793 UserIsSuccessor = true;
2794 break;
2795 }
2796
2797 // If the user is one of our immediate successors, and if that successor
2798 // only has us as a predecessors (we'd have to split the critical edge
2799 // otherwise), we can keep going.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002800 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002801 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002802 if (TryToSinkInstruction(I, UserParent)) {
2803 MadeIRChange = true;
2804 // We'll add uses of the sunk instruction below, but since sinking
2805 // can expose opportunities for it's *operands* add them to the
2806 // worklist
2807 for (Use &U : I->operands())
2808 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2809 Worklist.Add(OpI);
2810 }
2811 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002812 }
2813 }
2814
Chris Lattner022a5822009-08-30 07:44:24 +00002815 // Now that we have an instruction, try combining it to simplify it.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002816 Builder->SetInsertPoint(I);
Eli Friedman96254a02011-05-18 01:28:27 +00002817 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002818
Reid Spencer755d0e72007-03-26 17:44:01 +00002819#ifndef NDEBUG
2820 std::string OrigI;
2821#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002822 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002823 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002824
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002825 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002826 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002827 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002828 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002829 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002830 << " New = " << *Result << '\n');
2831
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002832 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002833 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002834 // Everything uses the new instruction now.
2835 I->replaceAllUsesWith(Result);
2836
Jim Grosbache7abae02011-10-05 20:53:43 +00002837 // Move the name to the new instruction first.
2838 Result->takeName(I);
2839
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002840 // Push the new instruction and any users onto the worklist.
2841 Worklist.Add(Result);
2842 Worklist.AddUsersToWorkList(*Result);
2843
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002844 // Insert the new instruction into the basic block...
2845 BasicBlock *InstParent = I->getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002846 BasicBlock::iterator InsertPos = I->getIterator();
Chris Lattner7515cab2004-11-14 19:13:23 +00002847
Eli Friedmana49b8282011-11-01 04:49:29 +00002848 // If we replace a PHI with something that isn't a PHI, fix up the
2849 // insertion point.
2850 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2851 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002852
2853 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002854
Chris Lattner905976b2009-08-30 06:13:40 +00002855 EraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002856 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00002857#ifndef NDEBUG
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002858 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002859 << " New = " << *I << '\n');
Evan Chenga4ed8a52007-03-27 16:44:48 +00002860#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00002861
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002862 // If the instruction was modified, it's possible that it is now dead.
2863 // if so, remove it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002864 if (isInstructionTriviallyDead(I, TLI)) {
Chris Lattner905976b2009-08-30 06:13:40 +00002865 EraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002866 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002867 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002868 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002869 }
Chris Lattner053c0932002-05-14 15:24:07 +00002870 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002871 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002872 }
2873 }
2874
Chris Lattner97fd3592009-08-30 05:55:36 +00002875 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002876 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002877}
2878
Sanjay Patel84dca492015-09-21 15:33:26 +00002879/// Walk the function in depth-first order, adding all reachable code to the
2880/// worklist.
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002881///
2882/// This has a couple of tricks to make the code faster and more powerful. In
2883/// particular, we constant fold and DCE instructions as we go, to avoid adding
2884/// them to the worklist (this significantly speeds up instcombine on code where
2885/// many instructions are dead or constant). Additionally, if we find a branch
2886/// whose condition is a known constant, we only visit the reachable successors.
2887///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002888static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2889 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002890 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002891 const TargetLibraryInfo *TLI) {
2892 bool MadeIRChange = false;
2893 SmallVector<BasicBlock*, 256> Worklist;
2894 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002895
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002896 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2897 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002898
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002899 do {
2900 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002901
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002902 // We have now visited this block! If we've already been here, ignore it.
2903 if (!Visited.insert(BB).second)
2904 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00002905
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002906 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002907 Instruction *Inst = &*BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00002908
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002909 // DCE instruction if trivially dead.
2910 if (isInstructionTriviallyDead(Inst, TLI)) {
2911 ++NumDeadInst;
2912 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2913 Inst->eraseFromParent();
2914 continue;
2915 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002916
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002917 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00002918 if (!Inst->use_empty() &&
2919 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002920 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2921 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2922 << *Inst << '\n');
2923 Inst->replaceAllUsesWith(C);
2924 ++NumConstProp;
2925 Inst->eraseFromParent();
2926 continue;
2927 }
2928
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002929 // See if we can constant fold its operands.
2930 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2931 ++i) {
2932 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2933 if (CE == nullptr)
2934 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002935
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002936 Constant *&FoldRes = FoldedConstants[CE];
2937 if (!FoldRes)
2938 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2939 if (!FoldRes)
2940 FoldRes = CE;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002941
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002942 if (FoldRes != CE) {
2943 *i = FoldRes;
2944 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002945 }
2946 }
2947
2948 InstrsForInstCombineWorklist.push_back(Inst);
2949 }
2950
2951 // Recursively visit successors. If this is a branch or switch on a
2952 // constant, only visit the reachable successor.
2953 TerminatorInst *TI = BB->getTerminator();
2954 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2955 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2956 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2957 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2958 Worklist.push_back(ReachableBB);
2959 continue;
2960 }
2961 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2962 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2963 // See if this is an explicit destination.
2964 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2965 i != e; ++i)
2966 if (i.getCaseValue() == Cond) {
2967 BasicBlock *ReachableBB = i.getCaseSuccessor();
2968 Worklist.push_back(ReachableBB);
2969 continue;
2970 }
2971
2972 // Otherwise it is the default destination.
2973 Worklist.push_back(SI->getDefaultDest());
2974 continue;
2975 }
2976 }
2977
Pete Cooperebcd7482015-08-06 20:22:46 +00002978 for (BasicBlock *SuccBB : TI->successors())
2979 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002980 } while (!Worklist.empty());
2981
2982 // Once we've found all of the instructions to add to instcombine's worklist,
2983 // add them in reverse order. This way instcombine will visit from the top
2984 // of the function down. This jives well with the way that it adds all uses
2985 // of instructions to the worklist after doing a transformation, thus avoiding
2986 // some N^2 behavior in pathological cases.
Craig Topper42526d32015-10-22 16:35:56 +00002987 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002988
2989 return MadeIRChange;
2990}
2991
2992/// \brief Populate the IC worklist from a function, and prune any dead basic
2993/// blocks discovered in the process.
2994///
2995/// This also does basic constant propagation and other forward fixing to make
2996/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002997static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002998 TargetLibraryInfo *TLI,
2999 InstCombineWorklist &ICWorklist) {
3000 bool MadeIRChange = false;
3001
3002 // Do a depth-first traversal of the function, populate the worklist with
3003 // the reachable instructions. Ignore blocks that are not reachable. Keep
3004 // track of which blocks we visit.
3005 SmallPtrSet<BasicBlock *, 64> Visited;
3006 MadeIRChange |=
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003007 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003008
3009 // Do a quick scan over the function. If we find any blocks that are
3010 // unreachable, remove any instructions inside of them. This prevents
3011 // the instcombine code from having to deal with some bad special cases.
3012 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003013 if (Visited.count(&*BB))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003014 continue;
3015
3016 // Delete the instructions backwards, as it has a reduced likelihood of
3017 // having to update as many def-use and use-def chains.
3018 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
3019 while (EndInst != BB->begin()) {
3020 // Delete the next to last instruction.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003021 Instruction *Inst = &*--EndInst->getIterator();
David Majnemer7204cff0a2015-11-06 21:26:32 +00003022 if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003023 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
Chen Lic6021032016-01-04 23:28:57 +00003024 if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003025 EndInst = Inst;
3026 continue;
3027 }
3028 if (!isa<DbgInfoIntrinsic>(Inst)) {
3029 ++NumDeadInst;
3030 MadeIRChange = true;
3031 }
Chen Lic6021032016-01-04 23:28:57 +00003032 Inst->eraseFromParent();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003033 }
3034 }
3035
3036 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00003037}
3038
Mehdi Amini46a43552015-03-04 18:43:29 +00003039static bool
3040combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003041 AliasAnalysis *AA, AssumptionCache &AC,
3042 TargetLibraryInfo &TLI, DominatorTree &DT,
3043 LoopInfo *LI = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003044 auto &DL = F.getParent()->getDataLayout();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003045
3046 /// Builder - This is an IRBuilder that automatically inserts new
3047 /// instructions into the worklist when they are created.
3048 IRBuilder<true, TargetFolder, InstCombineIRInserter> Builder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003049 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003050
3051 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3052 // by instcombiner.
3053 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3054
3055 // Iterate while there is work to do.
3056 int Iteration = 0;
3057 for (;;) {
3058 ++Iteration;
3059 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3060 << F.getName() << "\n");
3061
3062 bool Changed = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003063 if (prepareICWorklistFromFunction(F, DL, &TLI, Worklist))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003064 Changed = true;
3065
Sanjay Patel1cd6d882015-08-18 16:44:23 +00003066 InstCombiner IC(Worklist, &Builder, F.optForMinSize(),
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003067 AA, &AC, &TLI, &DT, DL, LI);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003068 if (IC.run())
3069 Changed = true;
3070
3071 if (!Changed)
3072 break;
3073 }
3074
3075 return DbgDeclaresChanged || Iteration > 1;
3076}
3077
3078PreservedAnalyses InstCombinePass::run(Function &F,
3079 AnalysisManager<Function> *AM) {
Chandler Carruth83ba2692015-01-24 04:19:17 +00003080 auto &AC = AM->getResult<AssumptionAnalysis>(F);
3081 auto &DT = AM->getResult<DominatorTreeAnalysis>(F);
3082 auto &TLI = AM->getResult<TargetLibraryAnalysis>(F);
3083
3084 auto *LI = AM->getCachedResult<LoopAnalysis>(F);
3085
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003086 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
3087 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003088 // No changes, all analyses are preserved.
3089 return PreservedAnalyses::all();
3090
3091 // Mark all the analyses that instcombine updates as preserved.
3092 // FIXME: Need a way to preserve CFG analyses here!
3093 PreservedAnalyses PA;
3094 PA.preserve<DominatorTreeAnalysis>();
3095 return PA;
3096}
3097
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003098namespace {
3099/// \brief The legacy pass manager's instcombine pass.
3100///
3101/// This is a basic whole-function wrapper around the instcombine utility. It
3102/// will try to combine all instructions in the function.
3103class InstructionCombiningPass : public FunctionPass {
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003104 InstCombineWorklist Worklist;
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003105
3106public:
3107 static char ID; // Pass identification, replacement for typeid
3108
3109 InstructionCombiningPass() : FunctionPass(ID) {
3110 initializeInstructionCombiningPassPass(*PassRegistry::getPassRegistry());
3111 }
3112
3113 void getAnalysisUsage(AnalysisUsage &AU) const override;
3114 bool runOnFunction(Function &F) override;
3115};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00003116}
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003117
3118void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3119 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003120 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003121 AU.addRequired<AssumptionCacheTracker>();
3122 AU.addRequired<TargetLibraryInfoWrapperPass>();
3123 AU.addRequired<DominatorTreeWrapperPass>();
3124 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003125 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003126}
3127
3128bool InstructionCombiningPass::runOnFunction(Function &F) {
3129 if (skipOptnoneFunction(F))
3130 return false;
3131
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003132 // Required analyses.
Chandler Carruth7b560d42015-09-09 17:55:00 +00003133 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003134 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003135 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3136 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003137
3138 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003139 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3140 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3141
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003142 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003143}
3144
3145char InstructionCombiningPass::ID = 0;
3146INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3147 "Combine redundant instructions", false, false)
3148INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3149INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3150INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +00003151INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3152INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003153INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3154 "Combine redundant instructions", false, false)
3155
3156// Initialization Routines
3157void llvm::initializeInstCombine(PassRegistry &Registry) {
3158 initializeInstructionCombiningPassPass(Registry);
3159}
3160
3161void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3162 initializeInstructionCombiningPassPass(*unwrap(R));
3163}
3164
Brian Gaeke38b79e82004-07-27 17:43:21 +00003165FunctionPass *llvm::createInstructionCombiningPass() {
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003166 return new InstructionCombiningPass();
Chris Lattner04805fa2002-02-26 21:46:54 +00003167}