blob: 0d29c1dceea1da91c0c6b955bf9ce67b0b9c98f7 [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);
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000129 if (!OBO || !OBO->hasNoSignedWrap())
Nick Lewyckyde492782011-08-14 01:45:19 +0000130 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000131
132 // We reason about Add and Sub Only.
133 Instruction::BinaryOps Opcode = I.getOpcode();
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000134 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
Nick Lewyckyde492782011-08-14 01:45:19 +0000135 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000136
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000137 const APInt *BVal, *CVal;
138 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
Nick Lewyckyde492782011-08-14 01:45:19 +0000139 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000140
Nick Lewyckyde492782011-08-14 01:45:19 +0000141 bool Overflow = false;
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000142 if (Opcode == Instruction::Add)
143 BVal->sadd_ov(*CVal, Overflow);
144 else
145 BVal->ssub_ov(*CVal, Overflow);
Nick Lewyckyde492782011-08-14 01:45:19 +0000146
147 return !Overflow;
148}
149
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000150/// Conservatively clears subclassOptionalData after a reassociation or
151/// commutation. We preserve fast-math flags when applicable as they can be
152/// preserved.
153static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
154 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
155 if (!FPMO) {
156 I.clearSubclassOptionalData();
157 return;
158 }
159
160 FastMathFlags FMF = I.getFastMathFlags();
161 I.clearSubclassOptionalData();
162 I.setFastMathFlags(FMF);
163}
164
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000165/// Combine constant operands of associative operations either before or after a
166/// cast to eliminate one of the associative operations:
167/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
168/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
169static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
170 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
171 if (!Cast || !Cast->hasOneUse())
172 return false;
173
174 // TODO: Enhance logic for other casts and remove this check.
175 auto CastOpcode = Cast->getOpcode();
176 if (CastOpcode != Instruction::ZExt)
177 return false;
178
179 // TODO: Enhance logic for other BinOps and remove this check.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000180 if (!BinOp1->isBitwiseLogicOp())
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000181 return false;
182
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000183 auto AssocOpcode = BinOp1->getOpcode();
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000184 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
185 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
186 return false;
187
188 Constant *C1, *C2;
189 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
190 !match(BinOp2->getOperand(1), m_Constant(C2)))
191 return false;
192
193 // TODO: This assumes a zext cast.
194 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
195 // to the destination type might lose bits.
196
197 // Fold the constants together in the destination type:
198 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
199 Type *DestTy = C1->getType();
200 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
201 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
202 Cast->setOperand(0, BinOp2->getOperand(0));
203 BinOp1->setOperand(1, FoldedC);
204 return true;
205}
206
Sanjay Patel84dca492015-09-21 15:33:26 +0000207/// This performs a few simplifications for operators that are associative or
208/// commutative:
209///
210/// Commutative operators:
211///
212/// 1. Order operands such that they are listed from right (least complex) to
213/// left (most complex). This puts constants before unary operators before
214/// binary operators.
215///
216/// Associative operators:
217///
218/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
219/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
220///
221/// Associative and commutative operators:
222///
223/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
224/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
225/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
226/// if C1 and C2 are constants.
Duncan Sands641baf12010-11-13 15:10:37 +0000227bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000229 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000230
Duncan Sands641baf12010-11-13 15:10:37 +0000231 do {
232 // Order operands such that they are listed from right (least complex) to
233 // left (most complex). This puts constants before unary operators before
234 // binary operators.
235 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
236 getComplexity(I.getOperand(1)))
237 Changed = !I.swapOperands();
238
239 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
240 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
241
242 if (I.isAssociative()) {
243 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
244 if (Op0 && Op0->getOpcode() == Opcode) {
245 Value *A = Op0->getOperand(0);
246 Value *B = Op0->getOperand(1);
247 Value *C = I.getOperand(1);
248
249 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000250 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000251 // It simplifies to V. Form "A op V".
252 I.setOperand(0, A);
253 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000254 // Conservatively clear the optional flags, since they may not be
255 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000256 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000257 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000258 // Note: this is only valid because SimplifyBinOp doesn't look at
259 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000260 I.clearSubclassOptionalData();
261 I.setHasNoSignedWrap(true);
262 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000263 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000264 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000265
Duncan Sands641baf12010-11-13 15:10:37 +0000266 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000267 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000268 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000269 }
Duncan Sands641baf12010-11-13 15:10:37 +0000270 }
271
272 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
273 if (Op1 && Op1->getOpcode() == Opcode) {
274 Value *A = I.getOperand(0);
275 Value *B = Op1->getOperand(0);
276 Value *C = Op1->getOperand(1);
277
278 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000279 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000280 // It simplifies to V. Form "V op C".
281 I.setOperand(0, V);
282 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000283 // Conservatively clear the optional flags, since they may not be
284 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000285 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000286 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000287 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000288 continue;
289 }
290 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 }
Duncan Sands641baf12010-11-13 15:10:37 +0000292
293 if (I.isAssociative() && I.isCommutative()) {
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000294 if (simplifyAssocCastAssoc(&I)) {
295 Changed = true;
296 ++NumReassoc;
297 continue;
298 }
299
Duncan Sands641baf12010-11-13 15:10:37 +0000300 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
301 if (Op0 && Op0->getOpcode() == Opcode) {
302 Value *A = Op0->getOperand(0);
303 Value *B = Op0->getOperand(1);
304 Value *C = I.getOperand(1);
305
306 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000307 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000308 // It simplifies to V. Form "V op B".
309 I.setOperand(0, V);
310 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000311 // Conservatively clear the optional flags, since they may not be
312 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000313 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000314 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000315 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000316 continue;
317 }
318 }
319
320 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
321 if (Op1 && Op1->getOpcode() == Opcode) {
322 Value *A = I.getOperand(0);
323 Value *B = Op1->getOperand(0);
324 Value *C = Op1->getOperand(1);
325
326 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000327 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000328 // It simplifies to V. Form "B op V".
329 I.setOperand(0, B);
330 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000331 // Conservatively clear the optional flags, since they may not be
332 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000333 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000334 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000335 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000336 continue;
337 }
338 }
339
340 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
341 // if C1 and C2 are constants.
342 if (Op0 && Op1 &&
343 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
344 isa<Constant>(Op0->getOperand(1)) &&
345 isa<Constant>(Op1->getOperand(1)) &&
346 Op0->hasOneUse() && Op1->hasOneUse()) {
347 Value *A = Op0->getOperand(0);
348 Constant *C1 = cast<Constant>(Op0->getOperand(1));
349 Value *B = Op1->getOperand(0);
350 Constant *C2 = cast<Constant>(Op1->getOperand(1));
351
352 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000353 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000354 if (isa<FPMathOperator>(New)) {
355 FastMathFlags Flags = I.getFastMathFlags();
356 Flags &= Op0->getFastMathFlags();
357 Flags &= Op1->getFastMathFlags();
358 New->setFastMathFlags(Flags);
359 }
Eli Friedman35211c62011-05-27 00:19:40 +0000360 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000361 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000362 I.setOperand(0, New);
363 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000364 // Conservatively clear the optional flags, since they may not be
365 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000366 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000367
Duncan Sands641baf12010-11-13 15:10:37 +0000368 Changed = true;
369 continue;
370 }
371 }
372
373 // No further simplifications.
374 return Changed;
375 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000376}
Chris Lattnerca081252001-12-14 16:52:21 +0000377
Sanjay Patel84dca492015-09-21 15:33:26 +0000378/// Return whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000379/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000380static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
381 Instruction::BinaryOps ROp) {
382 switch (LOp) {
383 default:
384 return false;
385
386 case Instruction::And:
387 // And distributes over Or and Xor.
388 switch (ROp) {
389 default:
390 return false;
391 case Instruction::Or:
392 case Instruction::Xor:
393 return true;
394 }
395
396 case Instruction::Mul:
397 // Multiplication distributes over addition and subtraction.
398 switch (ROp) {
399 default:
400 return false;
401 case Instruction::Add:
402 case Instruction::Sub:
403 return true;
404 }
405
406 case Instruction::Or:
407 // Or distributes over And.
408 switch (ROp) {
409 default:
410 return false;
411 case Instruction::And:
412 return true;
413 }
414 }
415}
416
Sanjay Patel84dca492015-09-21 15:33:26 +0000417/// Return whether "(X LOp Y) ROp Z" is always equal to
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000418/// "(X ROp Z) LOp (Y ROp Z)".
419static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
420 Instruction::BinaryOps ROp) {
421 if (Instruction::isCommutative(ROp))
422 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000423
424 switch (LOp) {
425 default:
426 return false;
427 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
428 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
429 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
430 case Instruction::And:
431 case Instruction::Or:
432 case Instruction::Xor:
433 switch (ROp) {
434 default:
435 return false;
436 case Instruction::Shl:
437 case Instruction::LShr:
438 case Instruction::AShr:
439 return true;
440 }
441 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000442 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
443 // but this requires knowing that the addition does not overflow and other
444 // such subtleties.
445 return false;
446}
447
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000448/// This function returns identity value for given opcode, which can be used to
449/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
450static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
451 if (isa<Constant>(V))
452 return nullptr;
453
454 if (OpCode == Instruction::Mul)
455 return ConstantInt::get(V->getType(), 1);
456
457 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
458
459 return nullptr;
460}
461
462/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000463/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
464/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
465/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
466/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
467/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000468static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000469getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
470 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000471 if (!Op)
472 return Instruction::BinaryOpsEnd;
473
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000474 LHS = Op->getOperand(0);
475 RHS = Op->getOperand(1);
476
477 switch (TopLevelOpcode) {
478 default:
479 return Op->getOpcode();
480
481 case Instruction::Add:
482 case Instruction::Sub:
483 if (Op->getOpcode() == Instruction::Shl) {
484 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
485 // The multiplier is really 1 << CST.
486 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
487 return Instruction::Mul;
488 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000489 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000490 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000491 }
492
493 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000494}
495
496/// This tries to simplify binary operations by factorizing out common terms
497/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
498static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000499 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000500 Instruction::BinaryOps InnerOpcode, Value *A,
501 Value *B, Value *C, Value *D) {
502
503 // If any of A, B, C, D are null, we can not factor I, return early.
504 // Checking A and C should be enough.
505 if (!A || !C || !B || !D)
506 return nullptr;
507
David Majnemer4c3753c2015-05-22 23:02:11 +0000508 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000509 Value *SimplifiedInst = nullptr;
510 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
511 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
512
513 // Does "X op' Y" always equal "Y op' X"?
514 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
515
516 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
517 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
518 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
519 // commutative case, "(A op' B) op (C op' A)"?
520 if (A == C || (InnerCommutative && A == D)) {
521 if (A != C)
522 std::swap(C, D);
523 // Consider forming "A op' (B op D)".
524 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000525 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000526 // If "B op D" doesn't simplify then only go on if both of the existing
527 // operations "A op' B" and "C op' D" will be zapped as no longer used.
528 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
529 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
530 if (V) {
531 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
532 }
533 }
534
535 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
536 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
537 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
538 // commutative case, "(A op' B) op (B op' D)"?
539 if (B == D || (InnerCommutative && B == C)) {
540 if (B != D)
541 std::swap(C, D);
542 // Consider forming "(A op C) op' B".
543 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000544 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000545
546 // If "A op C" doesn't simplify then only go on if both of the existing
547 // operations "A op' B" and "C op' D" will be zapped as no longer used.
548 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
549 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
550 if (V) {
551 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
552 }
553 }
554
555 if (SimplifiedInst) {
556 ++NumFactor;
557 SimplifiedInst->takeName(&I);
558
559 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
560 // TODO: Check for NUW.
561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
562 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
563 bool HasNSW = false;
564 if (isa<OverflowingBinaryOperator>(&I))
565 HasNSW = I.hasNoSignedWrap();
566
567 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
568 if (isa<OverflowingBinaryOperator>(Op0))
569 HasNSW &= Op0->hasNoSignedWrap();
570
571 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
572 if (isa<OverflowingBinaryOperator>(Op1))
573 HasNSW &= Op1->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000574
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000575 // We can propagate 'nsw' if we know that
David Majnemer4c3753c2015-05-22 23:02:11 +0000576 // %Y = mul nsw i16 %X, C
577 // %Z = add nsw i16 %Y, %X
578 // =>
579 // %Z = mul nsw i16 %X, C+1
580 //
581 // iff C+1 isn't INT_MIN
582 const APInt *CInt;
583 if (TopLevelOpcode == Instruction::Add &&
584 InnerOpcode == Instruction::Mul)
585 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
586 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000587 }
588 }
589 }
590 return SimplifiedInst;
591}
592
Sanjay Patel84dca492015-09-21 15:33:26 +0000593/// This tries to simplify binary operations which some other binary operation
594/// distributes over either by factorizing out common terms
595/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
596/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
597/// Returns the simplified value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000598Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
599 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
600 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
601 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000602
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000603 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000604 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000605 auto TopLevelOpcode = I.getOpcode();
606 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
607 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000608
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000609 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
610 // a common term.
611 if (LHSOpcode == RHSOpcode) {
612 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
613 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000614 }
615
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000616 // The instruction has the form "(A op' B) op (C)". Try to factorize common
617 // term.
618 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
619 getIdentityValue(LHSOpcode, RHS)))
620 return V;
621
622 // The instruction has the form "(B) op (C op' D)". Try to factorize common
623 // term.
624 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
625 getIdentityValue(RHSOpcode, LHS), C, D))
626 return V;
627
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000628 // Expansion.
629 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
630 // The instruction has the form "(A op' B) op C". See if expanding it out
631 // to "(A op C) op' (B op C)" results in simplifications.
632 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
633 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
634
635 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000636 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
637 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000638 // They do! Return "L op' R".
639 ++NumExpand;
640 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
641 if ((L == A && R == B) ||
642 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
643 return Op0;
644 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000645 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000646 return V;
647 // Otherwise, create a new instruction.
648 C = Builder->CreateBinOp(InnerOpcode, L, R);
649 C->takeName(&I);
650 return C;
651 }
652 }
653
654 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
655 // The instruction has the form "A op (B op' C)". See if expanding it out
656 // to "(A op B) op' (A op C)" results in simplifications.
657 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
658 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
659
660 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000661 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
662 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000663 // They do! Return "L op' R".
664 ++NumExpand;
665 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
666 if ((L == B && R == C) ||
667 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
668 return Op1;
669 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000670 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000671 return V;
672 // Otherwise, create a new instruction.
673 A = Builder->CreateBinOp(InnerOpcode, L, R);
674 A->takeName(&I);
675 return A;
676 }
677 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000678
David Majnemer33b6f822015-07-14 22:39:23 +0000679 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
680 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
681 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
682 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
683 if (SI0->getCondition() == SI1->getCondition()) {
684 Value *SI = nullptr;
685 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
Justin Bogner99798402016-08-05 01:06:44 +0000686 SI1->getFalseValue(), DL, &TLI, &DT, &AC))
David Majnemer33b6f822015-07-14 22:39:23 +0000687 SI = Builder->CreateSelect(SI0->getCondition(),
688 Builder->CreateBinOp(TopLevelOpcode,
689 SI0->getTrueValue(),
690 SI1->getTrueValue()),
691 V);
692 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
Justin Bogner99798402016-08-05 01:06:44 +0000693 SI1->getTrueValue(), DL, &TLI, &DT, &AC))
David Majnemer33b6f822015-07-14 22:39:23 +0000694 SI = Builder->CreateSelect(
695 SI0->getCondition(), V,
696 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
697 SI1->getFalseValue()));
698 if (SI) {
699 SI->takeName(&I);
700 return SI;
701 }
702 }
703 }
704 }
705
Craig Topperf40110f2014-04-25 05:29:35 +0000706 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000707}
708
Sanjay Patel84dca492015-09-21 15:33:26 +0000709/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
710/// constant zero (which is the 'negate' form).
Chris Lattner2188e402010-01-04 07:37:31 +0000711Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000712 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000713 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000714
Chris Lattner9ad0d552004-12-14 20:08:06 +0000715 // Constants can be considered to be negated values if they can be folded.
716 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000717 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000718
Chris Lattner8213c8a2012-02-06 21:56:39 +0000719 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
720 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000721 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000722
Craig Topperf40110f2014-04-25 05:29:35 +0000723 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000724}
725
Sanjay Patel84dca492015-09-21 15:33:26 +0000726/// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
727/// a constant negative zero (which is the 'negate' form).
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000728Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
729 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000730 return BinaryOperator::getFNegArgument(V);
731
732 // Constants can be considered to be negated values if they can be folded.
733 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000734 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000735
Chris Lattner8213c8a2012-02-06 21:56:39 +0000736 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
737 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000738 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000739
Craig Topperf40110f2014-04-25 05:29:35 +0000740 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000741}
742
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000743static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000744 InstCombiner *IC) {
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000745 if (auto *Cast = dyn_cast<CastInst>(&I))
746 return IC->Builder->CreateCast(Cast->getOpcode(), SO, I.getType());
Chris Lattner86102b82005-01-01 16:22:27 +0000747
Sanjay Patel80baf692016-11-16 20:40:02 +0000748 assert(I.isBinaryOp() && "Unexpected opcode for select folding");
749
Chris Lattner183b3362004-04-09 19:05:30 +0000750 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000751 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
752 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000753
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000754 if (auto *SOC = dyn_cast<Constant>(SO)) {
Chris Lattner183b3362004-04-09 19:05:30 +0000755 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000756 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
757 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000758 }
759
760 Value *Op0 = SO, *Op1 = ConstOperand;
761 if (!ConstIsRHS)
762 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000763
Sanjay Patel80baf692016-11-16 20:40:02 +0000764 auto *BO = cast<BinaryOperator>(&I);
765 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
766 SO->getName() + ".op");
767 auto *FPInst = dyn_cast<Instruction>(RI);
768 if (FPInst && isa<FPMathOperator>(FPInst))
769 FPInst->copyFastMathFlags(BO);
770 return RI;
Chris Lattner86102b82005-01-01 16:22:27 +0000771}
772
Sanjay Patel84dca492015-09-21 15:33:26 +0000773/// Given an instruction with a select as one operand and a constant as the
774/// other operand, try to fold the binary operator into the select arguments.
775/// This also works for Cast instructions, which obviously do not have a second
776/// operand.
Chris Lattner2b295a02010-01-04 07:53:58 +0000777Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000778 // Don't modify shared select instructions.
779 if (!SI->hasOneUse())
780 return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000781
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000782 Value *TV = SI->getTrueValue();
783 Value *FV = SI->getFalseValue();
784 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
785 return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000786
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000787 // Bool selects with constant operands can be folded to logical ops.
788 if (SI->getType()->getScalarType()->isIntegerTy(1))
789 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000790
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000791 // If it's a bitcast involving vectors, make sure it has the same number of
792 // elements on both sides.
793 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
794 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
795 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
796
797 // Verify that either both or neither are vectors.
798 if ((SrcTy == nullptr) != (DestTy == nullptr))
799 return nullptr;
800
801 // If vectors, verify that they have the same number of elements.
802 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
803 return nullptr;
804 }
805
806 // Test if a CmpInst instruction is used exclusively by a select as
807 // part of a minimum or maximum operation. If so, refrain from doing
808 // any other folding. This helps out other analyses which understand
809 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
810 // and CodeGen. And in this case, at least one of the comparison
811 // operands has at least one user besides the compare (the select),
812 // which would often largely negate the benefit of folding anyway.
813 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
814 if (CI->hasOneUse()) {
815 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
816 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
817 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +0000818 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000819 }
Chris Lattner86102b82005-01-01 16:22:27 +0000820 }
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000821
Sanjay Patel8bd69b72016-11-26 15:23:20 +0000822 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, this);
823 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, this);
824 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
Chris Lattner183b3362004-04-09 19:05:30 +0000825}
826
Sanjay Patel84dca492015-09-21 15:33:26 +0000827/// Given a binary operator, cast instruction, or select which has a PHI node as
828/// operand #0, see if we can fold the instruction into the PHI (which is only
829/// possible if all operands to the PHI are constants).
Chris Lattnerea7131a2011-01-16 05:14:26 +0000830Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000831 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000832 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000833 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000834 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000835
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000836 // We normally only transform phis with a single use. However, if a PHI has
837 // multiple uses and they are all the same operation, we can fold *all* of the
838 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000839 if (!PN->hasOneUse()) {
840 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000841 for (User *U : PN->users()) {
842 Instruction *UI = cast<Instruction>(U);
843 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000844 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000845 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000846 // Otherwise, we can replace *all* users with the new PHI we form.
847 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000848
Chris Lattnerfacb8672009-09-27 19:57:57 +0000849 // Check to see if all of the operands of the PHI are simple constants
850 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000851 // remember the BB it is in. If there is more than one or if *it* is a PHI,
852 // bail out. We don't do arbitrary constant expressions here because moving
853 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000854 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000855 for (unsigned i = 0; i != NumPHIValues; ++i) {
856 Value *InVal = PN->getIncomingValue(i);
857 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
858 continue;
859
Craig Topperf40110f2014-04-25 05:29:35 +0000860 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
861 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000862
Chris Lattner25ce2802011-01-16 04:37:29 +0000863 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000864
865 // If the InVal is an invoke at the end of the pred block, then we can't
866 // insert a computation after it without breaking the edge.
867 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
868 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000869 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000870
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000871 // If the incoming non-constant value is in I's block, we will remove one
872 // instruction, but insert another equivalent one, leading to infinite
873 // instcombine.
Justin Bogner99798402016-08-05 01:06:44 +0000874 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000876 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000877
Chris Lattner04689872006-09-09 22:02:56 +0000878 // If there is exactly one non-constant value, we can insert a copy of the
879 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000880 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000881 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000882 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000883 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000884 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000885 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000886
887 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000888 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000889 InsertNewInstBefore(NewPN, *PN);
890 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000891
Chris Lattnerff2e7372011-01-16 05:08:00 +0000892 // If we are going to have to insert a new computation, do so right before the
Sanjay Patel41c739b2015-09-11 19:29:18 +0000893 // predecessor's terminator.
Chris Lattnerff2e7372011-01-16 05:08:00 +0000894 if (NonConstBB)
895 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000896
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000897 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000898 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
899 // We only currently try to fold the condition of a select when it is a phi,
900 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000901 Value *TrueV = SI->getTrueValue();
902 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000903 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000904 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000905 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000906 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
907 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000908 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000909 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
910 // even if currently isNullValue gives false.
911 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
912 if (InC && !isa<ConstantExpr>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000913 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000914 else
915 InV = Builder->CreateSelect(PN->getIncomingValue(i),
916 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000917 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000918 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000919 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
920 Constant *C = cast<Constant>(I.getOperand(1));
921 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000922 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000923 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
924 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
925 else if (isa<ICmpInst>(CI))
926 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
927 C, "phitmp");
928 else
929 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
930 C, "phitmp");
931 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
932 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000933 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000934 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000935 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000936 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000937 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
938 InV = ConstantExpr::get(I.getOpcode(), InC, C);
939 else
940 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
941 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000942 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000943 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000944 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000945 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000946 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000947 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000948 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000949 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000950 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000951 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000952 InV = Builder->CreateCast(CI->getOpcode(),
953 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000954 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000955 }
956 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000957
Chandler Carruthcdf47882014-03-09 03:16:01 +0000958 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000959 Instruction *User = cast<Instruction>(*UI++);
960 if (User == &I) continue;
Sanjay Patel4b198802016-02-01 22:23:39 +0000961 replaceInstUsesWith(*User, NewPN);
962 eraseInstFromFunction(*User);
Chris Lattnerd55581d2011-01-16 05:28:59 +0000963 }
Sanjay Patel4b198802016-02-01 22:23:39 +0000964 return replaceInstUsesWith(I, NewPN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000965}
966
Sanjay Patel84dca492015-09-21 15:33:26 +0000967/// Given a pointer type and a constant offset, determine whether or not there
968/// is a sequence of GEP indices into the pointed type that will land us at the
969/// specified offset. If so, fill them into NewIndices and return the resultant
970/// element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000971Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000973 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000974 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000975 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000976
Chris Lattnerfef138b2009-01-09 05:44:56 +0000977 // Start with the index over the outer type. Note that the type size
978 // might be zero (even if the offset isn't zero) if the indexed type
979 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000981 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000982 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000983 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +0000984 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000985
Benjamin Kramere4c46fe2013-01-23 17:52:29 +0000986 // Handle hosts where % returns negative instead of values [0..TySize).
987 if (Offset < 0) {
988 --FirstIdx;
989 Offset += TySize;
990 assert(Offset >= 0);
991 }
Chris Lattnerfef138b2009-01-09 05:44:56 +0000992 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
993 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000994
Owen Andersonedb4a702009-07-24 23:12:02 +0000995 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000996
Chris Lattnerfef138b2009-01-09 05:44:56 +0000997 // Index into the types. If we fail, set OrigBase to null.
998 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +0000999 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001000 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +00001001 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001002
Chris Lattner229907c2011-07-18 04:54:35 +00001003 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001004 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +00001005 assert(Offset < (int64_t)SL->getSizeInBytes() &&
1006 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001007
Chris Lattnerfef138b2009-01-09 05:44:56 +00001008 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +00001009 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1010 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001011
Chris Lattnerfef138b2009-01-09 05:44:56 +00001012 Offset -= SL->getElementOffset(Elt);
1013 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +00001014 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001015 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +00001016 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +00001017 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +00001018 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +00001019 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +00001020 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +00001021 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +00001022 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +00001023 }
1024 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001025
Chris Lattner72cd68f2009-01-24 01:00:13 +00001026 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +00001027}
1028
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001029static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1030 // If this GEP has only 0 indices, it is the same pointer as
1031 // Src. If Src is not a trivial GEP too, don't combine
1032 // the indices.
1033 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1034 !Src.hasOneUse())
1035 return false;
1036 return true;
1037}
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001038
Sanjay Patel84dca492015-09-21 15:33:26 +00001039/// Return a value X such that Val = X * Scale, or null if none.
1040/// If the multiplication is known not to overflow, then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001041Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1042 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1043 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1044 Scale.getBitWidth() && "Scale not compatible with value!");
1045
1046 // If Val is zero or Scale is one then Val = Val * Scale.
1047 if (match(Val, m_Zero()) || Scale == 1) {
1048 NoSignedWrap = true;
1049 return Val;
1050 }
1051
1052 // If Scale is zero then it does not divide Val.
1053 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001054 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001055
1056 // Look through chains of multiplications, searching for a constant that is
1057 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1058 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1059 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1060 // down from Val:
1061 //
1062 // Val = M1 * X || Analysis starts here and works down
1063 // M1 = M2 * Y || Doesn't descend into terms with more
1064 // M2 = Z * 4 \/ than one use
1065 //
1066 // Then to modify a term at the bottom:
1067 //
1068 // Val = M1 * X
1069 // M1 = Z * Y || Replaced M2 with Z
1070 //
1071 // Then to work back up correcting nsw flags.
1072
1073 // Op - the term we are currently analyzing. Starts at Val then drills down.
1074 // Replaced with its descaled value before exiting from the drill down loop.
1075 Value *Op = Val;
1076
1077 // Parent - initially null, but after drilling down notes where Op came from.
1078 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1079 // 0'th operand of Val.
1080 std::pair<Instruction*, unsigned> Parent;
1081
Sanjay Patel84dca492015-09-21 15:33:26 +00001082 // Set if the transform requires a descaling at deeper levels that doesn't
1083 // overflow.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001084 bool RequireNoSignedWrap = false;
1085
Sanjay Patel84dca492015-09-21 15:33:26 +00001086 // Log base 2 of the scale. Negative if not a power of 2.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001087 int32_t logScale = Scale.exactLogBase2();
1088
1089 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1090
1091 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1092 // If Op is a constant divisible by Scale then descale to the quotient.
1093 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1094 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1095 if (!Remainder.isMinValue())
1096 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001097 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001098 // Replace with the quotient in the parent.
1099 Op = ConstantInt::get(CI->getType(), Quotient);
1100 NoSignedWrap = true;
1101 break;
1102 }
1103
1104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1105
1106 if (BO->getOpcode() == Instruction::Mul) {
1107 // Multiplication.
1108 NoSignedWrap = BO->hasNoSignedWrap();
1109 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001110 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001111
1112 // There are three cases for multiplication: multiplication by exactly
1113 // the scale, multiplication by a constant different to the scale, and
1114 // multiplication by something else.
1115 Value *LHS = BO->getOperand(0);
1116 Value *RHS = BO->getOperand(1);
1117
1118 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1119 // Multiplication by a constant.
1120 if (CI->getValue() == Scale) {
1121 // Multiplication by exactly the scale, replace the multiplication
1122 // by its left-hand side in the parent.
1123 Op = LHS;
1124 break;
1125 }
1126
1127 // Otherwise drill down into the constant.
1128 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001129 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001130
1131 Parent = std::make_pair(BO, 1);
1132 continue;
1133 }
1134
1135 // Multiplication by something else. Drill down into the left-hand side
1136 // since that's where the reassociate pass puts the good stuff.
1137 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001138 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001139
1140 Parent = std::make_pair(BO, 0);
1141 continue;
1142 }
1143
1144 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1145 isa<ConstantInt>(BO->getOperand(1))) {
1146 // Multiplication by a power of 2.
1147 NoSignedWrap = BO->hasNoSignedWrap();
1148 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001149 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001150
1151 Value *LHS = BO->getOperand(0);
1152 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1153 getLimitedValue(Scale.getBitWidth());
1154 // Op = LHS << Amt.
1155
1156 if (Amt == logScale) {
1157 // Multiplication by exactly the scale, replace the multiplication
1158 // by its left-hand side in the parent.
1159 Op = LHS;
1160 break;
1161 }
1162 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001163 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001164
1165 // Multiplication by more than the scale. Reduce the multiplying amount
1166 // by the scale in the parent.
1167 Parent = std::make_pair(BO, 1);
1168 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1169 break;
1170 }
1171 }
1172
1173 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001174 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001175
1176 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1177 if (Cast->getOpcode() == Instruction::SExt) {
1178 // Op is sign-extended from a smaller type, descale in the smaller type.
1179 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1180 APInt SmallScale = Scale.trunc(SmallSize);
1181 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1182 // descale Op as (sext Y) * Scale. In order to have
1183 // sext (Y * SmallScale) = (sext Y) * Scale
1184 // some conditions need to hold however: SmallScale must sign-extend to
1185 // Scale and the multiplication Y * SmallScale should not overflow.
1186 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1187 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001188 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001189 assert(SmallScale.exactLogBase2() == logScale);
1190 // Require that Y * SmallScale must not overflow.
1191 RequireNoSignedWrap = true;
1192
1193 // Drill down through the cast.
1194 Parent = std::make_pair(Cast, 0);
1195 Scale = SmallScale;
1196 continue;
1197 }
1198
Duncan Sands5ed39002012-10-23 09:07:02 +00001199 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001200 // Op is truncated from a larger type, descale in the larger type.
1201 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1202 // trunc (Y * sext Scale) = (trunc Y) * Scale
1203 // always holds. However (trunc Y) * Scale may overflow even if
1204 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1205 // from this point up in the expression (see later).
1206 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001207 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001208
1209 // Drill down through the cast.
1210 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1211 Parent = std::make_pair(Cast, 0);
1212 Scale = Scale.sext(LargeSize);
1213 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1214 logScale = -1;
1215 assert(Scale.exactLogBase2() == logScale);
1216 continue;
1217 }
1218 }
1219
1220 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001221 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001222 }
1223
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001224 // If Op is zero then Val = Op * Scale.
1225 if (match(Op, m_Zero())) {
1226 NoSignedWrap = true;
1227 return Op;
1228 }
1229
Duncan Sands533c8ae2012-10-23 08:28:26 +00001230 // We know that we can successfully descale, so from here on we can safely
1231 // modify the IR. Op holds the descaled version of the deepest term in the
1232 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1233 // not to overflow.
1234
1235 if (!Parent.first)
1236 // The expression only had one term.
1237 return Op;
1238
1239 // Rewrite the parent using the descaled version of its operand.
1240 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1241 assert(Op != Parent.first->getOperand(Parent.second) &&
1242 "Descaling was a no-op?");
1243 Parent.first->setOperand(Parent.second, Op);
1244 Worklist.Add(Parent.first);
1245
1246 // Now work back up the expression correcting nsw flags. The logic is based
1247 // on the following observation: if X * Y is known not to overflow as a signed
1248 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1249 // then X * Z will not overflow as a signed multiplication either. As we work
1250 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1251 // current level has strictly smaller absolute value than the original.
1252 Instruction *Ancestor = Parent.first;
1253 do {
1254 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1255 // If the multiplication wasn't nsw then we can't say anything about the
1256 // value of the descaled multiplication, and we have to clear nsw flags
1257 // from this point on up.
1258 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1259 NoSignedWrap &= OpNoSignedWrap;
1260 if (NoSignedWrap != OpNoSignedWrap) {
1261 BO->setHasNoSignedWrap(NoSignedWrap);
1262 Worklist.Add(Ancestor);
1263 }
1264 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1265 // The fact that the descaled input to the trunc has smaller absolute
1266 // value than the original input doesn't tell us anything useful about
1267 // the absolute values of the truncations.
1268 NoSignedWrap = false;
1269 }
1270 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1271 "Failed to keep proper track of nsw flags while drilling down?");
1272
1273 if (Ancestor == Val)
1274 // Got to the top, all done!
1275 return Val;
1276
1277 // Move up one level in the expression.
1278 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001279 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001280 } while (1);
1281}
1282
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001283/// \brief Creates node of binary operation with the same attributes as the
1284/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001285static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1286 InstCombiner::BuilderTy *B) {
Sanjay Patel968e91a2015-11-24 17:51:20 +00001287 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1288 // If LHS and RHS are constant, BO won't be a binary operator.
1289 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1290 NewBO->copyIRFlags(&Inst);
1291 return BO;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001292}
1293
1294/// \brief Makes transformation of binary operation specific for vector types.
1295/// \param Inst Binary operator to transform.
1296/// \return Pointer to node that must replace the original binary operator, or
1297/// null pointer if no transformation was made.
1298Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1299 if (!Inst.getType()->isVectorTy()) return nullptr;
1300
Sanjay Patel58814442014-07-09 16:34:54 +00001301 // It may not be safe to reorder shuffles and things like div, urem, etc.
1302 // because we may trap when executing those ops on unknown vector elements.
1303 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001304 if (!isSafeToSpeculativelyExecute(&Inst))
1305 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001306
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001307 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1308 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1309 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1310 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1311
1312 // If both arguments of binary operation are shuffles, which use the same
1313 // mask and shuffle within a single vector, it is worthwhile to move the
1314 // shuffle after binary operation:
1315 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
1316 if (isa<ShuffleVectorInst>(LHS) && isa<ShuffleVectorInst>(RHS)) {
1317 ShuffleVectorInst *LShuf = cast<ShuffleVectorInst>(LHS);
1318 ShuffleVectorInst *RShuf = cast<ShuffleVectorInst>(RHS);
1319 if (isa<UndefValue>(LShuf->getOperand(1)) &&
1320 isa<UndefValue>(RShuf->getOperand(1)) &&
Serge Pavlov05811092014-05-12 05:44:53 +00001321 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType() &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001322 LShuf->getMask() == RShuf->getMask()) {
Serge Pavlove6de9e32014-05-14 09:05:09 +00001323 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001324 RShuf->getOperand(0), Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001325 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov02ff6202014-05-12 10:11:27 +00001326 UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001327 }
1328 }
1329
1330 // If one argument is a shuffle within one vector, the other is a constant,
1331 // try moving the shuffle after the binary operation.
1332 ShuffleVectorInst *Shuffle = nullptr;
1333 Constant *C1 = nullptr;
1334 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1335 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1336 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1337 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001338 if (Shuffle && C1 &&
1339 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1340 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001341 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1342 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1343 // Find constant C2 that has property:
1344 // shuffle(C2, ShMask) = C1
1345 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1346 // reorder is not possible.
1347 SmallVector<Constant*, 16> C2M(VWidth,
1348 UndefValue::get(C1->getType()->getScalarType()));
1349 bool MayChange = true;
1350 for (unsigned I = 0; I < VWidth; ++I) {
1351 if (ShMask[I] >= 0) {
1352 assert(ShMask[I] < (int)VWidth);
1353 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1354 MayChange = false;
1355 break;
1356 }
1357 C2M[ShMask[I]] = C1->getAggregateElement(I);
1358 }
1359 }
1360 if (MayChange) {
1361 Constant *C2 = ConstantVector::get(C2M);
Sanjay Patel04df5832015-11-21 16:51:19 +00001362 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1363 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
Serge Pavlove6de9e32014-05-14 09:05:09 +00001364 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001365 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001366 UndefValue::get(Inst.getType()), Shuffle->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001367 }
1368 }
1369
1370 return nullptr;
1371}
1372
Chris Lattner113f4f42002-06-25 16:13:24 +00001373Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001374 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1375
Justin Bogner99798402016-08-05 01:06:44 +00001376 if (Value *V =
1377 SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001378 return replaceInstUsesWith(GEP, V);
Chris Lattner8574aba2009-11-27 00:29:05 +00001379
Chris Lattner5f667a62004-05-07 22:09:22 +00001380 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001381
Duncan Sandsc133c542010-11-22 16:32:50 +00001382 // Eliminate unneeded casts for indices, and replace indices which displace
1383 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001384 bool MadeChange = false;
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001385 Type *IntPtrTy =
1386 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001387
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001388 gep_type_iterator GTI = gep_type_begin(GEP);
1389 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1390 ++I, ++GTI) {
1391 // Skip indices into struct types.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001392 if (GTI.isStruct())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001393 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001394
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001395 // Index type should have the same width as IntPtr
1396 Type *IndexTy = (*I)->getType();
1397 Type *NewIndexType = IndexTy->isVectorTy() ?
1398 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001399
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001400 // If the element type has zero size then any index over it is equivalent
1401 // to an index of zero, so replace it with zero if it is not zero already.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001402 Type *EltTy = GTI.getIndexedType();
1403 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001404 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001405 *I = Constant::getNullValue(NewIndexType);
Duncan Sandsc133c542010-11-22 16:32:50 +00001406 MadeChange = true;
1407 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001409 if (IndexTy != NewIndexType) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001410 // If we are using a wider index than needed for this platform, shrink
1411 // it to what we need. If narrower, sign-extend it to what we need.
1412 // This explicit cast can make subsequent optimizations more obvious.
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001413 *I = Builder->CreateIntCast(*I, NewIndexType, true);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001414 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001415 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001416 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001417 if (MadeChange)
1418 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001419
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001420 // Check to see if the inputs to the PHI node are getelementptr instructions.
1421 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1422 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1423 if (!Op1)
1424 return nullptr;
1425
Daniel Jasper5add63f2015-03-19 11:05:08 +00001426 // Don't fold a GEP into itself through a PHI node. This can only happen
1427 // through the back-edge of a loop. Folding a GEP into itself means that
1428 // the value of the previous iteration needs to be stored in the meantime,
1429 // thus requiring an additional register variable to be live, but not
1430 // actually achieving anything (the GEP still needs to be executed once per
1431 // loop iteration).
1432 if (Op1 == &GEP)
1433 return nullptr;
1434
David Majnemere61e4bf2016-06-21 05:10:24 +00001435 int DI = -1;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001436
1437 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1438 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1439 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1440 return nullptr;
1441
Daniel Jasper5add63f2015-03-19 11:05:08 +00001442 // As for Op1 above, don't try to fold a GEP into itself.
1443 if (Op2 == &GEP)
1444 return nullptr;
1445
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001446 // Keep track of the type as we walk the GEP.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001447 Type *CurTy = nullptr;
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001448
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001449 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1450 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1451 return nullptr;
1452
1453 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1454 if (DI == -1) {
1455 // We have not seen any differences yet in the GEPs feeding the
1456 // PHI yet, so we record this one if it is allowed to be a
1457 // variable.
1458
1459 // The first two arguments can vary for any GEP, the rest have to be
1460 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001461 if (J > 1 && CurTy->isStructTy())
1462 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001463
1464 DI = J;
1465 } else {
1466 // The GEP is different by more than one input. While this could be
1467 // extended to support GEPs that vary by more than one variable it
1468 // doesn't make sense since it greatly increases the complexity and
1469 // would result in an R+R+R addressing mode which no backend
1470 // directly supports and would need to be broken into several
1471 // simpler instructions anyway.
1472 return nullptr;
1473 }
1474 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001475
1476 // Sink down a layer of the type for the next iteration.
1477 if (J > 0) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001478 if (J == 1) {
1479 CurTy = Op1->getSourceElementType();
1480 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001481 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1482 } else {
1483 CurTy = nullptr;
1484 }
1485 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001486 }
1487 }
1488
Silviu Barangab892e352015-10-26 10:25:05 +00001489 // If not all GEPs are identical we'll have to create a new PHI node.
1490 // Check that the old PHI node has only one use so that it will get
1491 // removed.
1492 if (DI != -1 && !PN->hasOneUse())
1493 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001494
Silviu Barangab892e352015-10-26 10:25:05 +00001495 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001496 if (DI == -1) {
1497 // All the GEPs feeding the PHI are identical. Clone one down into our
1498 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001499 GEP.getParent()->getInstList().insert(
1500 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001501 } else {
1502 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1503 // into the current block so it can be merged, and create a new PHI to
1504 // set that index.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001505 PHINode *NewPN;
1506 {
1507 IRBuilderBase::InsertPointGuard Guard(*Builder);
1508 Builder->SetInsertPoint(PN);
1509 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1510 PN->getNumOperands());
1511 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001512
1513 for (auto &I : PN->operands())
1514 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1515 PN->getIncomingBlock(I));
1516
1517 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001518 GEP.getParent()->getInstList().insert(
1519 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001520 NewGEP->setOperand(DI, NewPN);
1521 }
1522
1523 GEP.setOperand(0, NewGEP);
1524 PtrOp = NewGEP;
1525 }
1526
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001527 // Combine Indices - If the source pointer to this getelementptr instruction
1528 // is a getelementptr instruction, combine the indices of the two
1529 // getelementptr instructions into a single instruction.
1530 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001531 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001532 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001533 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001534
Duncan Sands533c8ae2012-10-23 08:28:26 +00001535 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001536 // chain to be resolved before we perform this transformation. This
1537 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001538 if (GEPOperator *SrcGEP =
1539 dyn_cast<GEPOperator>(Src->getOperand(0)))
1540 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001541 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001542
Chris Lattneraf6094f2007-02-15 22:48:32 +00001543 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001544
1545 // Find out whether the last index in the source GEP is a sequential idx.
1546 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001547 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1548 I != E; ++I)
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001549 EndsWithSequential = I.isSequential();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001550
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001551 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001552 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001553 // Replace: gep (gep %P, long B), long A, ...
1554 // With: T = long A+B; gep %P, T, ...
1555 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001556 Value *Sum;
1557 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1558 Value *GO1 = GEP.getOperand(1);
Owen Anderson5a1acd92009-07-31 20:28:14 +00001559 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001560 Sum = GO1;
Owen Anderson5a1acd92009-07-31 20:28:14 +00001561 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner69193f92004-04-05 01:30:19 +00001562 Sum = SO1;
1563 } else {
Chris Lattnerb2995e12009-08-30 05:30:55 +00001564 // If they aren't the same type, then the input hasn't been processed
1565 // by the loop above yet (which canonicalizes sequential index types to
1566 // intptr_t). Just avoid transforming this until the input has been
1567 // normalized.
1568 if (SO1->getType() != GO1->getType())
Craig Topperf40110f2014-04-25 05:29:35 +00001569 return nullptr;
Wei Mia0adf9f2015-04-21 23:02:15 +00001570 // Only do the combine when GO1 and SO1 are both constants. Only in
1571 // this case, we are sure the cost after the merge is never more than
1572 // that before the merge.
1573 if (!isa<Constant>(GO1) || !isa<Constant>(SO1))
1574 return nullptr;
Chris Lattner59663412009-08-30 18:50:58 +00001575 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner69193f92004-04-05 01:30:19 +00001576 }
Chris Lattner5f667a62004-05-07 22:09:22 +00001577
Chris Lattnerb2995e12009-08-30 05:30:55 +00001578 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001579 if (Src->getNumOperands() == 2) {
1580 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001581 GEP.setOperand(1, Sum);
1582 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001583 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001584 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001585 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001586 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001587 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001588 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001589 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001590 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001591 Indices.append(Src->op_begin()+1, Src->op_end());
1592 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001593 }
1594
Dan Gohman1b849082009-09-07 23:54:19 +00001595 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001596 return GEP.isInBounds() && Src->isInBounds()
1597 ? GetElementPtrInst::CreateInBounds(
1598 Src->getSourceElementType(), Src->getOperand(0), Indices,
1599 GEP.getName())
1600 : GetElementPtrInst::Create(Src->getSourceElementType(),
1601 Src->getOperand(0), Indices,
1602 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001603 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001604
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001605 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001606 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001607 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001608 DL.getPointerSizeInBits(AS)) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001609 Type *Ty = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001610 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001611
1612 bool Matched = false;
1613 uint64_t C;
1614 Value *V = nullptr;
1615 if (TyAllocSize == 1) {
1616 V = GEP.getOperand(1);
1617 Matched = true;
1618 } else if (match(GEP.getOperand(1),
1619 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1620 if (TyAllocSize == 1ULL << C)
1621 Matched = true;
1622 } else if (match(GEP.getOperand(1),
1623 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1624 if (TyAllocSize == C)
1625 Matched = true;
1626 }
1627
1628 if (Matched) {
1629 // Canonicalize (gep i8* X, -(ptrtoint Y))
1630 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1631 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1632 // pointer arithmetic.
1633 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1634 Operator *Index = cast<Operator>(V);
1635 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1636 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1637 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1638 }
1639 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1640 // to (bitcast Y)
1641 Value *Y;
1642 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1643 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1644 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1645 GEP.getType());
1646 }
1647 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001648 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001649 }
1650
Chris Lattner06c687b2009-08-30 05:08:50 +00001651 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001652 Value *StrippedPtr = PtrOp->stripPointerCasts();
Nadav Roteme63e59c2012-03-26 20:39:18 +00001653 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1654
Nadav Rotema8f35622012-03-26 21:00:53 +00001655 // We do not handle pointer-vector geps here.
1656 if (!StrippedPtrTy)
Craig Topperf40110f2014-04-25 05:29:35 +00001657 return nullptr;
Nadav Rotema8f35622012-03-26 21:00:53 +00001658
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001659 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001660 bool HasZeroPointerIndex = false;
1661 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1662 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001663
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001664 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1665 // into : GEP [10 x i8]* X, i32 0, ...
1666 //
1667 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1668 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001669 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001670 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001671 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001672 if (ArrayType *CATy =
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001673 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
Duncan Sands5795a602009-03-02 09:18:21 +00001674 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001675 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001676 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001677 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001678 GetElementPtrInst *Res = GetElementPtrInst::Create(
1679 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001680 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001681 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1682 return Res;
1683 // Insert Res, and create an addrspacecast.
1684 // e.g.,
1685 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1686 // ->
1687 // %0 = GEP i8 addrspace(1)* X, ...
1688 // addrspacecast i8 addrspace(1)* %0 to i8*
1689 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001690 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001691
Chris Lattner229907c2011-07-18 04:54:35 +00001692 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001693 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001694 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001695 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001696 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001697 // At this point, we know that the cast source type is a pointer
1698 // to an array of the same type as the destination pointer
1699 // array. Because the array type is never stepped over (there
1700 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001701 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1702 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001703 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001704 return &GEP;
1705 }
1706 // Cannot replace the base pointer directly because StrippedPtr's
1707 // address space is different. Instead, create a new GEP followed by
1708 // an addrspacecast.
1709 // e.g.,
1710 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1711 // i32 0, ...
1712 // ->
1713 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1714 // addrspacecast i8 addrspace(1)* %0 to i8*
1715 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001716 Value *NewGEP = GEP.isInBounds()
1717 ? Builder->CreateInBoundsGEP(
1718 nullptr, StrippedPtr, Idx, GEP.getName())
1719 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1720 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001721 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001722 }
Duncan Sands5795a602009-03-02 09:18:21 +00001723 }
1724 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001725 } else if (GEP.getNumOperands() == 2) {
1726 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001727 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1728 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001729 Type *SrcElTy = StrippedPtrTy->getElementType();
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001730 Type *ResElTy = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001731 if (SrcElTy->isArrayTy() &&
1732 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1733 DL.getTypeAllocSize(ResElTy)) {
1734 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001735 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001736 Value *NewGEP =
1737 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001738 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1739 GEP.getName())
1740 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001741
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001742 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001743 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1744 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001745 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001746
Chris Lattner2a893292005-09-13 18:36:04 +00001747 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001748 // %V = mul i64 %N, 4
1749 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1750 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001751 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001752 // Check that changing the type amounts to dividing the index by a scale
1753 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001754 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1755 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001756 if (ResSize && SrcSize % ResSize == 0) {
1757 Value *Idx = GEP.getOperand(1);
1758 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1759 uint64_t Scale = SrcSize / ResSize;
1760
1761 // Earlier transforms ensure that the index has type IntPtrType, which
1762 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001763 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001764 "Index not cast to pointer width?");
1765
1766 bool NSW;
1767 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1768 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1769 // If the multiplication NewIdx * Scale may overflow then the new
1770 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001771 Value *NewGEP =
1772 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001773 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001774 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001775 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1776 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001777
Duncan Sands533c8ae2012-10-23 08:28:26 +00001778 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001779 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1780 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001781 }
1782 }
1783 }
1784
1785 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001786 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001787 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001788 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001789 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001790 // Check that changing to the array element type amounts to dividing the
1791 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001792 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1793 uint64_t ArrayEltSize =
1794 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001795 if (ResSize && ArrayEltSize % ResSize == 0) {
1796 Value *Idx = GEP.getOperand(1);
1797 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1798 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001799
Duncan Sands533c8ae2012-10-23 08:28:26 +00001800 // Earlier transforms ensure that the index has type IntPtrType, which
1801 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001802 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001803 "Index not cast to pointer width?");
1804
1805 bool NSW;
1806 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1807 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1808 // If the multiplication NewIdx * Scale may overflow then the new
1809 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001810 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001811 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1812 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001813
David Blaikieaa41cd52015-04-03 21:33:42 +00001814 Value *NewGEP = GEP.isInBounds() && NSW
1815 ? Builder->CreateInBoundsGEP(
1816 SrcElTy, StrippedPtr, Off, GEP.getName())
1817 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1818 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001819 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001820 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1821 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001822 }
1823 }
Chris Lattner2a893292005-09-13 18:36:04 +00001824 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001825 }
Chris Lattnerca081252001-12-14 16:52:21 +00001826 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001827
Matt Arsenault4815f092014-08-12 19:46:13 +00001828 // addrspacecast between types is canonicalized as a bitcast, then an
1829 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1830 // through the addrspacecast.
1831 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1832 // X = bitcast A addrspace(1)* to B addrspace(1)*
1833 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1834 // Z = gep Y, <...constant indices...>
1835 // Into an addrspacecasted GEP of the struct.
1836 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1837 PtrOp = BC;
1838 }
1839
Chris Lattnerfef138b2009-01-09 05:44:56 +00001840 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001841 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001842 /// Y = gep X, <...constant indices...>
1843 /// into a gep of the original struct. This is important for SROA and alias
1844 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001845 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001846 Value *Operand = BCI->getOperand(0);
1847 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001848 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001849 APInt Offset(OffsetBits, 0);
1850 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001851 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001852
Chris Lattnerfef138b2009-01-09 05:44:56 +00001853 // If this GEP instruction doesn't move the pointer, just replace the GEP
1854 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001855 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001856 // If the bitcast is of an allocation, and the allocation will be
1857 // converted to match the type of the cast, don't touch this.
Justin Bogner99798402016-08-05 01:06:44 +00001858 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001859 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1860 if (Instruction *I = visitBitCast(*BCI)) {
1861 if (I != BCI) {
1862 I->takeName(BCI);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001863 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
Sanjay Patel4b198802016-02-01 22:23:39 +00001864 replaceInstUsesWith(*BCI, I);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001865 }
1866 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001867 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001868 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001869
1870 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1871 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001872 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001873 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001874
Chris Lattnerfef138b2009-01-09 05:44:56 +00001875 // Otherwise, if the offset is non-zero, we need to find out if there is a
1876 // field at Offset in 'A's type. If so, we can pull the cast through the
1877 // GEP.
1878 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001879 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001880 Value *NGEP =
1881 GEP.isInBounds()
1882 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1883 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001884
Chris Lattner59663412009-08-30 18:50:58 +00001885 if (NGEP->getType() == GEP.getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001886 return replaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001887 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001888
1889 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1890 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001891 return new BitCastInst(NGEP, GEP.getType());
1892 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001893 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001894 }
1895
David Majnemer4e4f4432016-08-07 07:58:00 +00001896 if (!GEP.isInBounds()) {
1897 unsigned PtrWidth =
1898 DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1899 APInt BasePtrOffset(PtrWidth, 0);
1900 Value *UnderlyingPtrOp =
1901 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1902 BasePtrOffset);
1903 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1904 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1905 BasePtrOffset.isNonNegative()) {
1906 APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1907 if (BasePtrOffset.ule(AllocSize)) {
1908 return GetElementPtrInst::CreateInBounds(
1909 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1910 }
1911 }
1912 }
1913 }
1914
Craig Topperf40110f2014-04-25 05:29:35 +00001915 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001916}
1917
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001918static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1919 Instruction *AI) {
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001920 if (isa<ConstantPointerNull>(V))
1921 return true;
1922 if (auto *LI = dyn_cast<LoadInst>(V))
1923 return isa<GlobalVariable>(LI->getPointerOperand());
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001924 // Two distinct allocations will never be equal.
1925 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1926 // through bitcasts of V can cause
1927 // the result statement below to be true, even when AI and V (ex:
1928 // i8* ->i32* ->i8* of AI) are the same allocations.
1929 return isAllocLikeFn(V, TLI) && V != AI;
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001930}
1931
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001932static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001933isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1934 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001935 SmallVector<Instruction*, 4> Worklist;
1936 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001937
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001938 do {
1939 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001940 for (User *U : PI->users()) {
1941 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001942 switch (I->getOpcode()) {
1943 default:
1944 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001945 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001946
1947 case Instruction::BitCast:
1948 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001949 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001950 Worklist.push_back(I);
1951 continue;
1952
1953 case Instruction::ICmp: {
1954 ICmpInst *ICI = cast<ICmpInst>(I);
1955 // We can fold eq/ne comparisons with null to false/true, respectively.
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001956 // We also fold comparisons in some conditions provided the alloc has
Anna Thomas95f68aa2016-04-25 13:58:05 +00001957 // not escaped (see isNeverEqualToUnescapedAlloc).
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001958 if (!ICI->isEquality())
1959 return false;
1960 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001961 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001962 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001963 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001964 continue;
1965 }
1966
1967 case Instruction::Call:
1968 // Ignore no-op and store intrinsics.
1969 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1970 switch (II->getIntrinsicID()) {
1971 default:
1972 return false;
1973
1974 case Intrinsic::memmove:
1975 case Intrinsic::memcpy:
1976 case Intrinsic::memset: {
1977 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1978 if (MI->isVolatile() || MI->getRawDest() != PI)
1979 return false;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001980 LLVM_FALLTHROUGH;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001981 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001982 case Intrinsic::dbg_declare:
1983 case Intrinsic::dbg_value:
1984 case Intrinsic::invariant_start:
1985 case Intrinsic::invariant_end:
1986 case Intrinsic::lifetime_start:
1987 case Intrinsic::lifetime_end:
1988 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001989 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001990 continue;
1991 }
1992 }
1993
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001994 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001995 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001996 continue;
1997 }
1998 return false;
1999
2000 case Instruction::Store: {
2001 StoreInst *SI = cast<StoreInst>(I);
2002 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2003 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002004 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002005 continue;
2006 }
2007 }
2008 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00002009 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002010 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00002011 return true;
2012}
2013
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002014Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00002015 // If we have a malloc call which is only used in any amount of comparisons
2016 // to null and free calls, delete the calls and replace the comparisons with
2017 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00002018 SmallVector<WeakVH, 64> Users;
Justin Bogner99798402016-08-05 01:06:44 +00002019 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00002020 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
Petar Jovanovic921c2b42016-03-09 14:12:47 +00002021 // Lowering all @llvm.objectsize calls first because they may
2022 // use a bitcast/GEP of the alloca we are removing.
2023 if (!Users[i])
2024 continue;
2025
2026 Instruction *I = cast<Instruction>(&*Users[i]);
2027
2028 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2029 if (II->getIntrinsicID() == Intrinsic::objectsize) {
2030 uint64_t Size;
Justin Bogner99798402016-08-05 01:06:44 +00002031 if (!getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
Petar Jovanovic921c2b42016-03-09 14:12:47 +00002032 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
2033 Size = CI->isZero() ? -1ULL : 0;
2034 }
2035 replaceInstUsesWith(*I, ConstantInt::get(I->getType(), Size));
2036 eraseInstFromFunction(*I);
2037 Users[i] = nullptr; // Skip examining in the next loop.
2038 }
2039 }
2040 }
2041 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2042 if (!Users[i])
2043 continue;
2044
2045 Instruction *I = cast<Instruction>(&*Users[i]);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002046
Nick Lewycky50f49662011-08-03 00:43:35 +00002047 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002048 replaceInstUsesWith(*C,
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00002049 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2050 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00002051 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002052 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sandsf162eac2010-05-27 19:09:06 +00002053 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002054 eraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002055 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002056
2057 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00002058 // Replace invoke with a NOP intrinsic to maintain the original CFG
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002059 Module *M = II->getModule();
Nuno Lopes9ac46612012-06-28 22:31:24 +00002060 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2061 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00002062 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002063 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002064 return eraseInstFromFunction(MI);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002065 }
Craig Topperf40110f2014-04-25 05:29:35 +00002066 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00002067}
2068
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002069/// \brief Move the call to free before a NULL test.
2070///
2071/// Check if this free is accessed after its argument has been test
2072/// against NULL (property 0).
2073/// If yes, it is legal to move this call in its predecessor block.
2074///
2075/// The move is performed only if the block containing the call to free
2076/// will be removed, i.e.:
2077/// 1. it has only one predecessor P, and P has two successors
2078/// 2. it contains the call and an unconditional branch
2079/// 3. its successor is the same as its predecessor's successor
2080///
2081/// The profitability is out-of concern here and this function should
2082/// be called only if the caller knows this transformation would be
2083/// profitable (e.g., for code size).
2084static Instruction *
2085tryToMoveFreeBeforeNullTest(CallInst &FI) {
2086 Value *Op = FI.getArgOperand(0);
2087 BasicBlock *FreeInstrBB = FI.getParent();
2088 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2089
2090 // Validate part of constraint #1: Only one predecessor
2091 // FIXME: We can extend the number of predecessor, but in that case, we
2092 // would duplicate the call to free in each predecessor and it may
2093 // not be profitable even for code size.
2094 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00002095 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002096
2097 // Validate constraint #2: Does this block contains only the call to
2098 // free and an unconditional branch?
2099 // FIXME: We could check if we can speculate everything in the
2100 // predecessor block
2101 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002102 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002103 BasicBlock *SuccBB;
2104 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002105 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002106
2107 // Validate the rest of constraint #1 by matching on the pred branch.
2108 TerminatorInst *TI = PredBB->getTerminator();
2109 BasicBlock *TrueBB, *FalseBB;
2110 ICmpInst::Predicate Pred;
2111 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002112 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002113 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002114 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002115
2116 // Validate constraint #3: Ensure the null case just falls through.
2117 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002118 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002119 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2120 "Broken CFG: missing edge from predecessor to successor");
2121
2122 FI.moveBefore(TI);
2123 return &FI;
2124}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002125
2126
Gabor Greif75f69432010-06-24 12:21:15 +00002127Instruction *InstCombiner::visitFree(CallInst &FI) {
2128 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002129
2130 // free undef -> unreachable.
2131 if (isa<UndefValue>(Op)) {
2132 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002133 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2134 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Sanjay Patel4b198802016-02-01 22:23:39 +00002135 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002136 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002137
Victor Hernandeze2971492009-10-24 04:23:03 +00002138 // If we have 'free null' delete the instruction. This can happen in stl code
2139 // when lots of inlining happens.
2140 if (isa<ConstantPointerNull>(Op))
Sanjay Patel4b198802016-02-01 22:23:39 +00002141 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002142
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002143 // If we optimize for code size, try to move the call to free before the null
2144 // test so that simplify cfg can remove the empty block and dead code
2145 // elimination the branch. I.e., helps to turn something like:
2146 // if (foo) free(foo);
2147 // into
2148 // free(foo);
2149 if (MinimizeSize)
2150 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2151 return I;
2152
Craig Topperf40110f2014-04-25 05:29:35 +00002153 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002154}
Chris Lattner8427bff2003-12-07 01:24:23 +00002155
Hal Finkel93873cc12014-09-07 21:28:34 +00002156Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2157 if (RI.getNumOperands() == 0) // ret void
2158 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002159
Hal Finkel93873cc12014-09-07 21:28:34 +00002160 Value *ResultOp = RI.getOperand(0);
2161 Type *VTy = ResultOp->getType();
2162 if (!VTy->isIntegerTy())
2163 return nullptr;
2164
2165 // There might be assume intrinsics dominating this return that completely
2166 // determine the value. If so, constant fold it.
2167 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2168 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2169 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2170 if ((KnownZero|KnownOne).isAllOnesValue())
2171 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2172
2173 return nullptr;
2174}
Chris Lattner31f486c2005-01-31 05:36:43 +00002175
Chris Lattner9eef8a72003-06-04 04:46:00 +00002176Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2177 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002178 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002179 BasicBlock *TrueDest;
2180 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002181 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002182 !isa<Constant>(X)) {
2183 // Swap Destinations and condition...
2184 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002185 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002186 return &BI;
2187 }
2188
Philip Reames71c40352015-03-10 22:52:37 +00002189 // If the condition is irrelevant, remove the use so that other
2190 // transforms on the condition become more effective.
2191 if (BI.isConditional() &&
2192 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2193 !isa<UndefValue>(BI.getCondition())) {
2194 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2195 return &BI;
2196 }
2197
Alp Tokercb402912014-01-24 17:20:08 +00002198 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002199 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002200 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002201 TrueDest, FalseDest)) &&
2202 BI.getCondition()->hasOneUse())
2203 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2204 FPred == FCmpInst::FCMP_OGE) {
2205 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2206 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002207
Chris Lattner905976b2009-08-30 06:13:40 +00002208 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002209 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002210 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002211 return &BI;
2212 }
2213
Alp Tokercb402912014-01-24 17:20:08 +00002214 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002215 ICmpInst::Predicate IPred;
2216 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002217 TrueDest, FalseDest)) &&
2218 BI.getCondition()->hasOneUse())
2219 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2220 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2221 IPred == ICmpInst::ICMP_SGE) {
2222 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2223 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2224 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002225 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002226 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002227 return &BI;
2228 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002229
Craig Topperf40110f2014-04-25 05:29:35 +00002230 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002231}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002232
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002233Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2234 Value *Cond = SI.getCondition();
Sanjay Patele730ce82016-12-12 16:13:52 +00002235 Value *Op0;
2236 ConstantInt *AddRHS;
2237 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2238 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2239 for (SwitchInst::CaseIt CaseIter : SI.cases()) {
2240 Constant *NewCase = ConstantExpr::getSub(CaseIter.getCaseValue(), AddRHS);
2241 assert(isa<ConstantInt>(NewCase) &&
2242 "Result of expression should be constant");
2243 CaseIter.setValue(cast<ConstantInt>(NewCase));
2244 }
2245 SI.setCondition(Op0);
2246 return &SI;
2247 }
2248
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002249 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2250 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002251 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002252 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2253 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2254
2255 // Compute the number of leading bits we can ignore.
Sanjay Patel7521e1b2016-06-30 15:32:45 +00002256 // TODO: A better way to determine this would use ComputeNumSignBits().
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002257 for (auto &C : SI.cases()) {
2258 LeadingKnownZeros = std::min(
2259 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2260 LeadingKnownOnes = std::min(
2261 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2262 }
2263
2264 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2265
Sanjay Patel7c6eab52016-06-30 14:51:21 +00002266 // Shrink the condition operand if the new type is smaller than the old type.
2267 // This may produce a non-standard type for the switch, but that's ok because
2268 // the backend should extend back to a legal type for the target.
Sanjay Patel7521e1b2016-06-30 15:32:45 +00002269 if (NewWidth > 0 && NewWidth < BitWidth) {
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002270 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2271 Builder->SetInsertPoint(&SI);
Sanjay Patel7c6eab52016-06-30 14:51:21 +00002272 Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002273 SI.setCondition(NewCond);
2274
Sanjay Patel87e2f672016-12-12 15:52:56 +00002275 for (SwitchInst::CaseIt CaseIter : SI.cases()) {
2276 APInt TruncatedCase = CaseIter.getCaseValue()->getValue().trunc(NewWidth);
2277 CaseIter.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2278 }
Sanjay Patelabbc2ac2016-05-13 21:51:17 +00002279 return &SI;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002280 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002281
Sanjay Patele730ce82016-12-12 16:13:52 +00002282 return nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002283}
2284
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002285Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002286 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002287
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002288 if (!EV.hasIndices())
Sanjay Patel4b198802016-02-01 22:23:39 +00002289 return replaceInstUsesWith(EV, Agg);
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002290
David Majnemer25a796e2015-07-13 01:15:46 +00002291 if (Value *V =
Justin Bogner99798402016-08-05 01:06:44 +00002292 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002293 return replaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002294
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002295 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2296 // We're extracting from an insertvalue instruction, compare the indices
2297 const unsigned *exti, *exte, *insi, *inse;
2298 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2299 exte = EV.idx_end(), inse = IV->idx_end();
2300 exti != exte && insi != inse;
2301 ++exti, ++insi) {
2302 if (*insi != *exti)
2303 // The insert and extract both reference distinctly different elements.
2304 // This means the extract is not influenced by the insert, and we can
2305 // replace the aggregate operand of the extract with the aggregate
2306 // operand of the insert. i.e., replace
2307 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2308 // %E = extractvalue { i32, { i32 } } %I, 0
2309 // with
2310 // %E = extractvalue { i32, { i32 } } %A, 0
2311 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002312 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002313 }
2314 if (exti == exte && insi == inse)
2315 // Both iterators are at the end: Index lists are identical. Replace
2316 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2317 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2318 // with "i32 42"
Sanjay Patel4b198802016-02-01 22:23:39 +00002319 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002320 if (exti == exte) {
2321 // The extract list is a prefix of the insert list. i.e. replace
2322 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2323 // %E = extractvalue { i32, { i32 } } %I, 1
2324 // with
2325 // %X = extractvalue { i32, { i32 } } %A, 1
2326 // %E = insertvalue { i32 } %X, i32 42, 0
2327 // by switching the order of the insert and extract (though the
2328 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002329 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002330 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002331 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002332 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002333 }
2334 if (insi == inse)
2335 // The insert list is a prefix of the extract list
2336 // We can simply remove the common indices from the extract and make it
2337 // operate on the inserted value instead of the insertvalue result.
2338 // i.e., replace
2339 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2340 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2341 // with
2342 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002343 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002344 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002345 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002346 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2347 // We're extracting from an intrinsic, see if we're the only user, which
2348 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002349 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002350 if (II->hasOneUse()) {
2351 // Check if we're grabbing the overflow bit or the result of a 'with
2352 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2353 // and replace it with a traditional binary instruction.
2354 switch (II->getIntrinsicID()) {
2355 case Intrinsic::uadd_with_overflow:
2356 case Intrinsic::sadd_with_overflow:
2357 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002358 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002359 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2360 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002361 return BinaryOperator::CreateAdd(LHS, RHS);
2362 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002363
Chris Lattner3e635d22010-12-19 19:43:52 +00002364 // If the normal result of the add is dead, and the RHS is a constant,
2365 // we can transform this into a range comparison.
2366 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002367 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2368 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2369 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2370 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002371 break;
2372 case Intrinsic::usub_with_overflow:
2373 case Intrinsic::ssub_with_overflow:
2374 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002375 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002376 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2377 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002378 return BinaryOperator::CreateSub(LHS, RHS);
2379 }
2380 break;
2381 case Intrinsic::umul_with_overflow:
2382 case Intrinsic::smul_with_overflow:
2383 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002384 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002385 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2386 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002387 return BinaryOperator::CreateMul(LHS, RHS);
2388 }
2389 break;
2390 default:
2391 break;
2392 }
2393 }
2394 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002395 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2396 // If the (non-volatile) load only has one use, we can rewrite this to a
Mehdi Amini1c131b32015-12-15 01:44:07 +00002397 // load from a GEP. This reduces the size of the load. If a load is used
2398 // only by extractvalue instructions then this either must have been
2399 // optimized before, or it is a struct with padding, in which case we
2400 // don't want to do the transformation as it loses padding knowledge.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002401 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002402 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2403 SmallVector<Value*, 4> Indices;
2404 // Prefix an i32 0 since we need the first element.
2405 Indices.push_back(Builder->getInt32(0));
2406 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2407 I != E; ++I)
2408 Indices.push_back(Builder->getInt32(*I));
2409
2410 // We need to insert these at the location of the old load, not at that of
2411 // the extractvalue.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002412 Builder->SetInsertPoint(L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002413 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2414 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002415 // Returning the load directly will cause the main loop to insert it in
Sanjay Patel4b198802016-02-01 22:23:39 +00002416 // the wrong spot, so use replaceInstUsesWith().
2417 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
Frits van Bommel28218aa2010-11-29 21:56:20 +00002418 }
2419 // We could simplify extracts from other values. Note that nested extracts may
2420 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002421 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002422 // the value inserted, if appropriate. Similarly for extracts from single-use
2423 // loads: extract (extract (load)) will be translated to extract (load (gep))
2424 // and if again single-use then via load (gep (gep)) to load (gep).
2425 // However, double extracts from e.g. function arguments or return values
2426 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002427 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002428}
2429
Sanjay Patel84dca492015-09-21 15:33:26 +00002430/// Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002431static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002432 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002433 case EHPersonality::GNU_C:
Saleem Abdulrasoold2f705d2016-05-31 01:48:07 +00002434 case EHPersonality::GNU_C_SjLj:
Bjorn Steinbrink37ca4622016-03-15 20:57:07 +00002435 case EHPersonality::Rust:
2436 // The GCC C EH and Rust personality only exists to support cleanups, so
2437 // it's not clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002438 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002439 case EHPersonality::Unknown:
2440 return false;
2441 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002442 // While __gnat_all_others_value will match any Ada exception, it doesn't
2443 // match foreign exceptions (or didn't, before gcc-4.7).
2444 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002445 case EHPersonality::GNU_CXX:
Saleem Abdulrasoold2f705d2016-05-31 01:48:07 +00002446 case EHPersonality::GNU_CXX_SjLj:
Reid Kleckner4af64152015-01-28 01:17:38 +00002447 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002448 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002449 case EHPersonality::MSVC_Win64SEH:
2450 case EHPersonality::MSVC_CXX:
Joseph Tremoulet2afea542015-10-06 20:28:16 +00002451 case EHPersonality::CoreCLR:
Duncan Sands5c055792011-09-30 13:12:16 +00002452 return TypeInfo->isNullValue();
2453 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002454 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002455}
2456
2457static bool shorter_filter(const Value *LHS, const Value *RHS) {
2458 return
2459 cast<ArrayType>(LHS->getType())->getNumElements()
2460 <
2461 cast<ArrayType>(RHS->getType())->getNumElements();
2462}
2463
2464Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2465 // The logic here should be correct for any real-world personality function.
2466 // However if that turns out not to be true, the offending logic can always
2467 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002468 EHPersonality Personality =
2469 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002470
2471 // Simplify the list of clauses, eg by removing repeated catch clauses
2472 // (these are often created by inlining).
2473 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002474 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002475 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2476
2477 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2478 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2479 bool isLastClause = i + 1 == e;
2480 if (LI.isCatch(i)) {
2481 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002482 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002483 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002484
2485 // If we already saw this clause, there is no point in having a second
2486 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002487 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002488 // This catch clause was not already seen.
2489 NewClauses.push_back(CatchClause);
2490 } else {
2491 // Repeated catch clause - drop the redundant copy.
2492 MakeNewInstruction = true;
2493 }
2494
2495 // If this is a catch-all then there is no point in keeping any following
2496 // clauses or marking the landingpad as having a cleanup.
2497 if (isCatchAll(Personality, TypeInfo)) {
2498 if (!isLastClause)
2499 MakeNewInstruction = true;
2500 CleanupFlag = false;
2501 break;
2502 }
2503 } else {
2504 // A filter clause. If any of the filter elements were already caught
2505 // then they can be dropped from the filter. It is tempting to try to
2506 // exploit the filter further by saying that any typeinfo that does not
2507 // occur in the filter can't be caught later (and thus can be dropped).
2508 // However this would be wrong, since typeinfos can match without being
2509 // equal (for example if one represents a C++ class, and the other some
2510 // class derived from it).
2511 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002512 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002513 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2514 unsigned NumTypeInfos = FilterType->getNumElements();
2515
2516 // An empty filter catches everything, so there is no point in keeping any
2517 // following clauses or marking the landingpad as having a cleanup. By
2518 // dealing with this case here the following code is made a bit simpler.
2519 if (!NumTypeInfos) {
2520 NewClauses.push_back(FilterClause);
2521 if (!isLastClause)
2522 MakeNewInstruction = true;
2523 CleanupFlag = false;
2524 break;
2525 }
2526
2527 bool MakeNewFilter = false; // If true, make a new filter.
2528 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2529 if (isa<ConstantAggregateZero>(FilterClause)) {
2530 // Not an empty filter - it contains at least one null typeinfo.
2531 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2532 Constant *TypeInfo =
2533 Constant::getNullValue(FilterType->getElementType());
2534 // If this typeinfo is a catch-all then the filter can never match.
2535 if (isCatchAll(Personality, TypeInfo)) {
2536 // Throw the filter away.
2537 MakeNewInstruction = true;
2538 continue;
2539 }
2540
2541 // There is no point in having multiple copies of this typeinfo, so
2542 // discard all but the first copy if there is more than one.
2543 NewFilterElts.push_back(TypeInfo);
2544 if (NumTypeInfos > 1)
2545 MakeNewFilter = true;
2546 } else {
2547 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2548 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2549 NewFilterElts.reserve(NumTypeInfos);
2550
2551 // Remove any filter elements that were already caught or that already
2552 // occurred in the filter. While there, see if any of the elements are
2553 // catch-alls. If so, the filter can be discarded.
2554 bool SawCatchAll = false;
2555 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002556 Constant *Elt = Filter->getOperand(j);
2557 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002558 if (isCatchAll(Personality, TypeInfo)) {
2559 // This element is a catch-all. Bail out, noting this fact.
2560 SawCatchAll = true;
2561 break;
2562 }
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002563
2564 // Even if we've seen a type in a catch clause, we don't want to
2565 // remove it from the filter. An unexpected type handler may be
2566 // set up for a call site which throws an exception of the same
2567 // type caught. In order for the exception thrown by the unexpected
Simon Pilgrim7d18a702016-11-20 13:19:49 +00002568 // handler to propagate correctly, the filter must be correctly
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002569 // described for the call site.
2570 //
2571 // Example:
2572 //
2573 // void unexpected() { throw 1;}
2574 // void foo() throw (int) {
2575 // std::set_unexpected(unexpected);
2576 // try {
2577 // throw 2.0;
2578 // } catch (int i) {}
2579 // }
2580
Duncan Sands5c055792011-09-30 13:12:16 +00002581 // There is no point in having multiple copies of the same typeinfo in
2582 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002583 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002584 NewFilterElts.push_back(cast<Constant>(Elt));
2585 }
2586 // A filter containing a catch-all cannot match anything by definition.
2587 if (SawCatchAll) {
2588 // Throw the filter away.
2589 MakeNewInstruction = true;
2590 continue;
2591 }
2592
2593 // If we dropped something from the filter, make a new one.
2594 if (NewFilterElts.size() < NumTypeInfos)
2595 MakeNewFilter = true;
2596 }
2597 if (MakeNewFilter) {
2598 FilterType = ArrayType::get(FilterType->getElementType(),
2599 NewFilterElts.size());
2600 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2601 MakeNewInstruction = true;
2602 }
2603
2604 NewClauses.push_back(FilterClause);
2605
2606 // If the new filter is empty then it will catch everything so there is
2607 // no point in keeping any following clauses or marking the landingpad
2608 // as having a cleanup. The case of the original filter being empty was
2609 // already handled above.
2610 if (MakeNewFilter && !NewFilterElts.size()) {
2611 assert(MakeNewInstruction && "New filter but not a new instruction!");
2612 CleanupFlag = false;
2613 break;
2614 }
2615 }
2616 }
2617
2618 // If several filters occur in a row then reorder them so that the shortest
2619 // filters come first (those with the smallest number of elements). This is
2620 // advantageous because shorter filters are more likely to match, speeding up
2621 // unwinding, but mostly because it increases the effectiveness of the other
2622 // filter optimizations below.
2623 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2624 unsigned j;
2625 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2626 for (j = i; j != e; ++j)
2627 if (!isa<ArrayType>(NewClauses[j]->getType()))
2628 break;
2629
2630 // Check whether the filters are already sorted by length. We need to know
2631 // if sorting them is actually going to do anything so that we only make a
2632 // new landingpad instruction if it does.
2633 for (unsigned k = i; k + 1 < j; ++k)
2634 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2635 // Not sorted, so sort the filters now. Doing an unstable sort would be
2636 // correct too but reordering filters pointlessly might confuse users.
2637 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2638 shorter_filter);
2639 MakeNewInstruction = true;
2640 break;
2641 }
2642
2643 // Look for the next batch of filters.
2644 i = j + 1;
2645 }
2646
2647 // If typeinfos matched if and only if equal, then the elements of a filter L
2648 // that occurs later than a filter F could be replaced by the intersection of
2649 // the elements of F and L. In reality two typeinfos can match without being
2650 // equal (for example if one represents a C++ class, and the other some class
2651 // derived from it) so it would be wrong to perform this transform in general.
2652 // However the transform is correct and useful if F is a subset of L. In that
2653 // case L can be replaced by F, and thus removed altogether since repeating a
2654 // filter is pointless. So here we look at all pairs of filters F and L where
2655 // L follows F in the list of clauses, and remove L if every element of F is
2656 // an element of L. This can occur when inlining C++ functions with exception
2657 // specifications.
2658 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2659 // Examine each filter in turn.
2660 Value *Filter = NewClauses[i];
2661 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2662 if (!FTy)
2663 // Not a filter - skip it.
2664 continue;
2665 unsigned FElts = FTy->getNumElements();
2666 // Examine each filter following this one. Doing this backwards means that
2667 // we don't have to worry about filters disappearing under us when removed.
2668 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2669 Value *LFilter = NewClauses[j];
2670 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2671 if (!LTy)
2672 // Not a filter - skip it.
2673 continue;
2674 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2675 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002676 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002677 // If Filter is empty then it is a subset of LFilter.
2678 if (!FElts) {
2679 // Discard LFilter.
2680 NewClauses.erase(J);
2681 MakeNewInstruction = true;
2682 // Move on to the next filter.
2683 continue;
2684 }
2685 unsigned LElts = LTy->getNumElements();
2686 // If Filter is longer than LFilter then it cannot be a subset of it.
2687 if (FElts > LElts)
2688 // Move on to the next filter.
2689 continue;
2690 // At this point we know that LFilter has at least one element.
2691 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002692 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002693 // already know that Filter is not longer than LFilter).
2694 if (isa<ConstantAggregateZero>(Filter)) {
2695 assert(FElts <= LElts && "Should have handled this case earlier!");
2696 // Discard LFilter.
2697 NewClauses.erase(J);
2698 MakeNewInstruction = true;
2699 }
2700 // Move on to the next filter.
2701 continue;
2702 }
2703 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2704 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2705 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002706 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002707 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2708 for (unsigned l = 0; l != LElts; ++l)
2709 if (LArray->getOperand(l)->isNullValue()) {
2710 // LFilter contains a zero - discard it.
2711 NewClauses.erase(J);
2712 MakeNewInstruction = true;
2713 break;
2714 }
2715 // Move on to the next filter.
2716 continue;
2717 }
2718 // At this point we know that both filters are ConstantArrays. Loop over
2719 // operands to see whether every element of Filter is also an element of
2720 // LFilter. Since filters tend to be short this is probably faster than
2721 // using a method that scales nicely.
2722 ConstantArray *FArray = cast<ConstantArray>(Filter);
2723 bool AllFound = true;
2724 for (unsigned f = 0; f != FElts; ++f) {
2725 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2726 AllFound = false;
2727 for (unsigned l = 0; l != LElts; ++l) {
2728 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2729 if (LTypeInfo == FTypeInfo) {
2730 AllFound = true;
2731 break;
2732 }
2733 }
2734 if (!AllFound)
2735 break;
2736 }
2737 if (AllFound) {
2738 // Discard LFilter.
2739 NewClauses.erase(J);
2740 MakeNewInstruction = true;
2741 }
2742 // Move on to the next filter.
2743 }
2744 }
2745
2746 // If we changed any of the clauses, replace the old landingpad instruction
2747 // with a new one.
2748 if (MakeNewInstruction) {
2749 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002750 NewClauses.size());
2751 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2752 NLI->addClause(NewClauses[i]);
2753 // A landing pad with no clauses must have the cleanup flag set. It is
2754 // theoretically possible, though highly unlikely, that we eliminated all
2755 // clauses. If so, force the cleanup flag to true.
2756 if (NewClauses.empty())
2757 CleanupFlag = true;
2758 NLI->setCleanup(CleanupFlag);
2759 return NLI;
2760 }
2761
2762 // Even if none of the clauses changed, we may nonetheless have understood
2763 // that the cleanup flag is pointless. Clear it if so.
2764 if (LI.isCleanup() != CleanupFlag) {
2765 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2766 LI.setCleanup(CleanupFlag);
2767 return &LI;
2768 }
2769
Craig Topperf40110f2014-04-25 05:29:35 +00002770 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002771}
2772
Sanjay Patel84dca492015-09-21 15:33:26 +00002773/// Try to move the specified instruction from its current block into the
2774/// beginning of DestBlock, which can only happen if it's safe to move the
2775/// instruction past all of the instructions between it and the end of its
2776/// block.
Chris Lattner39c98bb2004-12-08 23:43:58 +00002777static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2778 assert(I->hasOneUse() && "Invariants didn't hold!");
2779
Bill Wendlinge86965e2011-08-15 21:14:31 +00002780 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002781 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002782 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002783 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002784
Chris Lattner39c98bb2004-12-08 23:43:58 +00002785 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002786 if (isa<AllocaInst>(I) && I->getParent() ==
2787 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002788 return false;
2789
David Majnemerfe3f9d12016-04-01 17:28:17 +00002790 // Do not sink into catchswitch blocks.
2791 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2792 return false;
2793
Fiona Glasera8b653a2015-11-03 22:23:39 +00002794 // Do not sink convergent call instructions.
2795 if (auto *CI = dyn_cast<CallInst>(I)) {
2796 if (CI->isConvergent())
2797 return false;
2798 }
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002799 // We can only sink load instructions if there is nothing between the load and
2800 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002801 if (I->mayReadFromMemory()) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002802 for (BasicBlock::iterator Scan = I->getIterator(),
2803 E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002804 Scan != E; ++Scan)
2805 if (Scan->mayWriteToMemory())
2806 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002807 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002808
Bill Wendling8ddfc092011-08-16 20:45:24 +00002809 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002810 I->moveBefore(&*InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002811 ++NumSunkInst;
2812 return true;
2813}
2814
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002815bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002816 while (!Worklist.isEmpty()) {
2817 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002818 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002819
Chris Lattner1443bc52006-05-11 17:11:52 +00002820 // Check to see if we can DCE the instruction.
Justin Bogner99798402016-08-05 01:06:44 +00002821 if (isInstructionTriviallyDead(I, &TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002822 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Sanjay Patel4b198802016-02-01 22:23:39 +00002823 eraseInstFromFunction(*I);
Chris Lattner905976b2009-08-30 06:13:40 +00002824 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002825 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002826 continue;
2827 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002828
Chris Lattner1443bc52006-05-11 17:11:52 +00002829 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002830 if (!I->use_empty() &&
2831 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Justin Bogner99798402016-08-05 01:06:44 +00002832 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002833 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002834
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002835 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002836 replaceInstUsesWith(*I, C);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002837 ++NumConstProp;
Justin Bogner99798402016-08-05 01:06:44 +00002838 if (isInstructionTriviallyDead(I, &TLI))
David Majnemer522a9112016-07-22 04:54:44 +00002839 eraseInstFromFunction(*I);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002840 MadeIRChange = true;
2841 continue;
2842 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002843 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002844
Matthias Braunc31032d2016-03-09 18:47:11 +00002845 // In general, it is possible for computeKnownBits to determine all bits in
2846 // a value even when the operands are not all constants.
Sanjay Patelc96f6db2016-09-16 21:20:36 +00002847 Type *Ty = I->getType();
2848 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2849 unsigned BitWidth = Ty->getScalarSizeInBits();
Hal Finkelf2199b22015-10-23 20:37:08 +00002850 APInt KnownZero(BitWidth, 0);
2851 APInt KnownOne(BitWidth, 0);
2852 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2853 if ((KnownZero | KnownOne).isAllOnesValue()) {
Sanjay Patelc96f6db2016-09-16 21:20:36 +00002854 Constant *C = ConstantInt::get(Ty, KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00002855 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2856 " from: " << *I << '\n');
2857
2858 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002859 replaceInstUsesWith(*I, C);
Hal Finkelf2199b22015-10-23 20:37:08 +00002860 ++NumConstProp;
Justin Bogner99798402016-08-05 01:06:44 +00002861 if (isInstructionTriviallyDead(I, &TLI))
David Majnemer522a9112016-07-22 04:54:44 +00002862 eraseInstFromFunction(*I);
Hal Finkelf2199b22015-10-23 20:37:08 +00002863 MadeIRChange = true;
2864 continue;
2865 }
2866 }
2867
Chris Lattner39c98bb2004-12-08 23:43:58 +00002868 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002869 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002870 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002871 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002872 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002873
Chris Lattner6b9044d2009-10-14 15:21:58 +00002874 // Get the block the use occurs in.
2875 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002876 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002877 else
2878 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002879
Chris Lattner39c98bb2004-12-08 23:43:58 +00002880 if (UserParent != BB) {
2881 bool UserIsSuccessor = false;
2882 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002883 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2884 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002885 UserIsSuccessor = true;
2886 break;
2887 }
2888
2889 // If the user is one of our immediate successors, and if that successor
2890 // only has us as a predecessors (we'd have to split the critical edge
2891 // otherwise), we can keep going.
Jun Bum Limec8b8cc2016-08-22 18:21:56 +00002892 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002893 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002894 if (TryToSinkInstruction(I, UserParent)) {
David Majnemerfe3f9d12016-04-01 17:28:17 +00002895 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002896 MadeIRChange = true;
2897 // We'll add uses of the sunk instruction below, but since sinking
2898 // can expose opportunities for it's *operands* add them to the
2899 // worklist
2900 for (Use &U : I->operands())
2901 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2902 Worklist.Add(OpI);
2903 }
2904 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002905 }
2906 }
2907
Chris Lattner022a5822009-08-30 07:44:24 +00002908 // Now that we have an instruction, try combining it to simplify it.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002909 Builder->SetInsertPoint(I);
Eli Friedman96254a02011-05-18 01:28:27 +00002910 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002911
Reid Spencer755d0e72007-03-26 17:44:01 +00002912#ifndef NDEBUG
2913 std::string OrigI;
2914#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002915 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002916 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002917
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002918 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002919 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002920 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002921 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002922 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002923 << " New = " << *Result << '\n');
2924
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002925 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002926 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002927 // Everything uses the new instruction now.
2928 I->replaceAllUsesWith(Result);
2929
Jim Grosbache7abae02011-10-05 20:53:43 +00002930 // Move the name to the new instruction first.
2931 Result->takeName(I);
2932
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002933 // Push the new instruction and any users onto the worklist.
2934 Worklist.Add(Result);
2935 Worklist.AddUsersToWorkList(*Result);
2936
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002937 // Insert the new instruction into the basic block...
2938 BasicBlock *InstParent = I->getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002939 BasicBlock::iterator InsertPos = I->getIterator();
Chris Lattner7515cab2004-11-14 19:13:23 +00002940
Eli Friedmana49b8282011-11-01 04:49:29 +00002941 // If we replace a PHI with something that isn't a PHI, fix up the
2942 // insertion point.
2943 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2944 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002945
2946 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002947
Sanjay Patel4b198802016-02-01 22:23:39 +00002948 eraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002949 } else {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002950 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002951 << " New = " << *I << '\n');
Chris Lattner7d2a5392004-03-13 23:54:27 +00002952
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002953 // If the instruction was modified, it's possible that it is now dead.
2954 // if so, remove it.
Justin Bogner99798402016-08-05 01:06:44 +00002955 if (isInstructionTriviallyDead(I, &TLI)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002956 eraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002957 } else {
Chris Lattner905976b2009-08-30 06:13:40 +00002958 Worklist.Add(I);
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002959 Worklist.AddUsersToWorkList(*I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002960 }
Chris Lattner053c0932002-05-14 15:24:07 +00002961 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002962 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002963 }
2964 }
2965
Chris Lattner97fd3592009-08-30 05:55:36 +00002966 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002967 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002968}
2969
Sanjay Patel84dca492015-09-21 15:33:26 +00002970/// Walk the function in depth-first order, adding all reachable code to the
2971/// worklist.
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002972///
2973/// This has a couple of tricks to make the code faster and more powerful. In
2974/// particular, we constant fold and DCE instructions as we go, to avoid adding
2975/// them to the worklist (this significantly speeds up instcombine on code where
2976/// many instructions are dead or constant). Additionally, if we find a branch
2977/// whose condition is a known constant, we only visit the reachable successors.
2978///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002979static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2980 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002981 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002982 const TargetLibraryInfo *TLI) {
2983 bool MadeIRChange = false;
2984 SmallVector<BasicBlock*, 256> Worklist;
2985 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002986
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002987 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
David Majnemerd536f232016-07-29 03:27:26 +00002988 DenseMap<Constant *, Constant *> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002989
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002990 do {
2991 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002992
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002993 // We have now visited this block! If we've already been here, ignore it.
2994 if (!Visited.insert(BB).second)
2995 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00002996
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002997 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002998 Instruction *Inst = &*BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00002999
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003000 // DCE instruction if trivially dead.
3001 if (isInstructionTriviallyDead(Inst, TLI)) {
3002 ++NumDeadInst;
3003 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3004 Inst->eraseFromParent();
3005 continue;
3006 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00003007
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003008 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00003009 if (!Inst->use_empty() &&
3010 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003011 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3012 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3013 << *Inst << '\n');
3014 Inst->replaceAllUsesWith(C);
3015 ++NumConstProp;
David Majnemer522a9112016-07-22 04:54:44 +00003016 if (isInstructionTriviallyDead(Inst, TLI))
3017 Inst->eraseFromParent();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003018 continue;
3019 }
3020
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003021 // See if we can constant fold its operands.
3022 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end(); i != e;
3023 ++i) {
David Majnemerd536f232016-07-29 03:27:26 +00003024 if (!isa<ConstantVector>(i) && !isa<ConstantExpr>(i))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003025 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003026
David Majnemerd536f232016-07-29 03:27:26 +00003027 auto *C = cast<Constant>(i);
3028 Constant *&FoldRes = FoldedConstants[C];
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003029 if (!FoldRes)
David Majnemerd536f232016-07-29 03:27:26 +00003030 FoldRes = ConstantFoldConstant(C, DL, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003031 if (!FoldRes)
David Majnemerd536f232016-07-29 03:27:26 +00003032 FoldRes = C;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003033
David Majnemerd536f232016-07-29 03:27:26 +00003034 if (FoldRes != C) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003035 *i = FoldRes;
3036 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003037 }
3038 }
3039
3040 InstrsForInstCombineWorklist.push_back(Inst);
3041 }
3042
3043 // Recursively visit successors. If this is a branch or switch on a
3044 // constant, only visit the reachable successor.
3045 TerminatorInst *TI = BB->getTerminator();
3046 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3047 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3048 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3049 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3050 Worklist.push_back(ReachableBB);
3051 continue;
3052 }
3053 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3054 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3055 // See if this is an explicit destination.
3056 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3057 i != e; ++i)
3058 if (i.getCaseValue() == Cond) {
3059 BasicBlock *ReachableBB = i.getCaseSuccessor();
3060 Worklist.push_back(ReachableBB);
3061 continue;
3062 }
3063
3064 // Otherwise it is the default destination.
3065 Worklist.push_back(SI->getDefaultDest());
3066 continue;
3067 }
3068 }
3069
Pete Cooperebcd7482015-08-06 20:22:46 +00003070 for (BasicBlock *SuccBB : TI->successors())
3071 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003072 } while (!Worklist.empty());
3073
3074 // Once we've found all of the instructions to add to instcombine's worklist,
3075 // add them in reverse order. This way instcombine will visit from the top
3076 // of the function down. This jives well with the way that it adds all uses
3077 // of instructions to the worklist after doing a transformation, thus avoiding
3078 // some N^2 behavior in pathological cases.
Craig Topper42526d32015-10-22 16:35:56 +00003079 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003080
3081 return MadeIRChange;
3082}
3083
3084/// \brief Populate the IC worklist from a function, and prune any dead basic
3085/// blocks discovered in the process.
3086///
3087/// This also does basic constant propagation and other forward fixing to make
3088/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003089static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003090 TargetLibraryInfo *TLI,
3091 InstCombineWorklist &ICWorklist) {
3092 bool MadeIRChange = false;
3093
3094 // Do a depth-first traversal of the function, populate the worklist with
3095 // the reachable instructions. Ignore blocks that are not reachable. Keep
3096 // track of which blocks we visit.
Matthias Braunb30f2f512016-01-30 01:24:31 +00003097 SmallPtrSet<BasicBlock *, 32> Visited;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003098 MadeIRChange |=
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003099 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003100
3101 // Do a quick scan over the function. If we find any blocks that are
3102 // unreachable, remove any instructions inside of them. This prevents
3103 // the instcombine code from having to deal with some bad special cases.
Benjamin Kramer135f7352016-06-26 12:28:59 +00003104 for (BasicBlock &BB : F) {
3105 if (Visited.count(&BB))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003106 continue;
3107
Benjamin Kramer135f7352016-06-26 12:28:59 +00003108 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer35c46d32016-01-24 05:26:18 +00003109 MadeIRChange |= NumDeadInstInBB > 0;
3110 NumDeadInst += NumDeadInstInBB;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003111 }
3112
3113 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00003114}
3115
Mehdi Amini46a43552015-03-04 18:43:29 +00003116static bool
3117combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003118 AliasAnalysis *AA, AssumptionCache &AC,
3119 TargetLibraryInfo &TLI, DominatorTree &DT,
Matthias Braunc31032d2016-03-09 18:47:11 +00003120 bool ExpensiveCombines = true,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003121 LoopInfo *LI = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003122 auto &DL = F.getParent()->getDataLayout();
Matthias Braunc31032d2016-03-09 18:47:11 +00003123 ExpensiveCombines |= EnableExpensiveCombines;
Chandler Carruth83ba2692015-01-24 04:19:17 +00003124
3125 /// Builder - This is an IRBuilder that automatically inserts new
3126 /// instructions into the worklist when they are created.
Justin Bogner19dd0da2016-08-04 23:41:01 +00003127 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3128 F.getContext(), TargetFolder(DL),
3129 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
3130 Worklist.Add(I);
3131
3132 using namespace llvm::PatternMatch;
3133 if (match(I, m_Intrinsic<Intrinsic::assume>()))
3134 AC.registerAssumption(cast<CallInst>(I));
3135 }));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003136
3137 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3138 // by instcombiner.
3139 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3140
3141 // Iterate while there is work to do.
3142 int Iteration = 0;
3143 for (;;) {
3144 ++Iteration;
3145 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3146 << F.getName() << "\n");
3147
Sanjay Patel24b77d12016-01-31 16:33:33 +00003148 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003149
Matthias Braunc31032d2016-03-09 18:47:11 +00003150 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
Justin Bogner99798402016-08-05 01:06:44 +00003151 AA, AC, TLI, DT, DL, LI);
Sanjay Patel24b77d12016-01-31 16:33:33 +00003152 Changed |= IC.run();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003153
3154 if (!Changed)
3155 break;
3156 }
3157
3158 return DbgDeclaresChanged || Iteration > 1;
3159}
3160
3161PreservedAnalyses InstCombinePass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00003162 FunctionAnalysisManager &AM) {
Chandler Carruthb47f8012016-03-11 11:05:24 +00003163 auto &AC = AM.getResult<AssumptionAnalysis>(F);
3164 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3165 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003166
Chandler Carruthb47f8012016-03-11 11:05:24 +00003167 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003168
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003169 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
Matthias Braunc31032d2016-03-09 18:47:11 +00003170 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
3171 ExpensiveCombines, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003172 // No changes, all analyses are preserved.
3173 return PreservedAnalyses::all();
3174
3175 // Mark all the analyses that instcombine updates as preserved.
Michael Kuperstein835facd2016-06-28 00:54:12 +00003176 // FIXME: This should also 'preserve the CFG'.
Chandler Carruth83ba2692015-01-24 04:19:17 +00003177 PreservedAnalyses PA;
3178 PA.preserve<DominatorTreeAnalysis>();
3179 return PA;
3180}
3181
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003182void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3183 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003184 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003185 AU.addRequired<AssumptionCacheTracker>();
3186 AU.addRequired<TargetLibraryInfoWrapperPass>();
3187 AU.addRequired<DominatorTreeWrapperPass>();
3188 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +00003189 AU.addPreserved<AAResultsWrapperPass>();
3190 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003191 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003192}
3193
3194bool InstructionCombiningPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00003195 if (skipFunction(F))
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003196 return false;
3197
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003198 // Required analyses.
Chandler Carruth7b560d42015-09-09 17:55:00 +00003199 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003200 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003201 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3202 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003203
3204 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003205 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3206 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3207
Matthias Braunc31032d2016-03-09 18:47:11 +00003208 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
3209 ExpensiveCombines, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003210}
3211
3212char InstructionCombiningPass::ID = 0;
3213INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3214 "Combine redundant instructions", false, false)
3215INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
3216INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3217INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +00003218INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3219INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003220INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3221 "Combine redundant instructions", false, false)
3222
3223// Initialization Routines
3224void llvm::initializeInstCombine(PassRegistry &Registry) {
3225 initializeInstructionCombiningPassPass(Registry);
3226}
3227
3228void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3229 initializeInstructionCombiningPassPass(*unwrap(R));
3230}
3231
Matthias Braunc31032d2016-03-09 18:47:11 +00003232FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3233 return new InstructionCombiningPass(ExpensiveCombines);
Chris Lattner04805fa2002-02-26 21:46:54 +00003234}