blob: cc3d168677d6b15cc6d045565caff83f57a0844b [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 Carruthac072702016-02-19 03:12:14 +000042#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000043#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthac072702016-02-19 03:12:14 +000044#include "llvm/Analysis/BasicAliasAnalysis.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000045#include "llvm/Analysis/CFG.h"
Chris Lattner024f4ab2007-01-30 23:46:24 +000046#include "llvm/Analysis/ConstantFolding.h"
David Majnemer70497c62015-12-02 23:06:39 +000047#include "llvm/Analysis/EHPersonalities.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000048#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattnerc1f19072009-11-09 23:28:39 +000049#include "llvm/Analysis/InstructionSimplify.h"
David Majnemer7e2b9882014-11-03 21:55:12 +000050#include "llvm/Analysis/LoopInfo.h"
Victor Hernandezf390e042009-10-27 20:05:49 +000051#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000052#include "llvm/Analysis/TargetLibraryInfo.h"
Sanjay Patel58814442014-07-09 16:34:54 +000053#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000054#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/DataLayout.h"
Hal Finkel60db0582014-09-07 18:57:58 +000056#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000057#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000059#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000060#include "llvm/IR/ValueHandle.h"
Meador Inge193e0352012-11-13 04:16:17 +000061#include "llvm/Support/CommandLine.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000062#include "llvm/Support/Debug.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000063#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000064#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/Transforms/Utils/Local.h"
Chris Lattner053c0932002-05-14 15:24:07 +000066#include <algorithm>
Torok Edwinab207842008-04-20 08:33:11 +000067#include <climits>
Chris Lattner8427bff2003-12-07 01:24:23 +000068using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000069using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000070
Chandler Carruth964daaa2014-04-22 02:55:47 +000071#define DEBUG_TYPE "instcombine"
72
Chris Lattner79a42ac2006-12-19 21:40:18 +000073STATISTIC(NumCombined , "Number of insts combined");
74STATISTIC(NumConstProp, "Number of constant folds");
75STATISTIC(NumDeadInst , "Number of dead inst eliminated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076STATISTIC(NumSunkInst , "Number of instructions sunk");
Duncan Sandsfbb9ac32010-12-22 13:36:08 +000077STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000078STATISTIC(NumFactor , "Number of factorizations");
79STATISTIC(NumReassoc , "Number of reassociations");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000080
Matthias Braunc31032d2016-03-09 18:47:11 +000081static cl::opt<bool>
82EnableExpensiveCombines("expensive-combines",
83 cl::desc("Enable expensive instruction combines"));
84
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000085Value *InstCombiner::EmitGEPOffset(User *GEP) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000086 return llvm::EmitGEPOffset(Builder, DL, GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000087}
88
Sanjay Patel55dcd402015-09-21 16:09:37 +000089/// Return true if it is desirable to convert an integer computation from a
90/// given bit width to a new bit width.
Sanjay Patel84dca492015-09-21 15:33:26 +000091/// We don't want to convert from a legal to an illegal type for example or from
92/// a smaller to a larger illegal type.
Sanjay Patel55dcd402015-09-21 16:09:37 +000093bool InstCombiner::ShouldChangeType(unsigned FromWidth,
94 unsigned ToWidth) const {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000095 bool FromLegal = DL.isLegalInteger(FromWidth);
96 bool ToLegal = DL.isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +000097
Chris Lattner1559bed2009-11-10 07:23:37 +000098 // If this is a legal integer from type, and the result would be an illegal
99 // type, don't do the transformation.
100 if (FromLegal && !ToLegal)
101 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000102
Chris Lattner1559bed2009-11-10 07:23:37 +0000103 // Otherwise, if both are illegal, do not increase the size of the result. We
104 // do allow things like i160 -> i64, but not i64 -> i160.
105 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
106 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000107
Chris Lattner1559bed2009-11-10 07:23:37 +0000108 return true;
109}
110
Sanjay Patel55dcd402015-09-21 16:09:37 +0000111/// Return true if it is desirable to convert a computation from 'From' to 'To'.
112/// We don't want to convert from a legal to an illegal type for example or from
113/// a smaller to a larger illegal type.
114bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
115 assert(From->isIntegerTy() && To->isIntegerTy());
116
117 unsigned FromWidth = From->getPrimitiveSizeInBits();
118 unsigned ToWidth = To->getPrimitiveSizeInBits();
119 return ShouldChangeType(FromWidth, ToWidth);
120}
121
Nick Lewyckyde492782011-08-14 01:45:19 +0000122// Return true, if No Signed Wrap should be maintained for I.
123// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
124// where both B and C should be ConstantInts, results in a constant that does
125// not overflow. This function only handles the Add and Sub opcodes. For
126// all other opcodes, the function conservatively returns false.
127static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
128 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
129 if (!OBO || !OBO->hasNoSignedWrap()) {
130 return false;
131 }
132
133 // We reason about Add and Sub Only.
134 Instruction::BinaryOps Opcode = I.getOpcode();
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000135 if (Opcode != Instruction::Add &&
Nick Lewyckyde492782011-08-14 01:45:19 +0000136 Opcode != Instruction::Sub) {
137 return false;
138 }
139
140 ConstantInt *CB = dyn_cast<ConstantInt>(B);
141 ConstantInt *CC = dyn_cast<ConstantInt>(C);
142
143 if (!CB || !CC) {
144 return false;
145 }
146
147 const APInt &BVal = CB->getValue();
148 const APInt &CVal = CC->getValue();
149 bool Overflow = false;
150
151 if (Opcode == Instruction::Add) {
152 BVal.sadd_ov(CVal, Overflow);
153 } else {
154 BVal.ssub_ov(CVal, Overflow);
155 }
156
157 return !Overflow;
158}
159
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000160/// Conservatively clears subclassOptionalData after a reassociation or
161/// commutation. We preserve fast-math flags when applicable as they can be
162/// preserved.
163static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
164 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
165 if (!FPMO) {
166 I.clearSubclassOptionalData();
167 return;
168 }
169
170 FastMathFlags FMF = I.getFastMathFlags();
171 I.clearSubclassOptionalData();
172 I.setFastMathFlags(FMF);
173}
174
Sanjay Patel84dca492015-09-21 15:33:26 +0000175/// This performs a few simplifications for operators that are associative or
176/// commutative:
177///
178/// Commutative operators:
179///
180/// 1. Order operands such that they are listed from right (least complex) to
181/// left (most complex). This puts constants before unary operators before
182/// binary operators.
183///
184/// Associative operators:
185///
186/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
187/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
188///
189/// Associative and commutative operators:
190///
191/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
192/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
193/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
194/// if C1 and C2 are constants.
Duncan Sands641baf12010-11-13 15:10:37 +0000195bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000196 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000197 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000198
Duncan Sands641baf12010-11-13 15:10:37 +0000199 do {
200 // Order operands such that they are listed from right (least complex) to
201 // left (most complex). This puts constants before unary operators before
202 // binary operators.
203 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
204 getComplexity(I.getOperand(1)))
205 Changed = !I.swapOperands();
206
207 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
208 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
209
210 if (I.isAssociative()) {
211 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
212 if (Op0 && Op0->getOpcode() == Opcode) {
213 Value *A = Op0->getOperand(0);
214 Value *B = Op0->getOperand(1);
215 Value *C = I.getOperand(1);
216
217 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000218 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000219 // It simplifies to V. Form "A op V".
220 I.setOperand(0, A);
221 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000222 // Conservatively clear the optional flags, since they may not be
223 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000224 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000225 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000226 // Note: this is only valid because SimplifyBinOp doesn't look at
227 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000228 I.clearSubclassOptionalData();
229 I.setHasNoSignedWrap(true);
230 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000231 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000232 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000233
Duncan Sands641baf12010-11-13 15:10:37 +0000234 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000235 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000236 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000237 }
Duncan Sands641baf12010-11-13 15:10:37 +0000238 }
239
240 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
241 if (Op1 && Op1->getOpcode() == Opcode) {
242 Value *A = I.getOperand(0);
243 Value *B = Op1->getOperand(0);
244 Value *C = Op1->getOperand(1);
245
246 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000247 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000248 // It simplifies to V. Form "V op C".
249 I.setOperand(0, V);
250 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000251 // Conservatively clear the optional flags, since they may not be
252 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000253 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000254 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000255 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000256 continue;
257 }
258 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000259 }
Duncan Sands641baf12010-11-13 15:10:37 +0000260
261 if (I.isAssociative() && I.isCommutative()) {
262 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
263 if (Op0 && Op0->getOpcode() == Opcode) {
264 Value *A = Op0->getOperand(0);
265 Value *B = Op0->getOperand(1);
266 Value *C = I.getOperand(1);
267
268 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000269 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000270 // It simplifies to V. Form "V op B".
271 I.setOperand(0, V);
272 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000273 // Conservatively clear the optional flags, since they may not be
274 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000275 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000276 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000277 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000278 continue;
279 }
280 }
281
282 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
283 if (Op1 && Op1->getOpcode() == Opcode) {
284 Value *A = I.getOperand(0);
285 Value *B = Op1->getOperand(0);
286 Value *C = Op1->getOperand(1);
287
288 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000289 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000290 // It simplifies to V. Form "B op V".
291 I.setOperand(0, B);
292 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000293 // Conservatively clear the optional flags, since they may not be
294 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000295 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000296 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000297 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000298 continue;
299 }
300 }
301
302 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
303 // if C1 and C2 are constants.
304 if (Op0 && Op1 &&
305 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
306 isa<Constant>(Op0->getOperand(1)) &&
307 isa<Constant>(Op1->getOperand(1)) &&
308 Op0->hasOneUse() && Op1->hasOneUse()) {
309 Value *A = Op0->getOperand(0);
310 Constant *C1 = cast<Constant>(Op0->getOperand(1));
311 Value *B = Op1->getOperand(0);
312 Constant *C2 = cast<Constant>(Op1->getOperand(1));
313
314 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000315 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000316 if (isa<FPMathOperator>(New)) {
317 FastMathFlags Flags = I.getFastMathFlags();
318 Flags &= Op0->getFastMathFlags();
319 Flags &= Op1->getFastMathFlags();
320 New->setFastMathFlags(Flags);
321 }
Eli Friedman35211c62011-05-27 00:19:40 +0000322 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000323 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000324 I.setOperand(0, New);
325 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000326 // Conservatively clear the optional flags, since they may not be
327 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000328 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000329
Duncan Sands641baf12010-11-13 15:10:37 +0000330 Changed = true;
331 continue;
332 }
333 }
334
335 // No further simplifications.
336 return Changed;
337 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000338}
Chris Lattnerca081252001-12-14 16:52:21 +0000339
Sanjay Patel84dca492015-09-21 15:33:26 +0000340/// Return whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000341/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000342static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
343 Instruction::BinaryOps ROp) {
344 switch (LOp) {
345 default:
346 return false;
347
348 case Instruction::And:
349 // And distributes over Or and Xor.
350 switch (ROp) {
351 default:
352 return false;
353 case Instruction::Or:
354 case Instruction::Xor:
355 return true;
356 }
357
358 case Instruction::Mul:
359 // Multiplication distributes over addition and subtraction.
360 switch (ROp) {
361 default:
362 return false;
363 case Instruction::Add:
364 case Instruction::Sub:
365 return true;
366 }
367
368 case Instruction::Or:
369 // Or distributes over And.
370 switch (ROp) {
371 default:
372 return false;
373 case Instruction::And:
374 return true;
375 }
376 }
377}
378
Sanjay Patel84dca492015-09-21 15:33:26 +0000379/// Return whether "(X LOp Y) ROp Z" is always equal to
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000380/// "(X ROp Z) LOp (Y ROp Z)".
381static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
382 Instruction::BinaryOps ROp) {
383 if (Instruction::isCommutative(ROp))
384 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000385
386 switch (LOp) {
387 default:
388 return false;
389 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
390 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
391 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
392 case Instruction::And:
393 case Instruction::Or:
394 case Instruction::Xor:
395 switch (ROp) {
396 default:
397 return false;
398 case Instruction::Shl:
399 case Instruction::LShr:
400 case Instruction::AShr:
401 return true;
402 }
403 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000404 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
405 // but this requires knowing that the addition does not overflow and other
406 // such subtleties.
407 return false;
408}
409
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000410/// This function returns identity value for given opcode, which can be used to
411/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
412static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
413 if (isa<Constant>(V))
414 return nullptr;
415
416 if (OpCode == Instruction::Mul)
417 return ConstantInt::get(V->getType(), 1);
418
419 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
420
421 return nullptr;
422}
423
424/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000425/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
426/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
427/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
428/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
429/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000430static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000431getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
432 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000433 if (!Op)
434 return Instruction::BinaryOpsEnd;
435
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000436 LHS = Op->getOperand(0);
437 RHS = Op->getOperand(1);
438
439 switch (TopLevelOpcode) {
440 default:
441 return Op->getOpcode();
442
443 case Instruction::Add:
444 case Instruction::Sub:
445 if (Op->getOpcode() == Instruction::Shl) {
446 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
447 // The multiplier is really 1 << CST.
448 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
449 return Instruction::Mul;
450 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000451 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000452 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000453 }
454
455 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000456}
457
458/// This tries to simplify binary operations by factorizing out common terms
459/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
460static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000462 Instruction::BinaryOps InnerOpcode, Value *A,
463 Value *B, Value *C, Value *D) {
464
465 // If any of A, B, C, D are null, we can not factor I, return early.
466 // Checking A and C should be enough.
467 if (!A || !C || !B || !D)
468 return nullptr;
469
David Majnemer4c3753c2015-05-22 23:02:11 +0000470 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000471 Value *SimplifiedInst = nullptr;
472 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
473 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
474
475 // Does "X op' Y" always equal "Y op' X"?
476 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
477
478 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
479 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
480 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
481 // commutative case, "(A op' B) op (C op' A)"?
482 if (A == C || (InnerCommutative && A == D)) {
483 if (A != C)
484 std::swap(C, D);
485 // Consider forming "A op' (B op D)".
486 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000487 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000488 // If "B op D" doesn't simplify then only go on if both of the existing
489 // operations "A op' B" and "C op' D" will be zapped as no longer used.
490 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
491 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
492 if (V) {
493 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
494 }
495 }
496
497 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
498 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
499 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
500 // commutative case, "(A op' B) op (B op' D)"?
501 if (B == D || (InnerCommutative && B == C)) {
502 if (B != D)
503 std::swap(C, D);
504 // Consider forming "(A op C) op' B".
505 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000506 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000507
508 // If "A op C" doesn't simplify then only go on if both of the existing
509 // operations "A op' B" and "C op' D" will be zapped as no longer used.
510 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
511 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
512 if (V) {
513 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
514 }
515 }
516
517 if (SimplifiedInst) {
518 ++NumFactor;
519 SimplifiedInst->takeName(&I);
520
521 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
522 // TODO: Check for NUW.
523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
524 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
525 bool HasNSW = false;
526 if (isa<OverflowingBinaryOperator>(&I))
527 HasNSW = I.hasNoSignedWrap();
528
529 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
530 if (isa<OverflowingBinaryOperator>(Op0))
531 HasNSW &= Op0->hasNoSignedWrap();
532
533 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
534 if (isa<OverflowingBinaryOperator>(Op1))
535 HasNSW &= Op1->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000536
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000537 // We can propagate 'nsw' if we know that
David Majnemer4c3753c2015-05-22 23:02:11 +0000538 // %Y = mul nsw i16 %X, C
539 // %Z = add nsw i16 %Y, %X
540 // =>
541 // %Z = mul nsw i16 %X, C+1
542 //
543 // iff C+1 isn't INT_MIN
544 const APInt *CInt;
545 if (TopLevelOpcode == Instruction::Add &&
546 InnerOpcode == Instruction::Mul)
547 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
548 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000549 }
550 }
551 }
552 return SimplifiedInst;
553}
554
Sanjay Patel84dca492015-09-21 15:33:26 +0000555/// This tries to simplify binary operations which some other binary operation
556/// distributes over either by factorizing out common terms
557/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
558/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
559/// Returns the simplified value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000560Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
562 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
563 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000564
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000565 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000566 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000567 auto TopLevelOpcode = I.getOpcode();
568 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
569 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000570
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000571 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
572 // a common term.
573 if (LHSOpcode == RHSOpcode) {
574 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
575 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000576 }
577
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000578 // The instruction has the form "(A op' B) op (C)". Try to factorize common
579 // term.
580 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
581 getIdentityValue(LHSOpcode, RHS)))
582 return V;
583
584 // The instruction has the form "(B) op (C op' D)". Try to factorize common
585 // term.
586 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
587 getIdentityValue(RHSOpcode, LHS), C, D))
588 return V;
589
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000590 // Expansion.
591 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
592 // The instruction has the form "(A op' B) op C". See if expanding it out
593 // to "(A op C) op' (B op C)" results in simplifications.
594 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
595 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
596
597 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000598 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
599 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000600 // They do! Return "L op' R".
601 ++NumExpand;
602 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
603 if ((L == A && R == B) ||
604 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
605 return Op0;
606 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000607 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000608 return V;
609 // Otherwise, create a new instruction.
610 C = Builder->CreateBinOp(InnerOpcode, L, R);
611 C->takeName(&I);
612 return C;
613 }
614 }
615
616 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
617 // The instruction has the form "A op (B op' C)". See if expanding it out
618 // to "(A op B) op' (A op C)" results in simplifications.
619 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
620 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
621
622 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000623 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
624 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000625 // They do! Return "L op' R".
626 ++NumExpand;
627 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
628 if ((L == B && R == C) ||
629 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
630 return Op1;
631 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000632 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000633 return V;
634 // Otherwise, create a new instruction.
635 A = Builder->CreateBinOp(InnerOpcode, L, R);
636 A->takeName(&I);
637 return A;
638 }
639 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000640
David Majnemer33b6f822015-07-14 22:39:23 +0000641 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
642 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
643 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
644 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
645 if (SI0->getCondition() == SI1->getCondition()) {
646 Value *SI = nullptr;
647 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
648 SI1->getFalseValue(), DL, TLI, DT, AC))
649 SI = Builder->CreateSelect(SI0->getCondition(),
650 Builder->CreateBinOp(TopLevelOpcode,
651 SI0->getTrueValue(),
652 SI1->getTrueValue()),
653 V);
654 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
655 SI1->getTrueValue(), DL, TLI, DT, AC))
656 SI = Builder->CreateSelect(
657 SI0->getCondition(), V,
658 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
659 SI1->getFalseValue()));
660 if (SI) {
661 SI->takeName(&I);
662 return SI;
663 }
664 }
665 }
666 }
667
Craig Topperf40110f2014-04-25 05:29:35 +0000668 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000669}
670
Sanjay Patel84dca492015-09-21 15:33:26 +0000671/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
672/// constant zero (which is the 'negate' form).
Chris Lattner2188e402010-01-04 07:37:31 +0000673Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000674 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000675 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000676
Chris Lattner9ad0d552004-12-14 20:08:06 +0000677 // Constants can be considered to be negated values if they can be folded.
678 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000679 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000680
Chris Lattner8213c8a2012-02-06 21:56:39 +0000681 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
682 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000683 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000684
Craig Topperf40110f2014-04-25 05:29:35 +0000685 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000686}
687
Sanjay Patel84dca492015-09-21 15:33:26 +0000688/// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
689/// a constant negative zero (which is the 'negate' form).
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000690Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
691 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000692 return BinaryOperator::getFNegArgument(V);
693
694 // Constants can be considered to be negated values if they can be folded.
695 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000696 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000697
Chris Lattner8213c8a2012-02-06 21:56:39 +0000698 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
699 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000700 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000701
Craig Topperf40110f2014-04-25 05:29:35 +0000702 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000703}
704
Chris Lattner86102b82005-01-01 16:22:27 +0000705static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000706 InstCombiner *IC) {
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000707 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattnerc8565392009-08-30 20:01:10 +0000708 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000709 }
Chris Lattner86102b82005-01-01 16:22:27 +0000710
Chris Lattner183b3362004-04-09 19:05:30 +0000711 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000712 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
713 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000714
Chris Lattner183b3362004-04-09 19:05:30 +0000715 if (Constant *SOC = dyn_cast<Constant>(SO)) {
716 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000717 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
718 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000719 }
720
721 Value *Op0 = SO, *Op1 = ConstOperand;
722 if (!ConstIsRHS)
723 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000724
Owen Anderson1664dc82014-01-20 07:44:53 +0000725 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) {
726 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
Chris Lattner022a5822009-08-30 07:44:24 +0000727 SO->getName()+".op");
Owen Anderson1664dc82014-01-20 07:44:53 +0000728 Instruction *FPInst = dyn_cast<Instruction>(RI);
729 if (FPInst && isa<FPMathOperator>(FPInst))
730 FPInst->copyFastMathFlags(BO);
731 return RI;
732 }
Chris Lattner022a5822009-08-30 07:44:24 +0000733 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
734 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
735 SO->getName()+".cmp");
736 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
737 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
738 SO->getName()+".cmp");
739 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner86102b82005-01-01 16:22:27 +0000740}
741
Sanjay Patel84dca492015-09-21 15:33:26 +0000742/// Given an instruction with a select as one operand and a constant as the
743/// other operand, try to fold the binary operator into the select arguments.
744/// This also works for Cast instructions, which obviously do not have a second
745/// operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000746Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Chris Lattner86102b82005-01-01 16:22:27 +0000747 // Don't modify shared select instructions
Craig Topperf40110f2014-04-25 05:29:35 +0000748 if (!SI->hasOneUse()) return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000749 Value *TV = SI->getOperand(1);
750 Value *FV = SI->getOperand(2);
751
752 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000753 // Bool selects with constant operands can be folded to logical ops.
Craig Topperf40110f2014-04-25 05:29:35 +0000754 if (SI->getType()->isIntegerTy(1)) return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000755
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000756 // If it's a bitcast involving vectors, make sure it has the same number of
757 // elements on both sides.
758 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000759 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
760 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000761
762 // Verify that either both or neither are vectors.
Craig Topperf40110f2014-04-25 05:29:35 +0000763 if ((SrcTy == nullptr) != (DestTy == nullptr)) return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000764 // If vectors, verify that they have the same number of elements.
765 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
Craig Topperf40110f2014-04-25 05:29:35 +0000766 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000767 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000768
James Molloy2b21a7c2015-05-20 18:41:25 +0000769 // Test if a CmpInst instruction is used exclusively by a select as
770 // part of a minimum or maximum operation. If so, refrain from doing
771 // any other folding. This helps out other analyses which understand
772 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
773 // and CodeGen. And in this case, at least one of the comparison
774 // operands has at least one user besides the compare (the select),
775 // which would often largely negate the benefit of folding anyway.
776 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
777 if (CI->hasOneUse()) {
778 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
779 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
780 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
781 return nullptr;
782 }
783 }
784
Chris Lattner2b295a02010-01-04 07:53:58 +0000785 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
786 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
Chris Lattner86102b82005-01-01 16:22:27 +0000787
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000788 return SelectInst::Create(SI->getCondition(),
789 SelectTrueVal, SelectFalseVal);
Chris Lattner86102b82005-01-01 16:22:27 +0000790 }
Craig Topperf40110f2014-04-25 05:29:35 +0000791 return nullptr;
Chris Lattner183b3362004-04-09 19:05:30 +0000792}
793
Sanjay Patel84dca492015-09-21 15:33:26 +0000794/// Given a binary operator, cast instruction, or select which has a PHI node as
795/// operand #0, see if we can fold the instruction into the PHI (which is only
796/// possible if all operands to the PHI are constants).
Chris Lattnerea7131a2011-01-16 05:14:26 +0000797Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000798 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000799 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000800 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000801 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000802
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000803 // We normally only transform phis with a single use. However, if a PHI has
804 // multiple uses and they are all the same operation, we can fold *all* of the
805 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000806 if (!PN->hasOneUse()) {
807 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000808 for (User *U : PN->users()) {
809 Instruction *UI = cast<Instruction>(U);
810 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000811 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000812 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000813 // Otherwise, we can replace *all* users with the new PHI we form.
814 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000815
Chris Lattnerfacb8672009-09-27 19:57:57 +0000816 // Check to see if all of the operands of the PHI are simple constants
817 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000818 // remember the BB it is in. If there is more than one or if *it* is a PHI,
819 // bail out. We don't do arbitrary constant expressions here because moving
820 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000821 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000822 for (unsigned i = 0; i != NumPHIValues; ++i) {
823 Value *InVal = PN->getIncomingValue(i);
824 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
825 continue;
826
Craig Topperf40110f2014-04-25 05:29:35 +0000827 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
828 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000829
Chris Lattner25ce2802011-01-16 04:37:29 +0000830 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000831
832 // If the InVal is an invoke at the end of the pred block, then we can't
833 // insert a computation after it without breaking the edge.
834 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
835 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000836 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000837
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000838 // If the incoming non-constant value is in I's block, we will remove one
839 // instruction, but insert another equivalent one, leading to infinite
840 // instcombine.
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000841 if (isPotentiallyReachable(I.getParent(), NonConstBB, DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000842 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000843 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000844
Chris Lattner04689872006-09-09 22:02:56 +0000845 // If there is exactly one non-constant value, we can insert a copy of the
846 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000847 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000848 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000849 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000850 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000851 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000852 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000853
854 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000855 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000856 InsertNewInstBefore(NewPN, *PN);
857 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000858
Chris Lattnerff2e7372011-01-16 05:08:00 +0000859 // If we are going to have to insert a new computation, do so right before the
Sanjay Patel41c739b2015-09-11 19:29:18 +0000860 // predecessor's terminator.
Chris Lattnerff2e7372011-01-16 05:08:00 +0000861 if (NonConstBB)
862 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000863
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000864 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000865 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
866 // We only currently try to fold the condition of a select when it is a phi,
867 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000868 Value *TrueV = SI->getTrueValue();
869 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000870 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000871 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000872 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000873 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
874 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000875 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000876 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
877 // even if currently isNullValue gives false.
878 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
879 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000880 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000881 else
882 InV = Builder->CreateSelect(PN->getIncomingValue(i),
883 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000884 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000885 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000886 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
887 Constant *C = cast<Constant>(I.getOperand(1));
888 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000889 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000890 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
891 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
892 else if (isa<ICmpInst>(CI))
893 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
894 C, "phitmp");
895 else
896 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
897 C, "phitmp");
898 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
899 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000900 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000901 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000902 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000903 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000904 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
905 InV = ConstantExpr::get(I.getOpcode(), InC, C);
906 else
907 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
908 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000909 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000910 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000911 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000912 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000913 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000914 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000915 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000916 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000917 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000918 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000919 InV = Builder->CreateCast(CI->getOpcode(),
920 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000921 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000922 }
923 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000924
Chandler Carruthcdf47882014-03-09 03:16:01 +0000925 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000926 Instruction *User = cast<Instruction>(*UI++);
927 if (User == &I) continue;
Sanjay Patel4b198802016-02-01 22:23:39 +0000928 replaceInstUsesWith(*User, NewPN);
929 eraseInstFromFunction(*User);
Chris Lattnerd55581d2011-01-16 05:28:59 +0000930 }
Sanjay Patel4b198802016-02-01 22:23:39 +0000931 return replaceInstUsesWith(I, NewPN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000932}
933
Sanjay Patel84dca492015-09-21 15:33:26 +0000934/// Given a pointer type and a constant offset, determine whether or not there
935/// is a sequence of GEP indices into the pointed type that will land us at the
936/// specified offset. If so, fill them into NewIndices and return the resultant
937/// element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000938Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000939 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000940 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000941 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000942 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000943
Chris Lattnerfef138b2009-01-09 05:44:56 +0000944 // Start with the index over the outer type. Note that the type size
945 // might be zero (even if the offset isn't zero) if the indexed type
946 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000948 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000949 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000950 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000951 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000952
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000953 // Handle hosts where % returns negative instead of values [0..TySize).
954 if (Offset < 0) {
955 --FirstIdx;
956 Offset += TySize;
957 assert(Offset >= 0);
958 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000959 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
960 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000961
Owen Andersonedb4a702009-07-24 23:12:02 +0000962 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000963
Chris Lattnerfef138b2009-01-09 05:44:56 +0000964 // Index into the types. If we fail, set OrigBase to null.
965 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000966 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +0000968 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000969
Chris Lattner229907c2011-07-18 04:54:35 +0000970 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000971 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +0000972 assert(Offset < (int64_t)SL->getSizeInBytes() &&
973 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000974
Chris Lattnerfef138b2009-01-09 05:44:56 +0000975 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +0000976 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
977 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000978
Chris Lattnerfef138b2009-01-09 05:44:56 +0000979 Offset -= SL->getElementOffset(Elt);
980 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +0000981 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000982 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +0000983 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +0000984 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +0000985 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +0000986 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +0000987 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +0000988 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +0000989 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000990 }
991 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000992
Chris Lattner72cd68f2009-01-24 01:00:13 +0000993 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +0000994}
995
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +0000996static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
997 // If this GEP has only 0 indices, it is the same pointer as
998 // Src. If Src is not a trivial GEP too, don't combine
999 // the indices.
1000 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1001 !Src.hasOneUse())
1002 return false;
1003 return true;
1004}
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001005
Sanjay Patel84dca492015-09-21 15:33:26 +00001006/// Return a value X such that Val = X * Scale, or null if none.
1007/// If the multiplication is known not to overflow, then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001008Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1009 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1010 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1011 Scale.getBitWidth() && "Scale not compatible with value!");
1012
1013 // If Val is zero or Scale is one then Val = Val * Scale.
1014 if (match(Val, m_Zero()) || Scale == 1) {
1015 NoSignedWrap = true;
1016 return Val;
1017 }
1018
1019 // If Scale is zero then it does not divide Val.
1020 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001021 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001022
1023 // Look through chains of multiplications, searching for a constant that is
1024 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1025 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1026 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1027 // down from Val:
1028 //
1029 // Val = M1 * X || Analysis starts here and works down
1030 // M1 = M2 * Y || Doesn't descend into terms with more
1031 // M2 = Z * 4 \/ than one use
1032 //
1033 // Then to modify a term at the bottom:
1034 //
1035 // Val = M1 * X
1036 // M1 = Z * Y || Replaced M2 with Z
1037 //
1038 // Then to work back up correcting nsw flags.
1039
1040 // Op - the term we are currently analyzing. Starts at Val then drills down.
1041 // Replaced with its descaled value before exiting from the drill down loop.
1042 Value *Op = Val;
1043
1044 // Parent - initially null, but after drilling down notes where Op came from.
1045 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1046 // 0'th operand of Val.
1047 std::pair<Instruction*, unsigned> Parent;
1048
Sanjay Patel84dca492015-09-21 15:33:26 +00001049 // Set if the transform requires a descaling at deeper levels that doesn't
1050 // overflow.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001051 bool RequireNoSignedWrap = false;
1052
Sanjay Patel84dca492015-09-21 15:33:26 +00001053 // Log base 2 of the scale. Negative if not a power of 2.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001054 int32_t logScale = Scale.exactLogBase2();
1055
1056 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1057
1058 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1059 // If Op is a constant divisible by Scale then descale to the quotient.
1060 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1061 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1062 if (!Remainder.isMinValue())
1063 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001064 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001065 // Replace with the quotient in the parent.
1066 Op = ConstantInt::get(CI->getType(), Quotient);
1067 NoSignedWrap = true;
1068 break;
1069 }
1070
1071 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1072
1073 if (BO->getOpcode() == Instruction::Mul) {
1074 // Multiplication.
1075 NoSignedWrap = BO->hasNoSignedWrap();
1076 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001077 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001078
1079 // There are three cases for multiplication: multiplication by exactly
1080 // the scale, multiplication by a constant different to the scale, and
1081 // multiplication by something else.
1082 Value *LHS = BO->getOperand(0);
1083 Value *RHS = BO->getOperand(1);
1084
1085 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1086 // Multiplication by a constant.
1087 if (CI->getValue() == Scale) {
1088 // Multiplication by exactly the scale, replace the multiplication
1089 // by its left-hand side in the parent.
1090 Op = LHS;
1091 break;
1092 }
1093
1094 // Otherwise drill down into the constant.
1095 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001096 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001097
1098 Parent = std::make_pair(BO, 1);
1099 continue;
1100 }
1101
1102 // Multiplication by something else. Drill down into the left-hand side
1103 // since that's where the reassociate pass puts the good stuff.
1104 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001105 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001106
1107 Parent = std::make_pair(BO, 0);
1108 continue;
1109 }
1110
1111 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1112 isa<ConstantInt>(BO->getOperand(1))) {
1113 // Multiplication by a power of 2.
1114 NoSignedWrap = BO->hasNoSignedWrap();
1115 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001116 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001117
1118 Value *LHS = BO->getOperand(0);
1119 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1120 getLimitedValue(Scale.getBitWidth());
1121 // Op = LHS << Amt.
1122
1123 if (Amt == logScale) {
1124 // Multiplication by exactly the scale, replace the multiplication
1125 // by its left-hand side in the parent.
1126 Op = LHS;
1127 break;
1128 }
1129 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001130 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001131
1132 // Multiplication by more than the scale. Reduce the multiplying amount
1133 // by the scale in the parent.
1134 Parent = std::make_pair(BO, 1);
1135 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1136 break;
1137 }
1138 }
1139
1140 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001141 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001142
1143 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1144 if (Cast->getOpcode() == Instruction::SExt) {
1145 // Op is sign-extended from a smaller type, descale in the smaller type.
1146 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1147 APInt SmallScale = Scale.trunc(SmallSize);
1148 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1149 // descale Op as (sext Y) * Scale. In order to have
1150 // sext (Y * SmallScale) = (sext Y) * Scale
1151 // some conditions need to hold however: SmallScale must sign-extend to
1152 // Scale and the multiplication Y * SmallScale should not overflow.
1153 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1154 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001155 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001156 assert(SmallScale.exactLogBase2() == logScale);
1157 // Require that Y * SmallScale must not overflow.
1158 RequireNoSignedWrap = true;
1159
1160 // Drill down through the cast.
1161 Parent = std::make_pair(Cast, 0);
1162 Scale = SmallScale;
1163 continue;
1164 }
1165
Duncan Sands5ed39002012-10-23 09:07:02 +00001166 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001167 // Op is truncated from a larger type, descale in the larger type.
1168 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1169 // trunc (Y * sext Scale) = (trunc Y) * Scale
1170 // always holds. However (trunc Y) * Scale may overflow even if
1171 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1172 // from this point up in the expression (see later).
1173 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001174 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001175
1176 // Drill down through the cast.
1177 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1178 Parent = std::make_pair(Cast, 0);
1179 Scale = Scale.sext(LargeSize);
1180 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1181 logScale = -1;
1182 assert(Scale.exactLogBase2() == logScale);
1183 continue;
1184 }
1185 }
1186
1187 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001188 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001189 }
1190
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001191 // If Op is zero then Val = Op * Scale.
1192 if (match(Op, m_Zero())) {
1193 NoSignedWrap = true;
1194 return Op;
1195 }
1196
Duncan Sands533c8ae2012-10-23 08:28:26 +00001197 // We know that we can successfully descale, so from here on we can safely
1198 // modify the IR. Op holds the descaled version of the deepest term in the
1199 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1200 // not to overflow.
1201
1202 if (!Parent.first)
1203 // The expression only had one term.
1204 return Op;
1205
1206 // Rewrite the parent using the descaled version of its operand.
1207 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1208 assert(Op != Parent.first->getOperand(Parent.second) &&
1209 "Descaling was a no-op?");
1210 Parent.first->setOperand(Parent.second, Op);
1211 Worklist.Add(Parent.first);
1212
1213 // Now work back up the expression correcting nsw flags. The logic is based
1214 // on the following observation: if X * Y is known not to overflow as a signed
1215 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1216 // then X * Z will not overflow as a signed multiplication either. As we work
1217 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1218 // current level has strictly smaller absolute value than the original.
1219 Instruction *Ancestor = Parent.first;
1220 do {
1221 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1222 // If the multiplication wasn't nsw then we can't say anything about the
1223 // value of the descaled multiplication, and we have to clear nsw flags
1224 // from this point on up.
1225 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1226 NoSignedWrap &= OpNoSignedWrap;
1227 if (NoSignedWrap != OpNoSignedWrap) {
1228 BO->setHasNoSignedWrap(NoSignedWrap);
1229 Worklist.Add(Ancestor);
1230 }
1231 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1232 // The fact that the descaled input to the trunc has smaller absolute
1233 // value than the original input doesn't tell us anything useful about
1234 // the absolute values of the truncations.
1235 NoSignedWrap = false;
1236 }
1237 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1238 "Failed to keep proper track of nsw flags while drilling down?");
1239
1240 if (Ancestor == Val)
1241 // Got to the top, all done!
1242 return Val;
1243
1244 // Move up one level in the expression.
1245 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001246 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001247 } while (1);
1248}
1249
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001250/// \brief Creates node of binary operation with the same attributes as the
1251/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001252static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1253 InstCombiner::BuilderTy *B) {
Sanjay Patel968e91a2015-11-24 17:51:20 +00001254 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1255 // If LHS and RHS are constant, BO won't be a binary operator.
1256 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1257 NewBO->copyIRFlags(&Inst);
1258 return BO;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001259}
1260
1261/// \brief Makes transformation of binary operation specific for vector types.
1262/// \param Inst Binary operator to transform.
1263/// \return Pointer to node that must replace the original binary operator, or
1264/// null pointer if no transformation was made.
1265Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1266 if (!Inst.getType()->isVectorTy()) return nullptr;
1267
Sanjay Patel58814442014-07-09 16:34:54 +00001268 // It may not be safe to reorder shuffles and things like div, urem, etc.
1269 // because we may trap when executing those ops on unknown vector elements.
1270 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001271 if (!isSafeToSpeculativelyExecute(&Inst))
1272 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001273
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001274 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1275 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1276 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1277 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1278
1279 // If both arguments of binary operation are shuffles, which use the same
1280 // mask and shuffle within a single vector, it is worthwhile to move the
1281 // shuffle after binary operation:
1282 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1283 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1284 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1285 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1286 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1287 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001288 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001289 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001290 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001291 RShuf->getOperand(0), Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001292 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001293 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001294 }
1295 }
1296
1297 // If one argument is a shuffle within one vector, the other is a constant,
1298 // try moving the shuffle after the binary operation.
1299 ShuffleVectorInst *Shuffle = nullptr;
1300 Constant *C1 = nullptr;
1301 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1302 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1303 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1304 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001305 if (Shuffle && C1 &&
1306 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1307 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001308 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1309 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1310 // Find constant C2 that has property:
1311 // shuffle(C2, ShMask) = C1
1312 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1313 // reorder is not possible.
1314 SmallVector<Constant*, 16> C2M(VWidth,
1315 UndefValue::get(C1->getType()->getScalarType()));
1316 bool MayChange = true;
1317 for (unsigned I = 0; I < VWidth; ++I) {
1318 if (ShMask[I] >= 0) {
1319 assert(ShMask[I] < (int)VWidth);
1320 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1321 MayChange = false;
1322 break;
1323 }
1324 C2M[ShMask[I]] = C1->getAggregateElement(I);
1325 }
1326 }
1327 if (MayChange) {
1328 Constant *C2 = ConstantVector::get(C2M);
Sanjay Patel04df5832015-11-21 16:51:19 +00001329 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1330 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
Serge Pavlove6de9e32014-05-14 09:05:09 +00001331 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001332 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001333 UndefValue::get(Inst.getType()), Shuffle->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001334 }
1335 }
1336
1337 return nullptr;
1338}
1339
Chris Lattner113f4f42002-06-25 16:13:24 +00001340Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001341 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1342
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00001343 if (Value *V = SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001344 return replaceInstUsesWith(GEP, V);
Chris Lattner8574aba2009-11-27 00:29:05 +00001345
Chris Lattner5f667a62004-05-07 22:09:22 +00001346 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001347
Duncan Sandsc133c542010-11-22 16:32:50 +00001348 // Eliminate unneeded casts for indices, and replace indices which displace
1349 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001350 bool MadeChange = false;
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001351 Type *IntPtrTy =
1352 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001353
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001354 gep_type_iterator GTI = gep_type_begin(GEP);
1355 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1356 ++I, ++GTI) {
1357 // Skip indices into struct types.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001358 if (isa<StructType>(*GTI))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001359 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001360
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001361 // Index type should have the same width as IntPtr
1362 Type *IndexTy = (*I)->getType();
1363 Type *NewIndexType = IndexTy->isVectorTy() ?
1364 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001365
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001366 // If the element type has zero size then any index over it is equivalent
1367 // to an index of zero, so replace it with zero if it is not zero already.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001368 Type *EltTy = GTI.getIndexedType();
1369 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001370 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001371 *I = Constant::getNullValue(NewIndexType);
Duncan Sandsc133c542010-11-22 16:32:50 +00001372 MadeChange = true;
1373 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001374
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001375 if (IndexTy != NewIndexType) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001376 // If we are using a wider index than needed for this platform, shrink
1377 // it to what we need. If narrower, sign-extend it to what we need.
1378 // This explicit cast can make subsequent optimizations more obvious.
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001379 *I = Builder->CreateIntCast(*I, NewIndexType, true);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001380 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001381 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001382 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001383 if (MadeChange)
1384 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001385
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001386 // Check to see if the inputs to the PHI node are getelementptr instructions.
1387 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1388 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1389 if (!Op1)
1390 return nullptr;
1391
Daniel Jasper5add63f2015-03-19 11:05:08 +00001392 // Don't fold a GEP into itself through a PHI node. This can only happen
1393 // through the back-edge of a loop. Folding a GEP into itself means that
1394 // the value of the previous iteration needs to be stored in the meantime,
1395 // thus requiring an additional register variable to be live, but not
1396 // actually achieving anything (the GEP still needs to be executed once per
1397 // loop iteration).
1398 if (Op1 == &GEP)
1399 return nullptr;
1400
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001401 signed DI = -1;
1402
1403 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1404 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1405 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1406 return nullptr;
1407
Daniel Jasper5add63f2015-03-19 11:05:08 +00001408 // As for Op1 above, don't try to fold a GEP into itself.
1409 if (Op2 == &GEP)
1410 return nullptr;
1411
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001412 // Keep track of the type as we walk the GEP.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001413 Type *CurTy = nullptr;
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001414
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001415 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1416 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1417 return nullptr;
1418
1419 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1420 if (DI == -1) {
1421 // We have not seen any differences yet in the GEPs feeding the
1422 // PHI yet, so we record this one if it is allowed to be a
1423 // variable.
1424
1425 // The first two arguments can vary for any GEP, the rest have to be
1426 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001427 if (J > 1 && CurTy->isStructTy())
1428 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001429
1430 DI = J;
1431 } else {
1432 // The GEP is different by more than one input. While this could be
1433 // extended to support GEPs that vary by more than one variable it
1434 // doesn't make sense since it greatly increases the complexity and
1435 // would result in an R+R+R addressing mode which no backend
1436 // directly supports and would need to be broken into several
1437 // simpler instructions anyway.
1438 return nullptr;
1439 }
1440 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001441
1442 // Sink down a layer of the type for the next iteration.
1443 if (J > 0) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001444 if (J == 1) {
1445 CurTy = Op1->getSourceElementType();
1446 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001447 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1448 } else {
1449 CurTy = nullptr;
1450 }
1451 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001452 }
1453 }
1454
Silviu Barangab892e352015-10-26 10:25:05 +00001455 // If not all GEPs are identical we'll have to create a new PHI node.
1456 // Check that the old PHI node has only one use so that it will get
1457 // removed.
1458 if (DI != -1 && !PN->hasOneUse())
1459 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001460
Silviu Barangab892e352015-10-26 10:25:05 +00001461 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001462 if (DI == -1) {
1463 // All the GEPs feeding the PHI are identical. Clone one down into our
1464 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001465 GEP.getParent()->getInstList().insert(
1466 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001467 } else {
1468 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1469 // into the current block so it can be merged, and create a new PHI to
1470 // set that index.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001471 PHINode *NewPN;
1472 {
1473 IRBuilderBase::InsertPointGuard Guard(*Builder);
1474 Builder->SetInsertPoint(PN);
1475 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1476 PN->getNumOperands());
1477 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001478
1479 for (auto &I : PN->operands())
1480 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1481 PN->getIncomingBlock(I));
1482
1483 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001484 GEP.getParent()->getInstList().insert(
1485 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001486 NewGEP->setOperand(DI, NewPN);
1487 }
1488
1489 GEP.setOperand(0, NewGEP);
1490 PtrOp = NewGEP;
1491 }
1492
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001493 // Combine Indices - If the source pointer to this getelementptr instruction
1494 // is a getelementptr instruction, combine the indices of the two
1495 // getelementptr instructions into a single instruction.
1496 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001497 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001498 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001499 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001500
Duncan Sands533c8ae2012-10-23 08:28:26 +00001501 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001502 // chain to be resolved before we perform this transformation. This
1503 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001504 if (GEPOperator *SrcGEP =
1505 dyn_cast<GEPOperator>(Src->getOperand(0)))
1506 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001507 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001508
Chris Lattneraf6094f2007-02-15 22:48:32 +00001509 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001510
1511 // Find out whether the last index in the source GEP is a sequential idx.
1512 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001513 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1514 I != E; ++I)
Duncan Sands19d0b472010-02-16 11:11:14 +00001515 EndsWithSequential = !(*I)->isStructTy();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001516
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001517 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001518 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001519 // Replace: gep (gep %P, long B), long A, ...
1520 // With: T = long A+B; gep %P, T, ...
1521 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001522 Value *Sum;
1523 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1524 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001525 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001526 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001527 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001528 Sum = SO1;
1529 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001530 // If they aren't the same type, then the input hasn't been processed
1531 // by the loop above yet (which canonicalizes sequential index types to
1532 // intptr_t). Just avoid transforming this until the input has been
1533 // normalized.
1534 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001535 return nullptr;
Wei Mia0adf9f2015-04-21 23:02:15 +00001536 // Only do the combine when GO1 and SO1 are both constants. Only in
1537 // this case, we are sure the cost after the merge is never more than
1538 // that before the merge.
1539 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1540 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001541 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001542 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001543
Chris Lattnerb2995e12009-08-30 05:30:55 +00001544 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001545 if (Src->getNumOperands() == 2) {
1546 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001547 GEP.setOperand(1, Sum);
1548 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001549 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001550 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001551 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001552 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001553 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001554 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001555 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001556 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001557 Indices.append(Src->op_begin()+1, Src->op_end());
1558 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001559 }
1560
Dan Gohman1b849082009-09-07 23:54:19 +00001561 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001562 return GEP.isInBounds() && Src->isInBounds()
1563 ? GetElementPtrInst::CreateInBounds(
1564 Src->getSourceElementType(), Src->getOperand(0), Indices,
1565 GEP.getName())
1566 : GetElementPtrInst::Create(Src->getSourceElementType(),
1567 Src->getOperand(0), Indices,
1568 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001569 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001570
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001571 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001572 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001573 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001574 DL.getPointerSizeInBits(AS)) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001575 Type *Ty = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001576 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001577
1578 bool Matched = false;
1579 uint64_t C;
1580 Value *V = nullptr;
1581 if (TyAllocSize == 1) {
1582 V = GEP.getOperand(1);
1583 Matched = true;
1584 } else if (match(GEP.getOperand(1),
1585 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1586 if (TyAllocSize == 1ULL << C)
1587 Matched = true;
1588 } else if (match(GEP.getOperand(1),
1589 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1590 if (TyAllocSize == C)
1591 Matched = true;
1592 }
1593
1594 if (Matched) {
1595 // Canonicalize (gep i8* X, -(ptrtoint Y))
1596 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1597 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1598 // pointer arithmetic.
1599 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1600 Operator *Index = cast<Operator>(V);
1601 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1602 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1603 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1604 }
1605 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1606 // to (bitcast Y)
1607 Value *Y;
1608 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1609 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1610 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1611 GEP.getType());
1612 }
1613 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001614 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001615 }
1616
Chris Lattner06c687b2009-08-30 05:08:50 +00001617 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001618 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001619 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1620
Nadav Rotema8f35622012-03-26 21:00:53 +00001621 // We do not handle pointer-vector geps here.
1622 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001623 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001624
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001625 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001626 bool HasZeroPointerIndex = false;
1627 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1628 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001629
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001630 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1631 // into : GEP [10 x i8]* X, i32 0, ...
1632 //
1633 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1634 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001635 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001636 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001637 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001638 if (ArrayType *CATy =
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001639 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
Duncan Sands5795a602009-03-02 09:18:21 +00001640 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001641 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001642 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001643 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001644 GetElementPtrInst *Res = GetElementPtrInst::Create(
1645 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001646 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001647 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1648 return Res;
1649 // Insert Res, and create an addrspacecast.
1650 // e.g.,
1651 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1652 // ->
1653 // %0 = GEP i8 addrspace(1)* X, ...
1654 // addrspacecast i8 addrspace(1)* %0 to i8*
1655 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001656 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001657
Chris Lattner229907c2011-07-18 04:54:35 +00001658 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001659 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001660 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001661 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001662 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001663 // At this point, we know that the cast source type is a pointer
1664 // to an array of the same type as the destination pointer
1665 // array. Because the array type is never stepped over (there
1666 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001667 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1668 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001669 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001670 return &GEP;
1671 }
1672 // Cannot replace the base pointer directly because StrippedPtr's
1673 // address space is different. Instead, create a new GEP followed by
1674 // an addrspacecast.
1675 // e.g.,
1676 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1677 // i32 0, ...
1678 // ->
1679 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1680 // addrspacecast i8 addrspace(1)* %0 to i8*
1681 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001682 Value *NewGEP = GEP.isInBounds()
1683 ? Builder->CreateInBoundsGEP(
1684 nullptr, StrippedPtr, Idx, GEP.getName())
1685 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1686 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001687 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001688 }
Duncan Sands5795a602009-03-02 09:18:21 +00001689 }
1690 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001691 } else if (GEP.getNumOperands() == 2) {
1692 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001693 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1694 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001695 Type *SrcElTy = StrippedPtrTy->getElementType();
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001696 Type *ResElTy = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001697 if (SrcElTy->isArrayTy() &&
1698 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1699 DL.getTypeAllocSize(ResElTy)) {
1700 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001701 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001702 Value *NewGEP =
1703 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001704 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1705 GEP.getName())
1706 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001707
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001708 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001709 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1710 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001711 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001712
Chris Lattner2a893292005-09-13 18:36:04 +00001713 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001714 // %V = mul i64 %N, 4
1715 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1716 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001717 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001718 // Check that changing the type amounts to dividing the index by a scale
1719 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001720 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1721 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001722 if (ResSize && SrcSize % ResSize == 0) {
1723 Value *Idx = GEP.getOperand(1);
1724 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1725 uint64_t Scale = SrcSize / ResSize;
1726
1727 // Earlier transforms ensure that the index has type IntPtrType, which
1728 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001729 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001730 "Index not cast to pointer width?");
1731
1732 bool NSW;
1733 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1734 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1735 // If the multiplication NewIdx * Scale may overflow then the new
1736 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001737 Value *NewGEP =
1738 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001739 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001740 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001741 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1742 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001743
Duncan Sands533c8ae2012-10-23 08:28:26 +00001744 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001745 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1746 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001747 }
1748 }
1749 }
1750
1751 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001752 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001753 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001754 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001755 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001756 // Check that changing to the array element type amounts to dividing the
1757 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001758 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1759 uint64_t ArrayEltSize =
1760 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001761 if (ResSize && ArrayEltSize % ResSize == 0) {
1762 Value *Idx = GEP.getOperand(1);
1763 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1764 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001765
Duncan Sands533c8ae2012-10-23 08:28:26 +00001766 // Earlier transforms ensure that the index has type IntPtrType, which
1767 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001768 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001769 "Index not cast to pointer width?");
1770
1771 bool NSW;
1772 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1773 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1774 // If the multiplication NewIdx * Scale may overflow then the new
1775 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001776 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001777 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1778 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001779
David Blaikieaa41cd52015-04-03 21:33:42 +00001780 Value *NewGEP = GEP.isInBounds() && NSW
1781 ? Builder->CreateInBoundsGEP(
1782 SrcElTy, StrippedPtr, Off, GEP.getName())
1783 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1784 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001785 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001786 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1787 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001788 }
1789 }
Chris Lattner2a893292005-09-13 18:36:04 +00001790 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001791 }
Chris Lattnerca081252001-12-14 16:52:21 +00001792 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001793
Matt Arsenault4815f092014-08-12 19:46:13 +00001794 // addrspacecast between types is canonicalized as a bitcast, then an
1795 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1796 // through the addrspacecast.
1797 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1798 // X = bitcast A addrspace(1)* to B addrspace(1)*
1799 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1800 // Z = gep Y, <...constant indices...>
1801 // Into an addrspacecasted GEP of the struct.
1802 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1803 PtrOp = BC;
1804 }
1805
Chris Lattnerfef138b2009-01-09 05:44:56 +00001806 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001807 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001808 /// Y = gep X, <...constant indices...>
1809 /// into a gep of the original struct. This is important for SROA and alias
1810 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001811 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001812 Value *Operand = BCI->getOperand(0);
1813 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001814 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001815 APInt Offset(OffsetBits, 0);
1816 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001817 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001818
Chris Lattnerfef138b2009-01-09 05:44:56 +00001819 // If this GEP instruction doesn't move the pointer, just replace the GEP
1820 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001821 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001822 // If the bitcast is of an allocation, and the allocation will be
1823 // converted to match the type of the cast, don't touch this.
Matt Arsenault98f34e32013-08-19 22:17:34 +00001824 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001825 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1826 if (Instruction *I = visitBitCast(*BCI)) {
1827 if (I != BCI) {
1828 I->takeName(BCI);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001829 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
Sanjay Patel4b198802016-02-01 22:23:39 +00001830 replaceInstUsesWith(*BCI, I);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001831 }
1832 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001833 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001834 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001835
1836 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1837 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001838 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001839 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001840
Chris Lattnerfef138b2009-01-09 05:44:56 +00001841 // Otherwise, if the offset is non-zero, we need to find out if there is a
1842 // field at Offset in 'A's type. If so, we can pull the cast through the
1843 // GEP.
1844 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001845 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001846 Value *NGEP =
1847 GEP.isInBounds()
1848 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1849 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001850
Chris Lattner59663412009-08-30 18:50:58 +00001851 if (NGEP->getType() == GEP.getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001852 return replaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001853 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001854
1855 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1856 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001857 return new BitCastInst(NGEP, GEP.getType());
1858 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001859 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001860 }
1861
Craig Topperf40110f2014-04-25 05:29:35 +00001862 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001863}
1864
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001865static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1866 Instruction *AI) {
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001867 if (isa<ConstantPointerNull>(V))
1868 return true;
1869 if (auto *LI = dyn_cast<LoadInst>(V))
1870 return isa<GlobalVariable>(LI->getPointerOperand());
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001871 // Two distinct allocations will never be equal.
1872 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1873 // through bitcasts of V can cause
1874 // the result statement below to be true, even when AI and V (ex:
1875 // i8* ->i32* ->i8* of AI) are the same allocations.
1876 return isAllocLikeFn(V, TLI) && V != AI;
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001877}
1878
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001879static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001880isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1881 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001882 SmallVector<Instruction*, 4> Worklist;
1883 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001884
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001885 do {
1886 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001887 for (User *U : PI->users()) {
1888 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001889 switch (I->getOpcode()) {
1890 default:
1891 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001892 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001893
1894 case Instruction::BitCast:
1895 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001896 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001897 Worklist.push_back(I);
1898 continue;
1899
1900 case Instruction::ICmp: {
1901 ICmpInst *ICI = cast<ICmpInst>(I);
1902 // We can fold eq/ne comparisons with null to false/true, respectively.
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001903 // We also fold comparisons in some conditions provided the alloc has
Anna Thomas95f68aa2016-04-25 13:58:05 +00001904 // not escaped (see isNeverEqualToUnescapedAlloc).
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001905 if (!ICI->isEquality())
1906 return false;
1907 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001908 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001909 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001910 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001911 continue;
1912 }
1913
1914 case Instruction::Call:
1915 // Ignore no-op and store intrinsics.
1916 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1917 switch (II->getIntrinsicID()) {
1918 default:
1919 return false;
1920
1921 case Intrinsic::memmove:
1922 case Intrinsic::memcpy:
1923 case Intrinsic::memset: {
1924 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1925 if (MI->isVolatile() || MI->getRawDest() != PI)
1926 return false;
1927 }
1928 // fall through
1929 case Intrinsic::dbg_declare:
1930 case Intrinsic::dbg_value:
1931 case Intrinsic::invariant_start:
1932 case Intrinsic::invariant_end:
1933 case Intrinsic::lifetime_start:
1934 case Intrinsic::lifetime_end:
1935 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001936 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001937 continue;
1938 }
1939 }
1940
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001941 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001942 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001943 continue;
1944 }
1945 return false;
1946
1947 case Instruction::Store: {
1948 StoreInst *SI = cast<StoreInst>(I);
1949 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1950 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001951 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001952 continue;
1953 }
1954 }
1955 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001956 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001957 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00001958 return true;
1959}
1960
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001961Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00001962 // If we have a malloc call which is only used in any amount of comparisons
1963 // to null and free calls, delete the calls and replace the comparisons with
1964 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00001965 SmallVector<WeakVH, 64> Users;
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001966 if (isAllocSiteRemovable(&MI, Users, TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00001967 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
Petar Jovanovic921c2b42016-03-09 14:12:47 +00001968 // Lowering all @llvm.objectsize calls first because they may
1969 // use a bitcast/GEP of the alloca we are removing.
1970 if (!Users[i])
1971 continue;
1972
1973 Instruction *I = cast<Instruction>(&*Users[i]);
1974
1975 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1976 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1977 uint64_t Size;
1978 if (!getObjectSize(II->getArgOperand(0), Size, DL, TLI)) {
1979 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1980 Size = CI->isZero() ? -1ULL : 0;
1981 }
1982 replaceInstUsesWith(*I, ConstantInt::get(I->getType(), Size));
1983 eraseInstFromFunction(*I);
1984 Users[i] = nullptr; // Skip examining in the next loop.
1985 }
1986 }
1987 }
1988 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1989 if (!Users[i])
1990 continue;
1991
1992 Instruction *I = cast<Instruction>(&*Users[i]);
Duncan Sandsf162eac2010-05-27 19:09:06 +00001993
Nick Lewycky50f49662011-08-03 00:43:35 +00001994 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001995 replaceInstUsesWith(*C,
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001996 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1997 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00001998 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001999 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sandsf162eac2010-05-27 19:09:06 +00002000 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002001 eraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002002 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002003
2004 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00002005 // Replace invoke with a NOP intrinsic to maintain the original CFG
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002006 Module *M = II->getModule();
Nuno Lopes9ac46612012-06-28 22:31:24 +00002007 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2008 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00002009 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002010 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002011 return eraseInstFromFunction(MI);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002012 }
Craig Topperf40110f2014-04-25 05:29:35 +00002013 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00002014}
2015
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002016/// \brief Move the call to free before a NULL test.
2017///
2018/// Check if this free is accessed after its argument has been test
2019/// against NULL (property 0).
2020/// If yes, it is legal to move this call in its predecessor block.
2021///
2022/// The move is performed only if the block containing the call to free
2023/// will be removed, i.e.:
2024/// 1. it has only one predecessor P, and P has two successors
2025/// 2. it contains the call and an unconditional branch
2026/// 3. its successor is the same as its predecessor's successor
2027///
2028/// The profitability is out-of concern here and this function should
2029/// be called only if the caller knows this transformation would be
2030/// profitable (e.g., for code size).
2031static Instruction *
2032tryToMoveFreeBeforeNullTest(CallInst &FI) {
2033 Value *Op = FI.getArgOperand(0);
2034 BasicBlock *FreeInstrBB = FI.getParent();
2035 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2036
2037 // Validate part of constraint #1: Only one predecessor
2038 // FIXME: We can extend the number of predecessor, but in that case, we
2039 // would duplicate the call to free in each predecessor and it may
2040 // not be profitable even for code size.
2041 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00002042 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002043
2044 // Validate constraint #2: Does this block contains only the call to
2045 // free and an unconditional branch?
2046 // FIXME: We could check if we can speculate everything in the
2047 // predecessor block
2048 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002049 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002050 BasicBlock *SuccBB;
2051 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002052 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002053
2054 // Validate the rest of constraint #1 by matching on the pred branch.
2055 TerminatorInst *TI = PredBB->getTerminator();
2056 BasicBlock *TrueBB, *FalseBB;
2057 ICmpInst::Predicate Pred;
2058 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002059 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002060 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002061 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002062
2063 // Validate constraint #3: Ensure the null case just falls through.
2064 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002065 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002066 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2067 "Broken CFG: missing edge from predecessor to successor");
2068
2069 FI.moveBefore(TI);
2070 return &FI;
2071}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002072
2073
Gabor Greif75f69432010-06-24 12:21:15 +00002074Instruction *InstCombiner::visitFree(CallInst &FI) {
2075 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002076
2077 // free undef -> unreachable.
2078 if (isa<UndefValue>(Op)) {
2079 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002080 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2081 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Sanjay Patel4b198802016-02-01 22:23:39 +00002082 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002083 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002084
Victor Hernandeze2971492009-10-24 04:23:03 +00002085 // If we have 'free null' delete the instruction. This can happen in stl code
2086 // when lots of inlining happens.
2087 if (isa<ConstantPointerNull>(Op))
Sanjay Patel4b198802016-02-01 22:23:39 +00002088 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002089
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002090 // If we optimize for code size, try to move the call to free before the null
2091 // test so that simplify cfg can remove the empty block and dead code
2092 // elimination the branch. I.e., helps to turn something like:
2093 // if (foo) free(foo);
2094 // into
2095 // free(foo);
2096 if (MinimizeSize)
2097 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2098 return I;
2099
Craig Topperf40110f2014-04-25 05:29:35 +00002100 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002101}
Chris Lattner8427bff2003-12-07 01:24:23 +00002102
Hal Finkel93873cc12014-09-07 21:28:34 +00002103Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2104 if (RI.getNumOperands() == 0) // ret void
2105 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002106
Hal Finkel93873cc12014-09-07 21:28:34 +00002107 Value *ResultOp = RI.getOperand(0);
2108 Type *VTy = ResultOp->getType();
2109 if (!VTy->isIntegerTy())
2110 return nullptr;
2111
2112 // There might be assume intrinsics dominating this return that completely
2113 // determine the value. If so, constant fold it.
2114 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2115 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2116 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2117 if ((KnownZero|KnownOne).isAllOnesValue())
2118 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2119
2120 return nullptr;
2121}
Chris Lattner31f486c2005-01-31 05:36:43 +00002122
Chris Lattner9eef8a72003-06-04 04:46:00 +00002123Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2124 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002125 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002126 BasicBlock *TrueDest;
2127 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002128 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002129 !isa<Constant>(X)) {
2130 // Swap Destinations and condition...
2131 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002132 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002133 return &BI;
2134 }
2135
Philip Reames71c40352015-03-10 22:52:37 +00002136 // If the condition is irrelevant, remove the use so that other
2137 // transforms on the condition become more effective.
2138 if (BI.isConditional() &&
2139 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2140 !isa<UndefValue>(BI.getCondition())) {
2141 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2142 return &BI;
2143 }
2144
Alp Tokercb402912014-01-24 17:20:08 +00002145 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002146 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002147 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002148 TrueDest, FalseDest)) &&
2149 BI.getCondition()->hasOneUse())
2150 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2151 FPred == FCmpInst::FCMP_OGE) {
2152 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2153 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002154
Chris Lattner905976b2009-08-30 06:13:40 +00002155 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002156 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002157 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002158 return &BI;
2159 }
2160
Alp Tokercb402912014-01-24 17:20:08 +00002161 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002162 ICmpInst::Predicate IPred;
2163 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002164 TrueDest, FalseDest)) &&
2165 BI.getCondition()->hasOneUse())
2166 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2167 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2168 IPred == ICmpInst::ICMP_SGE) {
2169 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2170 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2171 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002172 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002173 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002174 return &BI;
2175 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002176
Craig Topperf40110f2014-04-25 05:29:35 +00002177 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002178}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002179
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002180Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2181 Value *Cond = SI.getCondition();
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002182 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2183 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002184 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002185 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2186 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2187
2188 // Compute the number of leading bits we can ignore.
2189 for (auto &C : SI.cases()) {
2190 LeadingKnownZeros = std::min(
2191 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2192 LeadingKnownOnes = std::min(
2193 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2194 }
2195
2196 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2197
2198 // Truncate the condition operand if the new type is equal to or larger than
2199 // the largest legal integer type. We need to be conservative here since
Sanjay Patel6a248112015-06-23 23:26:22 +00002200 // x86 generates redundant zero-extension instructions if the operand is
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002201 // truncated to i8 or i16.
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002202 bool TruncCond = false;
Owen Anderson58364dc2015-03-10 06:51:39 +00002203 if (NewWidth > 0 && BitWidth > NewWidth &&
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00002204 NewWidth >= DL.getLargestLegalIntTypeSizeInBits()) {
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002205 TruncCond = true;
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002206 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2207 Builder->SetInsertPoint(&SI);
2208 Value *NewCond = Builder->CreateTrunc(SI.getCondition(), Ty, "trunc");
2209 SI.setCondition(NewCond);
2210
2211 for (auto &C : SI.cases())
2212 static_cast<SwitchInst::CaseIt *>(&C)->setValue(ConstantInt::get(
2213 SI.getContext(), C.getCaseValue()->getValue().trunc(NewWidth)));
2214 }
2215
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002216 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
2217 if (I->getOpcode() == Instruction::Add)
2218 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2219 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
Eli Friedman95031ed2011-09-29 20:21:17 +00002220 // Skip the first item since that's the default case.
Stepan Dyatkovskiy97b02fc2012-03-11 06:09:17 +00002221 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002222 i != e; ++i) {
2223 ConstantInt* CaseVal = i.getCaseValue();
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002224 Constant *LHS = CaseVal;
2225 if (TruncCond)
2226 LHS = LeadingKnownZeros
2227 ? ConstantExpr::getZExt(CaseVal, Cond->getType())
2228 : ConstantExpr::getSExt(CaseVal, Cond->getType());
2229 Constant* NewCaseVal = ConstantExpr::getSub(LHS, AddRHS);
Eli Friedman95031ed2011-09-29 20:21:17 +00002230 assert(isa<ConstantInt>(NewCaseVal) &&
2231 "Result of expression should be constant");
Stepan Dyatkovskiy5b648af2012-03-08 07:06:20 +00002232 i.setValue(cast<ConstantInt>(NewCaseVal));
Eli Friedman95031ed2011-09-29 20:21:17 +00002233 }
2234 SI.setCondition(I->getOperand(0));
Chris Lattner905976b2009-08-30 06:13:40 +00002235 Worklist.Add(I);
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002236 return &SI;
2237 }
2238 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002239
2240 return TruncCond ? &SI : nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002241}
2242
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002243Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002244 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002245
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002246 if (!EV.hasIndices())
Sanjay Patel4b198802016-02-01 22:23:39 +00002247 return replaceInstUsesWith(EV, Agg);
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002248
David Majnemer25a796e2015-07-13 01:15:46 +00002249 if (Value *V =
2250 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002251 return replaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002252
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002253 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2254 // We're extracting from an insertvalue instruction, compare the indices
2255 const unsigned *exti, *exte, *insi, *inse;
2256 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2257 exte = EV.idx_end(), inse = IV->idx_end();
2258 exti != exte && insi != inse;
2259 ++exti, ++insi) {
2260 if (*insi != *exti)
2261 // The insert and extract both reference distinctly different elements.
2262 // This means the extract is not influenced by the insert, and we can
2263 // replace the aggregate operand of the extract with the aggregate
2264 // operand of the insert. i.e., replace
2265 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2266 // %E = extractvalue { i32, { i32 } } %I, 0
2267 // with
2268 // %E = extractvalue { i32, { i32 } } %A, 0
2269 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002270 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002271 }
2272 if (exti == exte && insi == inse)
2273 // Both iterators are at the end: Index lists are identical. Replace
2274 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2275 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2276 // with "i32 42"
Sanjay Patel4b198802016-02-01 22:23:39 +00002277 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002278 if (exti == exte) {
2279 // The extract list is a prefix of the insert list. i.e. replace
2280 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2281 // %E = extractvalue { i32, { i32 } } %I, 1
2282 // with
2283 // %X = extractvalue { i32, { i32 } } %A, 1
2284 // %E = insertvalue { i32 } %X, i32 42, 0
2285 // by switching the order of the insert and extract (though the
2286 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002287 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002288 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002289 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002290 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002291 }
2292 if (insi == inse)
2293 // The insert list is a prefix of the extract list
2294 // We can simply remove the common indices from the extract and make it
2295 // operate on the inserted value instead of the insertvalue result.
2296 // i.e., replace
2297 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2298 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2299 // with
2300 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002301 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002302 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002303 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002304 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2305 // We're extracting from an intrinsic, see if we're the only user, which
2306 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002307 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002308 if (II->hasOneUse()) {
2309 // Check if we're grabbing the overflow bit or the result of a 'with
2310 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2311 // and replace it with a traditional binary instruction.
2312 switch (II->getIntrinsicID()) {
2313 case Intrinsic::uadd_with_overflow:
2314 case Intrinsic::sadd_with_overflow:
2315 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002316 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002317 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2318 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002319 return BinaryOperator::CreateAdd(LHS, RHS);
2320 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002321
Chris Lattner3e635d22010-12-19 19:43:52 +00002322 // If the normal result of the add is dead, and the RHS is a constant,
2323 // we can transform this into a range comparison.
2324 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002325 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2326 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2327 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2328 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002329 break;
2330 case Intrinsic::usub_with_overflow:
2331 case Intrinsic::ssub_with_overflow:
2332 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002333 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002334 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2335 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002336 return BinaryOperator::CreateSub(LHS, RHS);
2337 }
2338 break;
2339 case Intrinsic::umul_with_overflow:
2340 case Intrinsic::smul_with_overflow:
2341 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002342 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002343 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2344 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002345 return BinaryOperator::CreateMul(LHS, RHS);
2346 }
2347 break;
2348 default:
2349 break;
2350 }
2351 }
2352 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002353 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2354 // If the (non-volatile) load only has one use, we can rewrite this to a
Mehdi Amini1c131b32015-12-15 01:44:07 +00002355 // load from a GEP. This reduces the size of the load. If a load is used
2356 // only by extractvalue instructions then this either must have been
2357 // optimized before, or it is a struct with padding, in which case we
2358 // don't want to do the transformation as it loses padding knowledge.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002359 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002360 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2361 SmallVector<Value*, 4> Indices;
2362 // Prefix an i32 0 since we need the first element.
2363 Indices.push_back(Builder->getInt32(0));
2364 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2365 I != E; ++I)
2366 Indices.push_back(Builder->getInt32(*I));
2367
2368 // We need to insert these at the location of the old load, not at that of
2369 // the extractvalue.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002370 Builder->SetInsertPoint(L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002371 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2372 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002373 // Returning the load directly will cause the main loop to insert it in
Sanjay Patel4b198802016-02-01 22:23:39 +00002374 // the wrong spot, so use replaceInstUsesWith().
2375 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
Frits van Bommel28218aa2010-11-29 21:56:20 +00002376 }
2377 // We could simplify extracts from other values. Note that nested extracts may
2378 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002379 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002380 // the value inserted, if appropriate. Similarly for extracts from single-use
2381 // loads: extract (extract (load)) will be translated to extract (load (gep))
2382 // and if again single-use then via load (gep (gep)) to load (gep).
2383 // However, double extracts from e.g. function arguments or return values
2384 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002385 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002386}
2387
Sanjay Patel84dca492015-09-21 15:33:26 +00002388/// Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002389static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002390 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002391 case EHPersonality::GNU_C:
Bjorn Steinbrink37ca4622016-03-15 20:57:07 +00002392 case EHPersonality::Rust:
2393 // The GCC C EH and Rust personality only exists to support cleanups, so
2394 // it's not clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002395 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002396 case EHPersonality::Unknown:
2397 return false;
2398 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002399 // While __gnat_all_others_value will match any Ada exception, it doesn't
2400 // match foreign exceptions (or didn't, before gcc-4.7).
2401 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002402 case EHPersonality::GNU_CXX:
2403 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002404 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002405 case EHPersonality::MSVC_Win64SEH:
2406 case EHPersonality::MSVC_CXX:
Joseph Tremoulet2afea542015-10-06 20:28:16 +00002407 case EHPersonality::CoreCLR:
Duncan Sands5c055792011-09-30 13:12:16 +00002408 return TypeInfo->isNullValue();
2409 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002410 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002411}
2412
2413static bool shorter_filter(const Value *LHS, const Value *RHS) {
2414 return
2415 cast<ArrayType>(LHS->getType())->getNumElements()
2416 <
2417 cast<ArrayType>(RHS->getType())->getNumElements();
2418}
2419
2420Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2421 // The logic here should be correct for any real-world personality function.
2422 // However if that turns out not to be true, the offending logic can always
2423 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002424 EHPersonality Personality =
2425 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002426
2427 // Simplify the list of clauses, eg by removing repeated catch clauses
2428 // (these are often created by inlining).
2429 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002430 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002431 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2432
2433 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2434 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2435 bool isLastClause = i + 1 == e;
2436 if (LI.isCatch(i)) {
2437 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002438 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002439 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002440
2441 // If we already saw this clause, there is no point in having a second
2442 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002443 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002444 // This catch clause was not already seen.
2445 NewClauses.push_back(CatchClause);
2446 } else {
2447 // Repeated catch clause - drop the redundant copy.
2448 MakeNewInstruction = true;
2449 }
2450
2451 // If this is a catch-all then there is no point in keeping any following
2452 // clauses or marking the landingpad as having a cleanup.
2453 if (isCatchAll(Personality, TypeInfo)) {
2454 if (!isLastClause)
2455 MakeNewInstruction = true;
2456 CleanupFlag = false;
2457 break;
2458 }
2459 } else {
2460 // A filter clause. If any of the filter elements were already caught
2461 // then they can be dropped from the filter. It is tempting to try to
2462 // exploit the filter further by saying that any typeinfo that does not
2463 // occur in the filter can't be caught later (and thus can be dropped).
2464 // However this would be wrong, since typeinfos can match without being
2465 // equal (for example if one represents a C++ class, and the other some
2466 // class derived from it).
2467 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002468 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002469 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2470 unsigned NumTypeInfos = FilterType->getNumElements();
2471
2472 // An empty filter catches everything, so there is no point in keeping any
2473 // following clauses or marking the landingpad as having a cleanup. By
2474 // dealing with this case here the following code is made a bit simpler.
2475 if (!NumTypeInfos) {
2476 NewClauses.push_back(FilterClause);
2477 if (!isLastClause)
2478 MakeNewInstruction = true;
2479 CleanupFlag = false;
2480 break;
2481 }
2482
2483 bool MakeNewFilter = false; // If true, make a new filter.
2484 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2485 if (isa<ConstantAggregateZero>(FilterClause)) {
2486 // Not an empty filter - it contains at least one null typeinfo.
2487 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2488 Constant *TypeInfo =
2489 Constant::getNullValue(FilterType->getElementType());
2490 // If this typeinfo is a catch-all then the filter can never match.
2491 if (isCatchAll(Personality, TypeInfo)) {
2492 // Throw the filter away.
2493 MakeNewInstruction = true;
2494 continue;
2495 }
2496
2497 // There is no point in having multiple copies of this typeinfo, so
2498 // discard all but the first copy if there is more than one.
2499 NewFilterElts.push_back(TypeInfo);
2500 if (NumTypeInfos > 1)
2501 MakeNewFilter = true;
2502 } else {
2503 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2504 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2505 NewFilterElts.reserve(NumTypeInfos);
2506
2507 // Remove any filter elements that were already caught or that already
2508 // occurred in the filter. While there, see if any of the elements are
2509 // catch-alls. If so, the filter can be discarded.
2510 bool SawCatchAll = false;
2511 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002512 Constant *Elt = Filter->getOperand(j);
2513 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002514 if (isCatchAll(Personality, TypeInfo)) {
2515 // This element is a catch-all. Bail out, noting this fact.
2516 SawCatchAll = true;
2517 break;
2518 }
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002519
2520 // Even if we've seen a type in a catch clause, we don't want to
2521 // remove it from the filter. An unexpected type handler may be
2522 // set up for a call site which throws an exception of the same
2523 // type caught. In order for the exception thrown by the unexpected
2524 // handler to propogate correctly, the filter must be correctly
2525 // described for the call site.
2526 //
2527 // Example:
2528 //
2529 // void unexpected() { throw 1;}
2530 // void foo() throw (int) {
2531 // std::set_unexpected(unexpected);
2532 // try {
2533 // throw 2.0;
2534 // } catch (int i) {}
2535 // }
2536
Duncan Sands5c055792011-09-30 13:12:16 +00002537 // There is no point in having multiple copies of the same typeinfo in
2538 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002539 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002540 NewFilterElts.push_back(cast<Constant>(Elt));
2541 }
2542 // A filter containing a catch-all cannot match anything by definition.
2543 if (SawCatchAll) {
2544 // Throw the filter away.
2545 MakeNewInstruction = true;
2546 continue;
2547 }
2548
2549 // If we dropped something from the filter, make a new one.
2550 if (NewFilterElts.size() < NumTypeInfos)
2551 MakeNewFilter = true;
2552 }
2553 if (MakeNewFilter) {
2554 FilterType = ArrayType::get(FilterType->getElementType(),
2555 NewFilterElts.size());
2556 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2557 MakeNewInstruction = true;
2558 }
2559
2560 NewClauses.push_back(FilterClause);
2561
2562 // If the new filter is empty then it will catch everything so there is
2563 // no point in keeping any following clauses or marking the landingpad
2564 // as having a cleanup. The case of the original filter being empty was
2565 // already handled above.
2566 if (MakeNewFilter && !NewFilterElts.size()) {
2567 assert(MakeNewInstruction && "New filter but not a new instruction!");
2568 CleanupFlag = false;
2569 break;
2570 }
2571 }
2572 }
2573
2574 // If several filters occur in a row then reorder them so that the shortest
2575 // filters come first (those with the smallest number of elements). This is
2576 // advantageous because shorter filters are more likely to match, speeding up
2577 // unwinding, but mostly because it increases the effectiveness of the other
2578 // filter optimizations below.
2579 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2580 unsigned j;
2581 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2582 for (j = i; j != e; ++j)
2583 if (!isa<ArrayType>(NewClauses[j]->getType()))
2584 break;
2585
2586 // Check whether the filters are already sorted by length. We need to know
2587 // if sorting them is actually going to do anything so that we only make a
2588 // new landingpad instruction if it does.
2589 for (unsigned k = i; k + 1 < j; ++k)
2590 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2591 // Not sorted, so sort the filters now. Doing an unstable sort would be
2592 // correct too but reordering filters pointlessly might confuse users.
2593 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2594 shorter_filter);
2595 MakeNewInstruction = true;
2596 break;
2597 }
2598
2599 // Look for the next batch of filters.
2600 i = j + 1;
2601 }
2602
2603 // If typeinfos matched if and only if equal, then the elements of a filter L
2604 // that occurs later than a filter F could be replaced by the intersection of
2605 // the elements of F and L. In reality two typeinfos can match without being
2606 // equal (for example if one represents a C++ class, and the other some class
2607 // derived from it) so it would be wrong to perform this transform in general.
2608 // However the transform is correct and useful if F is a subset of L. In that
2609 // case L can be replaced by F, and thus removed altogether since repeating a
2610 // filter is pointless. So here we look at all pairs of filters F and L where
2611 // L follows F in the list of clauses, and remove L if every element of F is
2612 // an element of L. This can occur when inlining C++ functions with exception
2613 // specifications.
2614 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2615 // Examine each filter in turn.
2616 Value *Filter = NewClauses[i];
2617 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2618 if (!FTy)
2619 // Not a filter - skip it.
2620 continue;
2621 unsigned FElts = FTy->getNumElements();
2622 // Examine each filter following this one. Doing this backwards means that
2623 // we don't have to worry about filters disappearing under us when removed.
2624 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2625 Value *LFilter = NewClauses[j];
2626 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2627 if (!LTy)
2628 // Not a filter - skip it.
2629 continue;
2630 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2631 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002632 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002633 // If Filter is empty then it is a subset of LFilter.
2634 if (!FElts) {
2635 // Discard LFilter.
2636 NewClauses.erase(J);
2637 MakeNewInstruction = true;
2638 // Move on to the next filter.
2639 continue;
2640 }
2641 unsigned LElts = LTy->getNumElements();
2642 // If Filter is longer than LFilter then it cannot be a subset of it.
2643 if (FElts > LElts)
2644 // Move on to the next filter.
2645 continue;
2646 // At this point we know that LFilter has at least one element.
2647 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002648 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002649 // already know that Filter is not longer than LFilter).
2650 if (isa<ConstantAggregateZero>(Filter)) {
2651 assert(FElts <= LElts && "Should have handled this case earlier!");
2652 // Discard LFilter.
2653 NewClauses.erase(J);
2654 MakeNewInstruction = true;
2655 }
2656 // Move on to the next filter.
2657 continue;
2658 }
2659 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2660 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2661 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002662 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002663 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2664 for (unsigned l = 0; l != LElts; ++l)
2665 if (LArray->getOperand(l)->isNullValue()) {
2666 // LFilter contains a zero - discard it.
2667 NewClauses.erase(J);
2668 MakeNewInstruction = true;
2669 break;
2670 }
2671 // Move on to the next filter.
2672 continue;
2673 }
2674 // At this point we know that both filters are ConstantArrays. Loop over
2675 // operands to see whether every element of Filter is also an element of
2676 // LFilter. Since filters tend to be short this is probably faster than
2677 // using a method that scales nicely.
2678 ConstantArray *FArray = cast<ConstantArray>(Filter);
2679 bool AllFound = true;
2680 for (unsigned f = 0; f != FElts; ++f) {
2681 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2682 AllFound = false;
2683 for (unsigned l = 0; l != LElts; ++l) {
2684 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2685 if (LTypeInfo == FTypeInfo) {
2686 AllFound = true;
2687 break;
2688 }
2689 }
2690 if (!AllFound)
2691 break;
2692 }
2693 if (AllFound) {
2694 // Discard LFilter.
2695 NewClauses.erase(J);
2696 MakeNewInstruction = true;
2697 }
2698 // Move on to the next filter.
2699 }
2700 }
2701
2702 // If we changed any of the clauses, replace the old landingpad instruction
2703 // with a new one.
2704 if (MakeNewInstruction) {
2705 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002706 NewClauses.size());
2707 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2708 NLI->addClause(NewClauses[i]);
2709 // A landing pad with no clauses must have the cleanup flag set. It is
2710 // theoretically possible, though highly unlikely, that we eliminated all
2711 // clauses. If so, force the cleanup flag to true.
2712 if (NewClauses.empty())
2713 CleanupFlag = true;
2714 NLI->setCleanup(CleanupFlag);
2715 return NLI;
2716 }
2717
2718 // Even if none of the clauses changed, we may nonetheless have understood
2719 // that the cleanup flag is pointless. Clear it if so.
2720 if (LI.isCleanup() != CleanupFlag) {
2721 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2722 LI.setCleanup(CleanupFlag);
2723 return &LI;
2724 }
2725
Craig Topperf40110f2014-04-25 05:29:35 +00002726 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002727}
2728
Sanjay Patel84dca492015-09-21 15:33:26 +00002729/// Try to move the specified instruction from its current block into the
2730/// beginning of DestBlock, which can only happen if it's safe to move the
2731/// instruction past all of the instructions between it and the end of its
2732/// block.
Chris Lattner39c98bb2004-12-08 23:43:58 +00002733static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2734 assert(I->hasOneUse() && "Invariants didn't hold!");
2735
Bill Wendlinge86965e2011-08-15 21:14:31 +00002736 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002737 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002738 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002739 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002740
Chris Lattner39c98bb2004-12-08 23:43:58 +00002741 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002742 if (isa<AllocaInst>(I) && I->getParent() ==
2743 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002744 return false;
2745
David Majnemerfe3f9d12016-04-01 17:28:17 +00002746 // Do not sink into catchswitch blocks.
2747 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2748 return false;
2749
Fiona Glasera8b653a2015-11-03 22:23:39 +00002750 // Do not sink convergent call instructions.
2751 if (auto *CI = dyn_cast<CallInst>(I)) {
2752 if (CI->isConvergent())
2753 return false;
2754 }
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002755 // We can only sink load instructions if there is nothing between the load and
2756 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002757 if (I->mayReadFromMemory()) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002758 for (BasicBlock::iterator Scan = I->getIterator(),
2759 E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002760 Scan != E; ++Scan)
2761 if (Scan->mayWriteToMemory())
2762 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002763 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002764
Bill Wendling8ddfc092011-08-16 20:45:24 +00002765 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002766 I->moveBefore(&*InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002767 ++NumSunkInst;
2768 return true;
2769}
2770
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002771bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002772 while (!Worklist.isEmpty()) {
2773 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002774 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002775
Chris Lattner1443bc52006-05-11 17:11:52 +00002776 // Check to see if we can DCE the instruction.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002777 if (isInstructionTriviallyDead(I, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002778 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Sanjay Patel4b198802016-02-01 22:23:39 +00002779 eraseInstFromFunction(*I);
Chris Lattner905976b2009-08-30 06:13:40 +00002780 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002781 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002782 continue;
2783 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002784
Chris Lattner1443bc52006-05-11 17:11:52 +00002785 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002786 if (!I->use_empty() &&
2787 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002788 if (Constant *C = ConstantFoldInstruction(I, DL, TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002789 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002790
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002791 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002792 replaceInstUsesWith(*I, C);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002793 ++NumConstProp;
Sanjay Patel4b198802016-02-01 22:23:39 +00002794 eraseInstFromFunction(*I);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002795 MadeIRChange = true;
2796 continue;
2797 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002798 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002799
Matthias Braunc31032d2016-03-09 18:47:11 +00002800 // In general, it is possible for computeKnownBits to determine all bits in
2801 // a value even when the operands are not all constants.
2802 if (ExpensiveCombines && !I->use_empty() && I->getType()->isIntegerTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00002803 unsigned BitWidth = I->getType()->getScalarSizeInBits();
2804 APInt KnownZero(BitWidth, 0);
2805 APInt KnownOne(BitWidth, 0);
2806 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2807 if ((KnownZero | KnownOne).isAllOnesValue()) {
2808 Constant *C = ConstantInt::get(I->getContext(), KnownOne);
2809 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2810 " from: " << *I << '\n');
2811
2812 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002813 replaceInstUsesWith(*I, C);
Hal Finkelf2199b22015-10-23 20:37:08 +00002814 ++NumConstProp;
Sanjay Patel4b198802016-02-01 22:23:39 +00002815 eraseInstFromFunction(*I);
Hal Finkelf2199b22015-10-23 20:37:08 +00002816 MadeIRChange = true;
2817 continue;
2818 }
2819 }
2820
Chris Lattner39c98bb2004-12-08 23:43:58 +00002821 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002822 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002823 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002824 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002825 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002826
Chris Lattner6b9044d2009-10-14 15:21:58 +00002827 // Get the block the use occurs in.
2828 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002829 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002830 else
2831 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002832
Chris Lattner39c98bb2004-12-08 23:43:58 +00002833 if (UserParent != BB) {
2834 bool UserIsSuccessor = false;
2835 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002836 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2837 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002838 UserIsSuccessor = true;
2839 break;
2840 }
2841
2842 // If the user is one of our immediate successors, and if that successor
2843 // only has us as a predecessors (we'd have to split the critical edge
2844 // otherwise), we can keep going.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002845 if (UserIsSuccessor && UserParent->getSinglePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002846 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002847 if (TryToSinkInstruction(I, UserParent)) {
David Majnemerfe3f9d12016-04-01 17:28:17 +00002848 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002849 MadeIRChange = true;
2850 // We'll add uses of the sunk instruction below, but since sinking
2851 // can expose opportunities for it's *operands* add them to the
2852 // worklist
2853 for (Use &U : I->operands())
2854 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2855 Worklist.Add(OpI);
2856 }
2857 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002858 }
2859 }
2860
Chris Lattner022a5822009-08-30 07:44:24 +00002861 // Now that we have an instruction, try combining it to simplify it.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002862 Builder->SetInsertPoint(I);
Eli Friedman96254a02011-05-18 01:28:27 +00002863 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002864
Reid Spencer755d0e72007-03-26 17:44:01 +00002865#ifndef NDEBUG
2866 std::string OrigI;
2867#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002868 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002869 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002870
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002871 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002872 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002873 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002874 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002875 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002876 << " New = " << *Result << '\n');
2877
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002878 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002879 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002880 // Everything uses the new instruction now.
2881 I->replaceAllUsesWith(Result);
2882
Jim Grosbache7abae02011-10-05 20:53:43 +00002883 // Move the name to the new instruction first.
2884 Result->takeName(I);
2885
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002886 // Push the new instruction and any users onto the worklist.
2887 Worklist.Add(Result);
2888 Worklist.AddUsersToWorkList(*Result);
2889
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002890 // Insert the new instruction into the basic block...
2891 BasicBlock *InstParent = I->getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002892 BasicBlock::iterator InsertPos = I->getIterator();
Chris Lattner7515cab2004-11-14 19:13:23 +00002893
Eli Friedmana49b8282011-11-01 04:49:29 +00002894 // If we replace a PHI with something that isn't a PHI, fix up the
2895 // insertion point.
2896 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2897 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002898
2899 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002900
Sanjay Patel4b198802016-02-01 22:23:39 +00002901 eraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002902 } else {
Evan Chenga4ed8a52007-03-27 16:44:48 +00002903#ifndef NDEBUG
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002904 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002905 << " New = " << *I << '\n');
Evan Chenga4ed8a52007-03-27 16:44:48 +00002906#endif
Chris Lattner7d2a5392004-03-13 23:54:27 +00002907
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002908 // If the instruction was modified, it's possible that it is now dead.
2909 // if so, remove it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002910 if (isInstructionTriviallyDead(I, TLI)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002911 eraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002912 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002913 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002914 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002915 }
Chris Lattner053c0932002-05-14 15:24:07 +00002916 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002917 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002918 }
2919 }
2920
Chris Lattner97fd3592009-08-30 05:55:36 +00002921 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002922 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002923}
2924
Sanjay Patel84dca492015-09-21 15:33:26 +00002925/// Walk the function in depth-first order, adding all reachable code to the
2926/// worklist.
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002927///
2928/// This has a couple of tricks to make the code faster and more powerful. In
2929/// particular, we constant fold and DCE instructions as we go, to avoid adding
2930/// them to the worklist (this significantly speeds up instcombine on code where
2931/// many instructions are dead or constant). Additionally, if we find a branch
2932/// whose condition is a known constant, we only visit the reachable successors.
2933///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002934static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2935 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002936 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002937 const TargetLibraryInfo *TLI) {
2938 bool MadeIRChange = false;
2939 SmallVector<BasicBlock*, 256> Worklist;
2940 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002941
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002942 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2943 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002944
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002945 do {
2946 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002947
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002948 // We have now visited this block! If we've already been here, ignore it.
2949 if (!Visited.insert(BB).second)
2950 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00002951
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002952 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002953 Instruction *Inst = &*BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00002954
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002955 // DCE instruction if trivially dead.
2956 if (isInstructionTriviallyDead(Inst, TLI)) {
2957 ++NumDeadInst;
2958 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
2959 Inst->eraseFromParent();
2960 continue;
2961 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002962
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002963 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00002964 if (!Inst->use_empty() &&
2965 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002966 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
2967 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
2968 << *Inst << '\n');
2969 Inst->replaceAllUsesWith(C);
2970 ++NumConstProp;
2971 Inst->eraseFromParent();
2972 continue;
2973 }
2974
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002975 // See if we can constant fold its operands.
2976 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
2977 ++i) {
2978 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2979 if (CE == nullptr)
2980 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002981
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002982 Constant *&FoldRes = FoldedConstants[CE];
2983 if (!FoldRes)
2984 FoldRes = ConstantFoldConstantExpression(CE, DL, TLI);
2985 if (!FoldRes)
2986 FoldRes = CE;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002987
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002988 if (FoldRes != CE) {
2989 *i = FoldRes;
2990 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002991 }
2992 }
2993
2994 InstrsForInstCombineWorklist.push_back(Inst);
2995 }
2996
2997 // Recursively visit successors. If this is a branch or switch on a
2998 // constant, only visit the reachable successor.
2999 TerminatorInst *TI = BB->getTerminator();
3000 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3001 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3002 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3003 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3004 Worklist.push_back(ReachableBB);
3005 continue;
3006 }
3007 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3008 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3009 // See if this is an explicit destination.
3010 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3011 i != e; ++i)
3012 if (i.getCaseValue() == Cond) {
3013 BasicBlock *ReachableBB = i.getCaseSuccessor();
3014 Worklist.push_back(ReachableBB);
3015 continue;
3016 }
3017
3018 // Otherwise it is the default destination.
3019 Worklist.push_back(SI->getDefaultDest());
3020 continue;
3021 }
3022 }
3023
Pete Cooperebcd7482015-08-06 20:22:46 +00003024 for (BasicBlock *SuccBB : TI->successors())
3025 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003026 } while (!Worklist.empty());
3027
3028 // Once we've found all of the instructions to add to instcombine's worklist,
3029 // add them in reverse order. This way instcombine will visit from the top
3030 // of the function down. This jives well with the way that it adds all uses
3031 // of instructions to the worklist after doing a transformation, thus avoiding
3032 // some N^2 behavior in pathological cases.
Craig Topper42526d32015-10-22 16:35:56 +00003033 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003034
3035 return MadeIRChange;
3036}
3037
3038/// \brief Populate the IC worklist from a function, and prune any dead basic
3039/// blocks discovered in the process.
3040///
3041/// This also does basic constant propagation and other forward fixing to make
3042/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003043static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003044 TargetLibraryInfo *TLI,
3045 InstCombineWorklist &ICWorklist) {
3046 bool MadeIRChange = false;
3047
3048 // Do a depth-first traversal of the function, populate the worklist with
3049 // the reachable instructions. Ignore blocks that are not reachable. Keep
3050 // track of which blocks we visit.
Matthias Braunb30f2f512016-01-30 01:24:31 +00003051 SmallPtrSet<BasicBlock *, 32> Visited;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003052 MadeIRChange |=
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003053 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003054
3055 // Do a quick scan over the function. If we find any blocks that are
3056 // unreachable, remove any instructions inside of them. This prevents
3057 // the instcombine code from having to deal with some bad special cases.
3058 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003059 if (Visited.count(&*BB))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003060 continue;
3061
David Majnemer35c46d32016-01-24 05:26:18 +00003062 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&*BB);
3063 MadeIRChange |= NumDeadInstInBB > 0;
3064 NumDeadInst += NumDeadInstInBB;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003065 }
3066
3067 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00003068}
3069
Mehdi Amini46a43552015-03-04 18:43:29 +00003070static bool
3071combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003072 AliasAnalysis *AA, AssumptionCache &AC,
3073 TargetLibraryInfo &TLI, DominatorTree &DT,
Matthias Braunc31032d2016-03-09 18:47:11 +00003074 bool ExpensiveCombines = true,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003075 LoopInfo *LI = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003076 auto &DL = F.getParent()->getDataLayout();
Matthias Braunc31032d2016-03-09 18:47:11 +00003077 ExpensiveCombines |= EnableExpensiveCombines;
Chandler Carruth83ba2692015-01-24 04:19:17 +00003078
3079 /// Builder - This is an IRBuilder that automatically inserts new
3080 /// instructions into the worklist when they are created.
Mehdi Aminiba9fba82016-03-13 21:05:13 +00003081 IRBuilder<TargetFolder, InstCombineIRInserter> Builder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003082 F.getContext(), TargetFolder(DL), InstCombineIRInserter(Worklist, &AC));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003083
3084 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3085 // by instcombiner.
3086 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3087
3088 // Iterate while there is work to do.
3089 int Iteration = 0;
3090 for (;;) {
3091 ++Iteration;
3092 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3093 << F.getName() << "\n");
3094
Sanjay Patel24b77d12016-01-31 16:33:33 +00003095 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003096
Matthias Braunc31032d2016-03-09 18:47:11 +00003097 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
3098 AA, &AC, &TLI, &DT, DL, LI);
Sanjay Patel24b77d12016-01-31 16:33:33 +00003099 Changed |= IC.run();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003100
3101 if (!Changed)
3102 break;
3103 }
3104
3105 return DbgDeclaresChanged || Iteration > 1;
3106}
3107
3108PreservedAnalyses InstCombinePass::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +00003109 AnalysisManager<Function> &AM) {
3110 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3111 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3112 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003113
Chandler Carruthb47f8012016-03-11 11:05:24 +00003114 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003115
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003116 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
Matthias Braunc31032d2016-03-09 18:47:11 +00003117 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3118 ExpensiveCombines, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003119 // No changes, all analyses are preserved.
3120 return PreservedAnalyses::all();
3121
3122 // Mark all the analyses that instcombine updates as preserved.
3123 // FIXME: Need a way to preserve CFG analyses here!
3124 PreservedAnalyses PA;
3125 PA.preserve<DominatorTreeAnalysis>();
3126 return PA;
3127}
3128
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003129void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3130 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003131 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003132 AU.addRequired<AssumptionCacheTracker>();
3133 AU.addRequired<TargetLibraryInfoWrapperPass>();
3134 AU.addRequired<DominatorTreeWrapperPass>();
3135 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +00003136 AU.addPreserved<AAResultsWrapperPass>();
3137 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003138 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003139}
3140
3141bool InstructionCombiningPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00003142 if (skipFunction(F))
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003143 return false;
3144
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003145 // Required analyses.
Chandler Carruth7b560d42015-09-09 17:55:00 +00003146 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003147 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003148 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3149 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003150
3151 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003152 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3153 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3154
Matthias Braunc31032d2016-03-09 18:47:11 +00003155 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3156 ExpensiveCombines, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003157}
3158
3159char InstructionCombiningPass::ID = 0;
3160INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3161 "Combine redundant instructions", false, false)
3162INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3163INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3164INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +00003165INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3166INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003167INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3168 "Combine redundant instructions", false, false)
3169
3170// Initialization Routines
3171void llvm::initializeInstCombine(PassRegistry &Registry) {
3172 initializeInstructionCombiningPassPass(Registry);
3173}
3174
3175void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3176 initializeInstructionCombiningPassPass(*unwrap(R));
3177}
3178
Matthias Braunc31032d2016-03-09 18:47:11 +00003179FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3180 return new InstructionCombiningPass(ExpensiveCombines);
Chris Lattner04805fa2002-02-26 21:46:54 +00003181}