blob: bc168dd57765efac84f29495009134e3469dfb82 [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"
Daniel Jasperaec2fa32016-12-19 08:22:17 +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
Davide Italiano2133bf52017-02-07 17:56:50 +000085static cl::opt<unsigned>
86MaxArraySize("instcombine-maxarray-size", cl::init(1024),
87 cl::desc("Maximum array size considered when doing a combine"));
88
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000089Value *InstCombiner::EmitGEPOffset(User *GEP) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000090 return llvm::EmitGEPOffset(Builder, DL, GEP);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +000091}
92
Sanjay Patel55dcd402015-09-21 16:09:37 +000093/// Return true if it is desirable to convert an integer computation from a
94/// given bit width to a new bit width.
Sanjay Patel2217f752017-01-31 17:25:42 +000095/// We don't want to convert from a legal to an illegal type or from a smaller
Sanjay Patel0fe32ac2017-02-03 23:13:11 +000096/// to a larger illegal type. A width of '1' is always treated as a legal type
97/// because i1 is a fundamental type in IR, and there are many specialized
98/// optimizations for i1 types.
Sanjay Patel2217f752017-01-31 17:25:42 +000099bool InstCombiner::shouldChangeType(unsigned FromWidth,
Sanjay Patel55dcd402015-09-21 16:09:37 +0000100 unsigned ToWidth) const {
Sanjay Patel0fe32ac2017-02-03 23:13:11 +0000101 bool FromLegal = FromWidth == 1 || DL.isLegalInteger(FromWidth);
102 bool ToLegal = ToWidth == 1 || DL.isLegalInteger(ToWidth);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000103
Chris Lattner1559bed2009-11-10 07:23:37 +0000104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
107 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000108
Chris Lattner1559bed2009-11-10 07:23:37 +0000109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
112 return false;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000113
Chris Lattner1559bed2009-11-10 07:23:37 +0000114 return true;
115}
116
Sanjay Patel55dcd402015-09-21 16:09:37 +0000117/// Return true if it is desirable to convert a computation from 'From' to 'To'.
Sanjay Patel2217f752017-01-31 17:25:42 +0000118/// We don't want to convert from a legal to an illegal type or from a smaller
Sanjay Patel0fe32ac2017-02-03 23:13:11 +0000119/// to a larger illegal type. i1 is always treated as a legal type because it is
120/// a fundamental type in IR, and there are many specialized optimizations for
121/// i1 types.
Sanjay Patel2217f752017-01-31 17:25:42 +0000122bool InstCombiner::shouldChangeType(Type *From, Type *To) const {
Sanjay Patel55dcd402015-09-21 16:09:37 +0000123 assert(From->isIntegerTy() && To->isIntegerTy());
124
125 unsigned FromWidth = From->getPrimitiveSizeInBits();
126 unsigned ToWidth = To->getPrimitiveSizeInBits();
Sanjay Patel2217f752017-01-31 17:25:42 +0000127 return shouldChangeType(FromWidth, ToWidth);
Sanjay Patel55dcd402015-09-21 16:09:37 +0000128}
129
Nick Lewyckyde492782011-08-14 01:45:19 +0000130// Return true, if No Signed Wrap should be maintained for I.
131// The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
132// where both B and C should be ConstantInts, results in a constant that does
133// not overflow. This function only handles the Add and Sub opcodes. For
134// all other opcodes, the function conservatively returns false.
135static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
136 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000137 if (!OBO || !OBO->hasNoSignedWrap())
Nick Lewyckyde492782011-08-14 01:45:19 +0000138 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000139
140 // We reason about Add and Sub Only.
141 Instruction::BinaryOps Opcode = I.getOpcode();
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000142 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
Nick Lewyckyde492782011-08-14 01:45:19 +0000143 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000144
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000145 const APInt *BVal, *CVal;
146 if (!match(B, m_APInt(BVal)) || !match(C, m_APInt(CVal)))
Nick Lewyckyde492782011-08-14 01:45:19 +0000147 return false;
Nick Lewyckyde492782011-08-14 01:45:19 +0000148
Nick Lewyckyde492782011-08-14 01:45:19 +0000149 bool Overflow = false;
Sanjay Patel2cbe6792016-06-24 20:36:34 +0000150 if (Opcode == Instruction::Add)
151 BVal->sadd_ov(*CVal, Overflow);
152 else
153 BVal->ssub_ov(*CVal, Overflow);
Nick Lewyckyde492782011-08-14 01:45:19 +0000154
155 return !Overflow;
156}
157
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000158/// Conservatively clears subclassOptionalData after a reassociation or
159/// commutation. We preserve fast-math flags when applicable as they can be
160/// preserved.
161static void ClearSubclassDataAfterReassociation(BinaryOperator &I) {
162 FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I);
163 if (!FPMO) {
164 I.clearSubclassOptionalData();
165 return;
166 }
167
168 FastMathFlags FMF = I.getFastMathFlags();
169 I.clearSubclassOptionalData();
170 I.setFastMathFlags(FMF);
171}
172
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000173/// Combine constant operands of associative operations either before or after a
174/// cast to eliminate one of the associative operations:
175/// (op (cast (op X, C2)), C1) --> (cast (op X, op (C1, C2)))
176/// (op (cast (op X, C2)), C1) --> (op (cast X), op (C1, C2))
177static bool simplifyAssocCastAssoc(BinaryOperator *BinOp1) {
178 auto *Cast = dyn_cast<CastInst>(BinOp1->getOperand(0));
179 if (!Cast || !Cast->hasOneUse())
180 return false;
181
182 // TODO: Enhance logic for other casts and remove this check.
183 auto CastOpcode = Cast->getOpcode();
184 if (CastOpcode != Instruction::ZExt)
185 return false;
186
187 // TODO: Enhance logic for other BinOps and remove this check.
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000188 if (!BinOp1->isBitwiseLogicOp())
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000189 return false;
190
Sanjay Patel1e6ca442016-11-22 22:54:36 +0000191 auto AssocOpcode = BinOp1->getOpcode();
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000192 auto *BinOp2 = dyn_cast<BinaryOperator>(Cast->getOperand(0));
193 if (!BinOp2 || !BinOp2->hasOneUse() || BinOp2->getOpcode() != AssocOpcode)
194 return false;
195
196 Constant *C1, *C2;
197 if (!match(BinOp1->getOperand(1), m_Constant(C1)) ||
198 !match(BinOp2->getOperand(1), m_Constant(C2)))
199 return false;
200
201 // TODO: This assumes a zext cast.
202 // Eg, if it was a trunc, we'd cast C1 to the source type because casting C2
203 // to the destination type might lose bits.
204
205 // Fold the constants together in the destination type:
206 // (op (cast (op X, C2)), C1) --> (op (cast X), FoldedC)
207 Type *DestTy = C1->getType();
208 Constant *CastC2 = ConstantExpr::getCast(CastOpcode, C2, DestTy);
209 Constant *FoldedC = ConstantExpr::get(AssocOpcode, C1, CastC2);
210 Cast->setOperand(0, BinOp2->getOperand(0));
211 BinOp1->setOperand(1, FoldedC);
212 return true;
213}
214
Sanjay Patel84dca492015-09-21 15:33:26 +0000215/// This performs a few simplifications for operators that are associative or
216/// commutative:
217///
218/// Commutative operators:
219///
220/// 1. Order operands such that they are listed from right (least complex) to
221/// left (most complex). This puts constants before unary operators before
222/// binary operators.
223///
224/// Associative operators:
225///
226/// 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
227/// 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
228///
229/// Associative and commutative operators:
230///
231/// 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
232/// 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
233/// 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
234/// if C1 and C2 are constants.
Duncan Sands641baf12010-11-13 15:10:37 +0000235bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000236 Instruction::BinaryOps Opcode = I.getOpcode();
Duncan Sands641baf12010-11-13 15:10:37 +0000237 bool Changed = false;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238
Duncan Sands641baf12010-11-13 15:10:37 +0000239 do {
240 // Order operands such that they are listed from right (least complex) to
241 // left (most complex). This puts constants before unary operators before
242 // binary operators.
243 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
244 getComplexity(I.getOperand(1)))
245 Changed = !I.swapOperands();
246
247 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
248 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
249
250 if (I.isAssociative()) {
251 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
252 if (Op0 && Op0->getOpcode() == Opcode) {
253 Value *A = Op0->getOperand(0);
254 Value *B = Op0->getOperand(1);
255 Value *C = I.getOperand(1);
256
257 // Does "B op C" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000258 if (Value *V = SimplifyBinOp(Opcode, B, C, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000259 // It simplifies to V. Form "A op V".
260 I.setOperand(0, A);
261 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000262 // Conservatively clear the optional flags, since they may not be
263 // preserved by the reassociation.
Nick Lewyckyae13df62011-08-14 03:41:33 +0000264 if (MaintainNoSignedWrap(I, B, C) &&
Bill Wendlingea6397f2012-07-19 00:11:40 +0000265 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
Nick Lewyckyae13df62011-08-14 03:41:33 +0000266 // Note: this is only valid because SimplifyBinOp doesn't look at
267 // the operands to Op0.
Nick Lewyckyde492782011-08-14 01:45:19 +0000268 I.clearSubclassOptionalData();
269 I.setHasNoSignedWrap(true);
270 } else {
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000271 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000272 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000273
Duncan Sands641baf12010-11-13 15:10:37 +0000274 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000275 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000276 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000277 }
Duncan Sands641baf12010-11-13 15:10:37 +0000278 }
279
280 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
281 if (Op1 && Op1->getOpcode() == Opcode) {
282 Value *A = I.getOperand(0);
283 Value *B = Op1->getOperand(0);
284 Value *C = Op1->getOperand(1);
285
286 // Does "A op B" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000287 if (Value *V = SimplifyBinOp(Opcode, A, B, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000288 // It simplifies to V. Form "V op C".
289 I.setOperand(0, V);
290 I.setOperand(1, C);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000291 // Conservatively clear the optional flags, since they may not be
292 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000293 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000294 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000295 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000296 continue;
297 }
298 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000299 }
Duncan Sands641baf12010-11-13 15:10:37 +0000300
301 if (I.isAssociative() && I.isCommutative()) {
Sanjay Patelf9d2b202016-07-16 15:20:19 +0000302 if (simplifyAssocCastAssoc(&I)) {
303 Changed = true;
304 ++NumReassoc;
305 continue;
306 }
307
Duncan Sands641baf12010-11-13 15:10:37 +0000308 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
309 if (Op0 && Op0->getOpcode() == Opcode) {
310 Value *A = Op0->getOperand(0);
311 Value *B = Op0->getOperand(1);
312 Value *C = I.getOperand(1);
313
314 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000316 // It simplifies to V. Form "V op B".
317 I.setOperand(0, V);
318 I.setOperand(1, B);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000319 // Conservatively clear the optional flags, since they may not be
320 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000321 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000322 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000323 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000324 continue;
325 }
326 }
327
328 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
329 if (Op1 && Op1->getOpcode() == Opcode) {
330 Value *A = I.getOperand(0);
331 Value *B = Op1->getOperand(0);
332 Value *C = Op1->getOperand(1);
333
334 // Does "C op A" simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000335 if (Value *V = SimplifyBinOp(Opcode, C, A, DL)) {
Duncan Sands641baf12010-11-13 15:10:37 +0000336 // It simplifies to V. Form "B op V".
337 I.setOperand(0, B);
338 I.setOperand(1, V);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000339 // Conservatively clear the optional flags, since they may not be
340 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000341 ClearSubclassDataAfterReassociation(I);
Duncan Sands641baf12010-11-13 15:10:37 +0000342 Changed = true;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000343 ++NumReassoc;
Duncan Sands641baf12010-11-13 15:10:37 +0000344 continue;
345 }
346 }
347
348 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
349 // if C1 and C2 are constants.
350 if (Op0 && Op1 &&
351 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
352 isa<Constant>(Op0->getOperand(1)) &&
353 isa<Constant>(Op1->getOperand(1)) &&
354 Op0->hasOneUse() && Op1->hasOneUse()) {
355 Value *A = Op0->getOperand(0);
356 Constant *C1 = cast<Constant>(Op0->getOperand(1));
357 Value *B = Op1->getOperand(0);
358 Constant *C2 = cast<Constant>(Op1->getOperand(1));
359
360 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
Nick Lewyckyde492782011-08-14 01:45:19 +0000361 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
Owen Anderson1664dc82014-01-20 07:44:53 +0000362 if (isa<FPMathOperator>(New)) {
363 FastMathFlags Flags = I.getFastMathFlags();
364 Flags &= Op0->getFastMathFlags();
365 Flags &= Op1->getFastMathFlags();
366 New->setFastMathFlags(Flags);
367 }
Eli Friedman35211c62011-05-27 00:19:40 +0000368 InsertNewInstWith(New, I);
Eli Friedman41e509a2011-05-18 23:58:37 +0000369 New->takeName(Op1);
Duncan Sands641baf12010-11-13 15:10:37 +0000370 I.setOperand(0, New);
371 I.setOperand(1, Folded);
Dan Gohmanc6f0bda2011-02-02 02:05:46 +0000372 // Conservatively clear the optional flags, since they may not be
373 // preserved by the reassociation.
Michael Ilseman1dd6f2a2013-02-07 01:40:15 +0000374 ClearSubclassDataAfterReassociation(I);
Nick Lewyckyde492782011-08-14 01:45:19 +0000375
Duncan Sands641baf12010-11-13 15:10:37 +0000376 Changed = true;
377 continue;
378 }
379 }
380
381 // No further simplifications.
382 return Changed;
383 } while (1);
Chris Lattner260ab202002-04-18 17:39:14 +0000384}
Chris Lattnerca081252001-12-14 16:52:21 +0000385
Sanjay Patel84dca492015-09-21 15:33:26 +0000386/// Return whether "X LOp (Y ROp Z)" is always equal to
Duncan Sands22df7412010-11-23 15:25:34 +0000387/// "(X LOp Y) ROp (X LOp Z)".
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000388static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
389 Instruction::BinaryOps ROp) {
390 switch (LOp) {
391 default:
392 return false;
393
394 case Instruction::And:
395 // And distributes over Or and Xor.
396 switch (ROp) {
397 default:
398 return false;
399 case Instruction::Or:
400 case Instruction::Xor:
401 return true;
402 }
403
404 case Instruction::Mul:
405 // Multiplication distributes over addition and subtraction.
406 switch (ROp) {
407 default:
408 return false;
409 case Instruction::Add:
410 case Instruction::Sub:
411 return true;
412 }
413
414 case Instruction::Or:
415 // Or distributes over And.
416 switch (ROp) {
417 default:
418 return false;
419 case Instruction::And:
420 return true;
421 }
422 }
423}
424
Sanjay Patel84dca492015-09-21 15:33:26 +0000425/// Return whether "(X LOp Y) ROp Z" is always equal to
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000426/// "(X ROp Z) LOp (Y ROp Z)".
427static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
428 Instruction::BinaryOps ROp) {
429 if (Instruction::isCommutative(ROp))
430 return LeftDistributesOverRight(ROp, LOp);
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000431
432 switch (LOp) {
433 default:
434 return false;
435 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
436 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
437 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
438 case Instruction::And:
439 case Instruction::Or:
440 case Instruction::Xor:
441 switch (ROp) {
442 default:
443 return false;
444 case Instruction::Shl:
445 case Instruction::LShr:
446 case Instruction::AShr:
447 return true;
448 }
449 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000450 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
451 // but this requires knowing that the addition does not overflow and other
452 // such subtleties.
453 return false;
454}
455
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000456/// This function returns identity value for given opcode, which can be used to
457/// factor patterns like (X * 2) + X ==> (X * 2) + (X * 1) ==> X * (2 + 1).
458static Value *getIdentityValue(Instruction::BinaryOps OpCode, Value *V) {
459 if (isa<Constant>(V))
460 return nullptr;
461
462 if (OpCode == Instruction::Mul)
463 return ConstantInt::get(V->getType(), 1);
464
465 // TODO: We can handle other cases e.g. Instruction::And, Instruction::Or etc.
466
467 return nullptr;
468}
469
470/// This function factors binary ops which can be combined using distributive
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000471/// laws. This function tries to transform 'Op' based TopLevelOpcode to enable
472/// factorization e.g for ADD(SHL(X , 2), MUL(X, 5)), When this function called
473/// with TopLevelOpcode == Instruction::Add and Op = SHL(X, 2), transforms
474/// SHL(X, 2) to MUL(X, 4) i.e. returns Instruction::Mul with LHS set to 'X' and
475/// RHS to 4.
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000476static Instruction::BinaryOps
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000477getBinOpsForFactorization(Instruction::BinaryOps TopLevelOpcode,
478 BinaryOperator *Op, Value *&LHS, Value *&RHS) {
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000479 if (!Op)
480 return Instruction::BinaryOpsEnd;
481
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000482 LHS = Op->getOperand(0);
483 RHS = Op->getOperand(1);
484
485 switch (TopLevelOpcode) {
486 default:
487 return Op->getOpcode();
488
489 case Instruction::Add:
490 case Instruction::Sub:
491 if (Op->getOpcode() == Instruction::Shl) {
492 if (Constant *CST = dyn_cast<Constant>(Op->getOperand(1))) {
493 // The multiplier is really 1 << CST.
494 RHS = ConstantExpr::getShl(ConstantInt::get(Op->getType(), 1), CST);
495 return Instruction::Mul;
496 }
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000497 }
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000498 return Op->getOpcode();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000499 }
500
501 // TODO: We can add other conversions e.g. shr => div etc.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000502}
503
504/// This tries to simplify binary operations by factorizing out common terms
505/// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
506static Value *tryFactorization(InstCombiner::BuilderTy *Builder,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000507 const DataLayout &DL, BinaryOperator &I,
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000508 Instruction::BinaryOps InnerOpcode, Value *A,
509 Value *B, Value *C, Value *D) {
510
511 // If any of A, B, C, D are null, we can not factor I, return early.
512 // Checking A and C should be enough.
513 if (!A || !C || !B || !D)
514 return nullptr;
515
David Majnemer4c3753c2015-05-22 23:02:11 +0000516 Value *V = nullptr;
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000517 Value *SimplifiedInst = nullptr;
518 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
519 Instruction::BinaryOps TopLevelOpcode = I.getOpcode();
520
521 // Does "X op' Y" always equal "Y op' X"?
522 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
523
524 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
525 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
526 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
527 // commutative case, "(A op' B) op (C op' A)"?
528 if (A == C || (InnerCommutative && A == D)) {
529 if (A != C)
530 std::swap(C, D);
531 // Consider forming "A op' (B op D)".
532 // If "B op D" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000533 V = SimplifyBinOp(TopLevelOpcode, B, D, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000534 // If "B op D" doesn't simplify then only go on if both of the existing
535 // operations "A op' B" and "C op' D" will be zapped as no longer used.
536 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
537 V = Builder->CreateBinOp(TopLevelOpcode, B, D, RHS->getName());
538 if (V) {
539 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, A, V);
540 }
541 }
542
543 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
544 if (!SimplifiedInst && RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
545 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
546 // commutative case, "(A op' B) op (B op' D)"?
547 if (B == D || (InnerCommutative && B == C)) {
548 if (B != D)
549 std::swap(C, D);
550 // Consider forming "(A op C) op' B".
551 // If "A op C" simplifies then it can be formed with no cost.
David Majnemer4c3753c2015-05-22 23:02:11 +0000552 V = SimplifyBinOp(TopLevelOpcode, A, C, DL);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000553
554 // If "A op C" doesn't simplify then only go on if both of the existing
555 // operations "A op' B" and "C op' D" will be zapped as no longer used.
556 if (!V && LHS->hasOneUse() && RHS->hasOneUse())
557 V = Builder->CreateBinOp(TopLevelOpcode, A, C, LHS->getName());
558 if (V) {
559 SimplifiedInst = Builder->CreateBinOp(InnerOpcode, V, B);
560 }
561 }
562
563 if (SimplifiedInst) {
564 ++NumFactor;
565 SimplifiedInst->takeName(&I);
566
567 // Check if we can add NSW flag to SimplifiedInst. If so, set NSW flag.
568 // TODO: Check for NUW.
569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(SimplifiedInst)) {
570 if (isa<OverflowingBinaryOperator>(SimplifiedInst)) {
571 bool HasNSW = false;
572 if (isa<OverflowingBinaryOperator>(&I))
573 HasNSW = I.hasNoSignedWrap();
574
Sanjay Patelcf4c90f2017-02-06 17:16:16 +0000575 if (auto *LOBO = dyn_cast<OverflowingBinaryOperator>(LHS))
576 HasNSW &= LOBO->hasNoSignedWrap();
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000577
Sanjay Patelcf4c90f2017-02-06 17:16:16 +0000578 if (auto *ROBO = dyn_cast<OverflowingBinaryOperator>(RHS))
579 HasNSW &= ROBO->hasNoSignedWrap();
David Majnemer4c3753c2015-05-22 23:02:11 +0000580
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000581 // We can propagate 'nsw' if we know that
David Majnemer4c3753c2015-05-22 23:02:11 +0000582 // %Y = mul nsw i16 %X, C
583 // %Z = add nsw i16 %Y, %X
584 // =>
585 // %Z = mul nsw i16 %X, C+1
586 //
587 // iff C+1 isn't INT_MIN
588 const APInt *CInt;
589 if (TopLevelOpcode == Instruction::Add &&
590 InnerOpcode == Instruction::Mul)
591 if (match(V, m_APInt(CInt)) && !CInt->isMinSignedValue())
592 BO->setHasNoSignedWrap(HasNSW);
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000593 }
594 }
595 }
596 return SimplifiedInst;
597}
598
Sanjay Patel84dca492015-09-21 15:33:26 +0000599/// This tries to simplify binary operations which some other binary operation
600/// distributes over either by factorizing out common terms
601/// (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this results in
602/// simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is a win).
603/// Returns the simplified value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000604Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
605 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
606 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
607 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000608
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000609 // Factorization.
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000610 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Dinesh Dwivedi4919bbe2014-08-26 08:53:32 +0000611 auto TopLevelOpcode = I.getOpcode();
612 auto LHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op0, A, B);
613 auto RHSOpcode = getBinOpsForFactorization(TopLevelOpcode, Op1, C, D);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000614
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000615 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
616 // a common term.
617 if (LHSOpcode == RHSOpcode) {
618 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, C, D))
619 return V;
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000620 }
621
Dinesh Dwivedib62e52e2014-06-19 08:29:18 +0000622 // The instruction has the form "(A op' B) op (C)". Try to factorize common
623 // term.
624 if (Value *V = tryFactorization(Builder, DL, I, LHSOpcode, A, B, RHS,
625 getIdentityValue(LHSOpcode, RHS)))
626 return V;
627
628 // The instruction has the form "(B) op (C op' D)". Try to factorize common
629 // term.
630 if (Value *V = tryFactorization(Builder, DL, I, RHSOpcode, LHS,
631 getIdentityValue(RHSOpcode, LHS), C, D))
632 return V;
633
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000634 // Expansion.
635 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
636 // The instruction has the form "(A op' B) op C". See if expanding it out
637 // to "(A op C) op' (B op C)" results in simplifications.
638 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
639 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
640
641 // Do "A op C" and "B op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000642 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, DL))
643 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000644 // They do! Return "L op' R".
645 ++NumExpand;
646 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
647 if ((L == A && R == B) ||
648 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
649 return Op0;
650 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000651 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000652 return V;
653 // Otherwise, create a new instruction.
654 C = Builder->CreateBinOp(InnerOpcode, L, R);
655 C->takeName(&I);
656 return C;
657 }
658 }
659
660 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
661 // The instruction has the form "A op (B op' C)". See if expanding it out
662 // to "(A op B) op' (A op C)" results in simplifications.
663 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
664 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
665
666 // Do "A op B" and "A op C" both simplify?
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000667 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, DL))
668 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, DL)) {
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000669 // They do! Return "L op' R".
670 ++NumExpand;
671 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
672 if ((L == B && R == C) ||
673 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
674 return Op1;
675 // Otherwise return "L op' R" if it simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000676 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, DL))
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000677 return V;
678 // Otherwise, create a new instruction.
679 A = Builder->CreateBinOp(InnerOpcode, L, R);
680 A->takeName(&I);
681 return A;
682 }
683 }
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000684
David Majnemer33b6f822015-07-14 22:39:23 +0000685 // (op (select (a, c, b)), (select (a, d, b))) -> (select (a, (op c, d), 0))
686 // (op (select (a, b, c)), (select (a, b, d))) -> (select (a, 0, (op c, d)))
687 if (auto *SI0 = dyn_cast<SelectInst>(LHS)) {
688 if (auto *SI1 = dyn_cast<SelectInst>(RHS)) {
689 if (SI0->getCondition() == SI1->getCondition()) {
690 Value *SI = nullptr;
691 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getFalseValue(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000692 SI1->getFalseValue(), DL, &TLI, &DT, &AC))
David Majnemer33b6f822015-07-14 22:39:23 +0000693 SI = Builder->CreateSelect(SI0->getCondition(),
694 Builder->CreateBinOp(TopLevelOpcode,
695 SI0->getTrueValue(),
696 SI1->getTrueValue()),
697 V);
698 if (Value *V = SimplifyBinOp(TopLevelOpcode, SI0->getTrueValue(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000699 SI1->getTrueValue(), DL, &TLI, &DT, &AC))
David Majnemer33b6f822015-07-14 22:39:23 +0000700 SI = Builder->CreateSelect(
701 SI0->getCondition(), V,
702 Builder->CreateBinOp(TopLevelOpcode, SI0->getFalseValue(),
703 SI1->getFalseValue()));
704 if (SI) {
705 SI->takeName(&I);
706 return SI;
707 }
708 }
709 }
710 }
711
Craig Topperf40110f2014-04-25 05:29:35 +0000712 return nullptr;
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000713}
714
Sanjay Patel84dca492015-09-21 15:33:26 +0000715/// Given a 'sub' instruction, return the RHS of the instruction if the LHS is a
716/// constant zero (which is the 'negate' form).
Chris Lattner2188e402010-01-04 07:37:31 +0000717Value *InstCombiner::dyn_castNegVal(Value *V) const {
Owen Andersonbb2501b2009-07-13 22:18:28 +0000718 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000719 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000720
Chris Lattner9ad0d552004-12-14 20:08:06 +0000721 // Constants can be considered to be negated values if they can be folded.
722 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000723 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000724
Chris Lattner8213c8a2012-02-06 21:56:39 +0000725 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
726 if (C->getType()->getElementType()->isIntegerTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000727 return ConstantExpr::getNeg(C);
Nick Lewycky3bf55122008-05-23 04:54:45 +0000728
Craig Topperf40110f2014-04-25 05:29:35 +0000729 return nullptr;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000730}
731
Sanjay Patel84dca492015-09-21 15:33:26 +0000732/// Given a 'fsub' instruction, return the RHS of the instruction if the LHS is
733/// a constant negative zero (which is the 'negate' form).
Shuxin Yangf0537ab2013-01-09 00:13:41 +0000734Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
735 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
Dan Gohmana5b96452009-06-04 22:49:04 +0000736 return BinaryOperator::getFNegArgument(V);
737
738 // Constants can be considered to be negated values if they can be folded.
739 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson487375e2009-07-29 18:55:55 +0000740 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000741
Chris Lattner8213c8a2012-02-06 21:56:39 +0000742 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
743 if (C->getType()->getElementType()->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +0000744 return ConstantExpr::getFNeg(C);
Dan Gohmana5b96452009-06-04 22:49:04 +0000745
Craig Topperf40110f2014-04-25 05:29:35 +0000746 return nullptr;
Dan Gohmana5b96452009-06-04 22:49:04 +0000747}
748
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000749static Value *foldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000750 InstCombiner *IC) {
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000751 if (auto *Cast = dyn_cast<CastInst>(&I))
752 return IC->Builder->CreateCast(Cast->getOpcode(), SO, I.getType());
Chris Lattner86102b82005-01-01 16:22:27 +0000753
Sanjay Patel80baf692016-11-16 20:40:02 +0000754 assert(I.isBinaryOp() && "Unexpected opcode for select folding");
755
Chris Lattner183b3362004-04-09 19:05:30 +0000756 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000757 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
758 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000759
Sanjay Patel1b9560f2016-11-16 20:18:34 +0000760 if (auto *SOC = dyn_cast<Constant>(SO)) {
Chris Lattner183b3362004-04-09 19:05:30 +0000761 if (ConstIsRHS)
Owen Anderson487375e2009-07-29 18:55:55 +0000762 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
763 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000764 }
765
766 Value *Op0 = SO, *Op1 = ConstOperand;
767 if (!ConstIsRHS)
768 std::swap(Op0, Op1);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000769
Sanjay Patel80baf692016-11-16 20:40:02 +0000770 auto *BO = cast<BinaryOperator>(&I);
771 Value *RI = IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
772 SO->getName() + ".op");
773 auto *FPInst = dyn_cast<Instruction>(RI);
774 if (FPInst && isa<FPMathOperator>(FPInst))
775 FPInst->copyFastMathFlags(BO);
776 return RI;
Chris Lattner86102b82005-01-01 16:22:27 +0000777}
778
Chris Lattner2b295a02010-01-04 07:53:58 +0000779Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000780 // Don't modify shared select instructions.
781 if (!SI->hasOneUse())
782 return nullptr;
Chris Lattner86102b82005-01-01 16:22:27 +0000783
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000784 Value *TV = SI->getTrueValue();
785 Value *FV = SI->getFalseValue();
786 if (!(isa<Constant>(TV) || isa<Constant>(FV)))
787 return nullptr;
Chris Lattner374e6592005-04-21 05:43:13 +0000788
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000789 // Bool selects with constant operands can be folded to logical ops.
790 if (SI->getType()->getScalarType()->isIntegerTy(1))
791 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000792
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000793 // If it's a bitcast involving vectors, make sure it has the same number of
794 // elements on both sides.
795 if (auto *BC = dyn_cast<BitCastInst>(&Op)) {
796 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
797 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
798
799 // Verify that either both or neither are vectors.
800 if ((SrcTy == nullptr) != (DestTy == nullptr))
801 return nullptr;
802
803 // If vectors, verify that they have the same number of elements.
804 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
805 return nullptr;
806 }
807
808 // Test if a CmpInst instruction is used exclusively by a select as
809 // part of a minimum or maximum operation. If so, refrain from doing
810 // any other folding. This helps out other analyses which understand
811 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
812 // and CodeGen. And in this case, at least one of the comparison
813 // operands has at least one user besides the compare (the select),
814 // which would often largely negate the benefit of folding anyway.
815 if (auto *CI = dyn_cast<CmpInst>(SI->getCondition())) {
816 if (CI->hasOneUse()) {
817 Value *Op0 = CI->getOperand(0), *Op1 = CI->getOperand(1);
818 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
819 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
Craig Topperf40110f2014-04-25 05:29:35 +0000820 return nullptr;
Nick Lewycky6a083cf2011-01-21 02:30:43 +0000821 }
Chris Lattner86102b82005-01-01 16:22:27 +0000822 }
Sanjay Pateld1bf4342016-11-11 17:42:16 +0000823
Sanjay Patel8bd69b72016-11-26 15:23:20 +0000824 Value *NewTV = foldOperationIntoSelectOperand(Op, TV, this);
825 Value *NewFV = foldOperationIntoSelectOperand(Op, FV, this);
826 return SelectInst::Create(SI->getCondition(), NewTV, NewFV, "", nullptr, SI);
Chris Lattner183b3362004-04-09 19:05:30 +0000827}
828
Chris Lattnerea7131a2011-01-16 05:14:26 +0000829Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000830 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000831 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner25ce2802011-01-16 04:37:29 +0000832 if (NumPHIValues == 0)
Craig Topperf40110f2014-04-25 05:29:35 +0000833 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000834
Chris Lattnerf4ca47b2011-01-21 05:08:26 +0000835 // We normally only transform phis with a single use. However, if a PHI has
836 // multiple uses and they are all the same operation, we can fold *all* of the
837 // uses into the PHI.
Chris Lattnerd55581d2011-01-16 05:28:59 +0000838 if (!PN->hasOneUse()) {
839 // Walk the use list for the instruction, comparing them to I.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000840 for (User *U : PN->users()) {
841 Instruction *UI = cast<Instruction>(U);
842 if (UI != &I && !I.isIdenticalTo(UI))
Craig Topperf40110f2014-04-25 05:29:35 +0000843 return nullptr;
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000844 }
Chris Lattnerd55581d2011-01-16 05:28:59 +0000845 // Otherwise, we can replace *all* users with the new PHI we form.
846 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000847
Chris Lattnerfacb8672009-09-27 19:57:57 +0000848 // Check to see if all of the operands of the PHI are simple constants
849 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerae289632009-09-27 20:18:49 +0000850 // remember the BB it is in. If there is more than one or if *it* is a PHI,
851 // bail out. We don't do arbitrary constant expressions here because moving
852 // their computation can be expensive without a cost model.
Craig Topperf40110f2014-04-25 05:29:35 +0000853 BasicBlock *NonConstBB = nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000854 for (unsigned i = 0; i != NumPHIValues; ++i) {
855 Value *InVal = PN->getIncomingValue(i);
856 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
857 continue;
858
Craig Topperf40110f2014-04-25 05:29:35 +0000859 if (isa<PHINode>(InVal)) return nullptr; // Itself a phi.
860 if (NonConstBB) return nullptr; // More than one non-const value.
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000861
Chris Lattner25ce2802011-01-16 04:37:29 +0000862 NonConstBB = PN->getIncomingBlock(i);
Chris Lattnerff2e7372011-01-16 05:08:00 +0000863
864 // If the InVal is an invoke at the end of the pred block, then we can't
865 // insert a computation after it without breaking the edge.
866 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
867 if (II->getParent() == NonConstBB)
Craig Topperf40110f2014-04-25 05:29:35 +0000868 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000869
Chris Lattnerb5e15d12011-01-21 05:29:50 +0000870 // If the incoming non-constant value is in I's block, we will remove one
871 // instruction, but insert another equivalent one, leading to infinite
872 // instcombine.
Justin Bogner99798402016-08-05 01:06:44 +0000873 if (isPotentiallyReachable(I.getParent(), NonConstBB, &DT, LI))
Craig Topperf40110f2014-04-25 05:29:35 +0000874 return nullptr;
Chris Lattner25ce2802011-01-16 04:37:29 +0000875 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000876
Chris Lattner04689872006-09-09 22:02:56 +0000877 // If there is exactly one non-constant value, we can insert a copy of the
878 // operation in that block. However, if this is a critical edge, we would be
David Majnemer7e2b9882014-11-03 21:55:12 +0000879 // inserting the computation on some other paths (e.g. inside a loop). Only
Chris Lattner04689872006-09-09 22:02:56 +0000880 // do this if the pred block is unconditionally branching into the phi block.
Craig Topperf40110f2014-04-25 05:29:35 +0000881 if (NonConstBB != nullptr) {
Chris Lattner04689872006-09-09 22:02:56 +0000882 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000883 if (!BI || !BI->isUnconditional()) return nullptr;
Chris Lattner04689872006-09-09 22:02:56 +0000884 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000885
886 // Okay, we can do the transformation: create the new PHI node.
Eli Friedman41e509a2011-05-18 23:58:37 +0000887 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
Chris Lattner966526c2009-10-21 23:41:58 +0000888 InsertNewInstBefore(NewPN, *PN);
889 NewPN->takeName(PN);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000890
Chris Lattnerff2e7372011-01-16 05:08:00 +0000891 // If we are going to have to insert a new computation, do so right before the
Sanjay Patel41c739b2015-09-11 19:29:18 +0000892 // predecessor's terminator.
Chris Lattnerff2e7372011-01-16 05:08:00 +0000893 if (NonConstBB)
894 Builder->SetInsertPoint(NonConstBB->getTerminator());
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000895
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000896 // Next, add all of the operands to the PHI.
Chris Lattnerfacb8672009-09-27 19:57:57 +0000897 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
898 // We only currently try to fold the condition of a select when it is a phi,
899 // not the true/false values.
Chris Lattnerae289632009-09-27 20:18:49 +0000900 Value *TrueV = SI->getTrueValue();
901 Value *FalseV = SI->getFalseValue();
Chris Lattner0261b5d2009-09-28 06:49:44 +0000902 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattnerfacb8672009-09-27 19:57:57 +0000903 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerae289632009-09-27 20:18:49 +0000904 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner0261b5d2009-09-28 06:49:44 +0000905 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
906 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Craig Topperf40110f2014-04-25 05:29:35 +0000907 Value *InV = nullptr;
Duncan P. N. Exon Smithce5f93e2013-12-06 21:48:36 +0000908 // Beware of ConstantExpr: it may eventually evaluate to getNullValue,
909 // even if currently isNullValue gives false.
910 Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i));
Anna Thomasf57ae332017-03-27 13:52:51 +0000911 // For vector constants, we cannot use isNullValue to fold into
912 // FalseVInPred versus TrueVInPred. When we have individual nonzero
913 // elements in the vector, we will incorrectly fold InC to
914 // `TrueVInPred`.
Anna Thomas923e5742017-03-28 09:32:24 +0000915 if (InC && !isa<ConstantExpr>(InC) && isa<ConstantInt>(InC))
Chris Lattnerae289632009-09-27 20:18:49 +0000916 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000917 else
918 InV = Builder->CreateSelect(PN->getIncomingValue(i),
919 TrueVInPred, FalseVInPred, "phitmp");
Chris Lattnerae289632009-09-27 20:18:49 +0000920 NewPN->addIncoming(InV, ThisBB);
Chris Lattnerfacb8672009-09-27 19:57:57 +0000921 }
Chris Lattnerff2e7372011-01-16 05:08:00 +0000922 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
923 Constant *C = cast<Constant>(I.getOperand(1));
924 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000925 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000926 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
927 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
928 else if (isa<ICmpInst>(CI))
929 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
930 C, "phitmp");
931 else
932 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
933 C, "phitmp");
934 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
935 }
Chris Lattnerfacb8672009-09-27 19:57:57 +0000936 } else if (I.getNumOperands() == 2) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000937 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000938 for (unsigned i = 0; i != NumPHIValues; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +0000939 Value *InV = nullptr;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000940 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
941 InV = ConstantExpr::get(I.getOpcode(), InC, C);
942 else
943 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
944 PN->getIncomingValue(i), C, "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000945 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000946 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000947 } else {
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000948 CastInst *CI = cast<CastInst>(&I);
Chris Lattner229907c2011-07-18 04:54:35 +0000949 Type *RetTy = CI->getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000950 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner04689872006-09-09 22:02:56 +0000951 Value *InV;
Chris Lattnerff2e7372011-01-16 05:08:00 +0000952 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
Owen Anderson487375e2009-07-29 18:55:55 +0000953 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000954 else
Chris Lattnerff2e7372011-01-16 05:08:00 +0000955 InV = Builder->CreateCast(CI->getOpcode(),
956 PN->getIncomingValue(i), I.getType(), "phitmp");
Chris Lattner04689872006-09-09 22:02:56 +0000957 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000958 }
959 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000960
Chandler Carruthcdf47882014-03-09 03:16:01 +0000961 for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
Chris Lattnerd55581d2011-01-16 05:28:59 +0000962 Instruction *User = cast<Instruction>(*UI++);
963 if (User == &I) continue;
Sanjay Patel4b198802016-02-01 22:23:39 +0000964 replaceInstUsesWith(*User, NewPN);
965 eraseInstFromFunction(*User);
Chris Lattnerd55581d2011-01-16 05:28:59 +0000966 }
Sanjay Patel4b198802016-02-01 22:23:39 +0000967 return replaceInstUsesWith(I, NewPN);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000968}
969
Craig Topperd0b053d2017-04-03 07:08:08 +0000970Instruction *InstCombiner::foldOpWithConstantIntoOperand(BinaryOperator &I) {
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000971 assert(isa<Constant>(I.getOperand(1)) && "Unexpected operand type");
972
973 if (auto *Sel = dyn_cast<SelectInst>(I.getOperand(0))) {
974 if (Instruction *NewSel = FoldOpIntoSelect(I, Sel))
975 return NewSel;
976 } else if (isa<PHINode>(I.getOperand(0))) {
977 if (Instruction *NewPhi = FoldOpIntoPhi(I))
978 return NewPhi;
979 }
980 return nullptr;
981}
982
Sanjay Patel84dca492015-09-21 15:33:26 +0000983/// Given a pointer type and a constant offset, determine whether or not there
984/// is a sequence of GEP indices into the pointed type that will land us at the
985/// specified offset. If so, fill them into NewIndices and return the resultant
986/// element type, otherwise return null.
David Blaikie87ca1b62015-03-27 20:56:11 +0000987Type *InstCombiner::FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000988 SmallVectorImpl<Value *> &NewIndices) {
David Blaikie87ca1b62015-03-27 20:56:11 +0000989 Type *Ty = PtrTy->getElementType();
Matt Arsenaultd79f7d92013-08-19 22:17:40 +0000990 if (!Ty->isSized())
Craig Topperf40110f2014-04-25 05:29:35 +0000991 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +0000992
Chris Lattnerfef138b2009-01-09 05:44:56 +0000993 // Start with the index over the outer type. Note that the type size
994 // might be zero (even if the offset isn't zero) if the indexed type
995 // is something like [0 x {int, int}]
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Chris Lattnerfef138b2009-01-09 05:44:56 +0000997 int64_t FirstIdx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000998 if (int64_t TySize = DL.getTypeAllocSize(Ty)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +0000999 FirstIdx = Offset/TySize;
Chris Lattnerbd3c7c82009-01-11 20:41:36 +00001000 Offset -= FirstIdx*TySize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001001
Benjamin Kramere4c46fe2013-01-23 17:52:29 +00001002 // Handle hosts where % returns negative instead of values [0..TySize).
1003 if (Offset < 0) {
1004 --FirstIdx;
1005 Offset += TySize;
1006 assert(Offset >= 0);
1007 }
Chris Lattnerfef138b2009-01-09 05:44:56 +00001008 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
1009 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001010
Owen Andersonedb4a702009-07-24 23:12:02 +00001011 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001012
Chris Lattnerfef138b2009-01-09 05:44:56 +00001013 // Index into the types. If we fail, set OrigBase to null.
1014 while (Offset) {
Chris Lattner171d2d42009-01-11 20:15:20 +00001015 // Indexing into tail padding between struct/array elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 if (uint64_t(Offset * 8) >= DL.getTypeSizeInBits(Ty))
Craig Topperf40110f2014-04-25 05:29:35 +00001017 return nullptr;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001018
Chris Lattner229907c2011-07-18 04:54:35 +00001019 if (StructType *STy = dyn_cast<StructType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001020 const StructLayout *SL = DL.getStructLayout(STy);
Chris Lattner171d2d42009-01-11 20:15:20 +00001021 assert(Offset < (int64_t)SL->getSizeInBytes() &&
1022 "Offset must stay within the indexed type");
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001023
Chris Lattnerfef138b2009-01-09 05:44:56 +00001024 unsigned Elt = SL->getElementContainingOffset(Offset);
Chris Lattnerb8906bd2010-01-04 07:02:48 +00001025 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
1026 Elt));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001027
Chris Lattnerfef138b2009-01-09 05:44:56 +00001028 Offset -= SL->getElementOffset(Elt);
1029 Ty = STy->getElementType(Elt);
Chris Lattner229907c2011-07-18 04:54:35 +00001030 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001031 uint64_t EltSize = DL.getTypeAllocSize(AT->getElementType());
Chris Lattner171d2d42009-01-11 20:15:20 +00001032 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersonedb4a702009-07-24 23:12:02 +00001033 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattner171d2d42009-01-11 20:15:20 +00001034 Offset %= EltSize;
Chris Lattnerb1915162009-01-11 20:23:52 +00001035 Ty = AT->getElementType();
Chris Lattnerfef138b2009-01-09 05:44:56 +00001036 } else {
Chris Lattner171d2d42009-01-11 20:15:20 +00001037 // Otherwise, we can't index into the middle of this atomic type, bail.
Craig Topperf40110f2014-04-25 05:29:35 +00001038 return nullptr;
Chris Lattnerfef138b2009-01-09 05:44:56 +00001039 }
1040 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001041
Chris Lattner72cd68f2009-01-24 01:00:13 +00001042 return Ty;
Chris Lattnerfef138b2009-01-09 05:44:56 +00001043}
1044
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001045static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
1046 // If this GEP has only 0 indices, it is the same pointer as
1047 // Src. If Src is not a trivial GEP too, don't combine
1048 // the indices.
1049 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
1050 !Src.hasOneUse())
1051 return false;
1052 return true;
1053}
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001054
Sanjay Patel84dca492015-09-21 15:33:26 +00001055/// Return a value X such that Val = X * Scale, or null if none.
1056/// If the multiplication is known not to overflow, then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001057Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
1058 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
1059 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
1060 Scale.getBitWidth() && "Scale not compatible with value!");
1061
1062 // If Val is zero or Scale is one then Val = Val * Scale.
1063 if (match(Val, m_Zero()) || Scale == 1) {
1064 NoSignedWrap = true;
1065 return Val;
1066 }
1067
1068 // If Scale is zero then it does not divide Val.
1069 if (Scale.isMinValue())
Craig Topperf40110f2014-04-25 05:29:35 +00001070 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001071
1072 // Look through chains of multiplications, searching for a constant that is
1073 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
1074 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
1075 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
1076 // down from Val:
1077 //
1078 // Val = M1 * X || Analysis starts here and works down
1079 // M1 = M2 * Y || Doesn't descend into terms with more
1080 // M2 = Z * 4 \/ than one use
1081 //
1082 // Then to modify a term at the bottom:
1083 //
1084 // Val = M1 * X
1085 // M1 = Z * Y || Replaced M2 with Z
1086 //
1087 // Then to work back up correcting nsw flags.
1088
1089 // Op - the term we are currently analyzing. Starts at Val then drills down.
1090 // Replaced with its descaled value before exiting from the drill down loop.
1091 Value *Op = Val;
1092
1093 // Parent - initially null, but after drilling down notes where Op came from.
1094 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
1095 // 0'th operand of Val.
1096 std::pair<Instruction*, unsigned> Parent;
1097
Sanjay Patel84dca492015-09-21 15:33:26 +00001098 // Set if the transform requires a descaling at deeper levels that doesn't
1099 // overflow.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001100 bool RequireNoSignedWrap = false;
1101
Sanjay Patel84dca492015-09-21 15:33:26 +00001102 // Log base 2 of the scale. Negative if not a power of 2.
Duncan Sands533c8ae2012-10-23 08:28:26 +00001103 int32_t logScale = Scale.exactLogBase2();
1104
1105 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
1106
1107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1108 // If Op is a constant divisible by Scale then descale to the quotient.
1109 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
1110 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
1111 if (!Remainder.isMinValue())
1112 // Not divisible by Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001113 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001114 // Replace with the quotient in the parent.
1115 Op = ConstantInt::get(CI->getType(), Quotient);
1116 NoSignedWrap = true;
1117 break;
1118 }
1119
1120 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
1121
1122 if (BO->getOpcode() == Instruction::Mul) {
1123 // Multiplication.
1124 NoSignedWrap = BO->hasNoSignedWrap();
1125 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001126 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001127
1128 // There are three cases for multiplication: multiplication by exactly
1129 // the scale, multiplication by a constant different to the scale, and
1130 // multiplication by something else.
1131 Value *LHS = BO->getOperand(0);
1132 Value *RHS = BO->getOperand(1);
1133
1134 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1135 // Multiplication by a constant.
1136 if (CI->getValue() == Scale) {
1137 // Multiplication by exactly the scale, replace the multiplication
1138 // by its left-hand side in the parent.
1139 Op = LHS;
1140 break;
1141 }
1142
1143 // Otherwise drill down into the constant.
1144 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001145 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001146
1147 Parent = std::make_pair(BO, 1);
1148 continue;
1149 }
1150
1151 // Multiplication by something else. Drill down into the left-hand side
1152 // since that's where the reassociate pass puts the good stuff.
1153 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001154 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001155
1156 Parent = std::make_pair(BO, 0);
1157 continue;
1158 }
1159
1160 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
1161 isa<ConstantInt>(BO->getOperand(1))) {
1162 // Multiplication by a power of 2.
1163 NoSignedWrap = BO->hasNoSignedWrap();
1164 if (RequireNoSignedWrap && !NoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001165 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001166
1167 Value *LHS = BO->getOperand(0);
1168 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
1169 getLimitedValue(Scale.getBitWidth());
1170 // Op = LHS << Amt.
1171
1172 if (Amt == logScale) {
1173 // Multiplication by exactly the scale, replace the multiplication
1174 // by its left-hand side in the parent.
1175 Op = LHS;
1176 break;
1177 }
1178 if (Amt < logScale || !Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001179 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001180
1181 // Multiplication by more than the scale. Reduce the multiplying amount
1182 // by the scale in the parent.
1183 Parent = std::make_pair(BO, 1);
1184 Op = ConstantInt::get(BO->getType(), Amt - logScale);
1185 break;
1186 }
1187 }
1188
1189 if (!Op->hasOneUse())
Craig Topperf40110f2014-04-25 05:29:35 +00001190 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001191
1192 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
1193 if (Cast->getOpcode() == Instruction::SExt) {
1194 // Op is sign-extended from a smaller type, descale in the smaller type.
1195 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1196 APInt SmallScale = Scale.trunc(SmallSize);
1197 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
1198 // descale Op as (sext Y) * Scale. In order to have
1199 // sext (Y * SmallScale) = (sext Y) * Scale
1200 // some conditions need to hold however: SmallScale must sign-extend to
1201 // Scale and the multiplication Y * SmallScale should not overflow.
1202 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
1203 // SmallScale does not sign-extend to Scale.
Craig Topperf40110f2014-04-25 05:29:35 +00001204 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001205 assert(SmallScale.exactLogBase2() == logScale);
1206 // Require that Y * SmallScale must not overflow.
1207 RequireNoSignedWrap = true;
1208
1209 // Drill down through the cast.
1210 Parent = std::make_pair(Cast, 0);
1211 Scale = SmallScale;
1212 continue;
1213 }
1214
Duncan Sands5ed39002012-10-23 09:07:02 +00001215 if (Cast->getOpcode() == Instruction::Trunc) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001216 // Op is truncated from a larger type, descale in the larger type.
1217 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
1218 // trunc (Y * sext Scale) = (trunc Y) * Scale
1219 // always holds. However (trunc Y) * Scale may overflow even if
1220 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
1221 // from this point up in the expression (see later).
1222 if (RequireNoSignedWrap)
Craig Topperf40110f2014-04-25 05:29:35 +00001223 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001224
1225 // Drill down through the cast.
1226 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
1227 Parent = std::make_pair(Cast, 0);
1228 Scale = Scale.sext(LargeSize);
1229 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
1230 logScale = -1;
1231 assert(Scale.exactLogBase2() == logScale);
1232 continue;
1233 }
1234 }
1235
1236 // Unsupported expression, bail out.
Craig Topperf40110f2014-04-25 05:29:35 +00001237 return nullptr;
Duncan Sands533c8ae2012-10-23 08:28:26 +00001238 }
1239
Duncan P. N. Exon Smith04934b02014-07-10 17:13:27 +00001240 // If Op is zero then Val = Op * Scale.
1241 if (match(Op, m_Zero())) {
1242 NoSignedWrap = true;
1243 return Op;
1244 }
1245
Duncan Sands533c8ae2012-10-23 08:28:26 +00001246 // We know that we can successfully descale, so from here on we can safely
1247 // modify the IR. Op holds the descaled version of the deepest term in the
1248 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1249 // not to overflow.
1250
1251 if (!Parent.first)
1252 // The expression only had one term.
1253 return Op;
1254
1255 // Rewrite the parent using the descaled version of its operand.
1256 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1257 assert(Op != Parent.first->getOperand(Parent.second) &&
1258 "Descaling was a no-op?");
1259 Parent.first->setOperand(Parent.second, Op);
1260 Worklist.Add(Parent.first);
1261
1262 // Now work back up the expression correcting nsw flags. The logic is based
1263 // on the following observation: if X * Y is known not to overflow as a signed
1264 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1265 // then X * Z will not overflow as a signed multiplication either. As we work
1266 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1267 // current level has strictly smaller absolute value than the original.
1268 Instruction *Ancestor = Parent.first;
1269 do {
1270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1271 // If the multiplication wasn't nsw then we can't say anything about the
1272 // value of the descaled multiplication, and we have to clear nsw flags
1273 // from this point on up.
1274 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1275 NoSignedWrap &= OpNoSignedWrap;
1276 if (NoSignedWrap != OpNoSignedWrap) {
1277 BO->setHasNoSignedWrap(NoSignedWrap);
1278 Worklist.Add(Ancestor);
1279 }
1280 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1281 // The fact that the descaled input to the trunc has smaller absolute
1282 // value than the original input doesn't tell us anything useful about
1283 // the absolute values of the truncations.
1284 NoSignedWrap = false;
1285 }
1286 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1287 "Failed to keep proper track of nsw flags while drilling down?");
1288
1289 if (Ancestor == Val)
1290 // Got to the top, all done!
1291 return Val;
1292
1293 // Move up one level in the expression.
1294 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
Chandler Carruthcdf47882014-03-09 03:16:01 +00001295 Ancestor = Ancestor->user_back();
Duncan Sands533c8ae2012-10-23 08:28:26 +00001296 } while (1);
1297}
1298
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001299/// \brief Creates node of binary operation with the same attributes as the
1300/// specified one but with other operands.
Serge Pavlove6de9e32014-05-14 09:05:09 +00001301static Value *CreateBinOpAsGiven(BinaryOperator &Inst, Value *LHS, Value *RHS,
1302 InstCombiner::BuilderTy *B) {
Sanjay Patel968e91a2015-11-24 17:51:20 +00001303 Value *BO = B->CreateBinOp(Inst.getOpcode(), LHS, RHS);
1304 // If LHS and RHS are constant, BO won't be a binary operator.
1305 if (BinaryOperator *NewBO = dyn_cast<BinaryOperator>(BO))
1306 NewBO->copyIRFlags(&Inst);
1307 return BO;
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001308}
1309
1310/// \brief Makes transformation of binary operation specific for vector types.
1311/// \param Inst Binary operator to transform.
1312/// \return Pointer to node that must replace the original binary operator, or
1313/// null pointer if no transformation was made.
1314Value *InstCombiner::SimplifyVectorOp(BinaryOperator &Inst) {
1315 if (!Inst.getType()->isVectorTy()) return nullptr;
1316
Sanjay Patel58814442014-07-09 16:34:54 +00001317 // It may not be safe to reorder shuffles and things like div, urem, etc.
1318 // because we may trap when executing those ops on unknown vector elements.
1319 // See PR20059.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001320 if (!isSafeToSpeculativelyExecute(&Inst))
1321 return nullptr;
Sanjay Patel58814442014-07-09 16:34:54 +00001322
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001323 unsigned VWidth = cast<VectorType>(Inst.getType())->getNumElements();
1324 Value *LHS = Inst.getOperand(0), *RHS = Inst.getOperand(1);
1325 assert(cast<VectorType>(LHS->getType())->getNumElements() == VWidth);
1326 assert(cast<VectorType>(RHS->getType())->getNumElements() == VWidth);
1327
Sanjay Patelc3b4735b2017-03-06 23:25:28 +00001328 // If both arguments of the binary operation are shuffles that use the same
1329 // mask and shuffle within a single vector, move the shuffle after the binop:
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001330 // Op(shuffle(v1, m), shuffle(v2, m)) -> shuffle(Op(v1, v2), m)
Sanjay Patelc3b4735b2017-03-06 23:25:28 +00001331 auto *LShuf = dyn_cast<ShuffleVectorInst>(LHS);
1332 auto *RShuf = dyn_cast<ShuffleVectorInst>(RHS);
1333 if (LShuf && RShuf && LShuf->getMask() == RShuf->getMask() &&
1334 isa<UndefValue>(LShuf->getOperand(1)) &&
1335 isa<UndefValue>(RShuf->getOperand(1)) &&
1336 LShuf->getOperand(0)->getType() == RShuf->getOperand(0)->getType()) {
1337 Value *NewBO = CreateBinOpAsGiven(Inst, LShuf->getOperand(0),
1338 RShuf->getOperand(0), Builder);
1339 return Builder->CreateShuffleVector(
1340 NewBO, UndefValue::get(NewBO->getType()), LShuf->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001341 }
1342
1343 // If one argument is a shuffle within one vector, the other is a constant,
1344 // try moving the shuffle after the binary operation.
1345 ShuffleVectorInst *Shuffle = nullptr;
1346 Constant *C1 = nullptr;
1347 if (isa<ShuffleVectorInst>(LHS)) Shuffle = cast<ShuffleVectorInst>(LHS);
1348 if (isa<ShuffleVectorInst>(RHS)) Shuffle = cast<ShuffleVectorInst>(RHS);
1349 if (isa<Constant>(LHS)) C1 = cast<Constant>(LHS);
1350 if (isa<Constant>(RHS)) C1 = cast<Constant>(RHS);
Benjamin Kramer6de78662014-06-24 10:38:10 +00001351 if (Shuffle && C1 &&
1352 (isa<ConstantVector>(C1) || isa<ConstantDataVector>(C1)) &&
1353 isa<UndefValue>(Shuffle->getOperand(1)) &&
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001354 Shuffle->getType() == Shuffle->getOperand(0)->getType()) {
1355 SmallVector<int, 16> ShMask = Shuffle->getShuffleMask();
1356 // Find constant C2 that has property:
1357 // shuffle(C2, ShMask) = C1
1358 // If such constant does not exist (example: ShMask=<0,0> and C1=<1,2>)
1359 // reorder is not possible.
1360 SmallVector<Constant*, 16> C2M(VWidth,
1361 UndefValue::get(C1->getType()->getScalarType()));
1362 bool MayChange = true;
1363 for (unsigned I = 0; I < VWidth; ++I) {
1364 if (ShMask[I] >= 0) {
1365 assert(ShMask[I] < (int)VWidth);
1366 if (!isa<UndefValue>(C2M[ShMask[I]])) {
1367 MayChange = false;
1368 break;
1369 }
1370 C2M[ShMask[I]] = C1->getAggregateElement(I);
1371 }
1372 }
1373 if (MayChange) {
1374 Constant *C2 = ConstantVector::get(C2M);
Sanjay Patel04df5832015-11-21 16:51:19 +00001375 Value *NewLHS = isa<Constant>(LHS) ? C2 : Shuffle->getOperand(0);
1376 Value *NewRHS = isa<Constant>(LHS) ? Shuffle->getOperand(0) : C2;
Serge Pavlove6de9e32014-05-14 09:05:09 +00001377 Value *NewBO = CreateBinOpAsGiven(Inst, NewLHS, NewRHS, Builder);
Sanjay Patel1f3fa212015-11-21 16:37:09 +00001378 return Builder->CreateShuffleVector(NewBO,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001379 UndefValue::get(Inst.getType()), Shuffle->getMask());
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001380 }
1381 }
1382
1383 return nullptr;
1384}
1385
Chris Lattner113f4f42002-06-25 16:13:24 +00001386Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001387 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1388
Justin Bogner99798402016-08-05 01:06:44 +00001389 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001390 SimplifyGEPInst(GEP.getSourceElementType(), Ops, DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001391 return replaceInstUsesWith(GEP, V);
Chris Lattner8574aba2009-11-27 00:29:05 +00001392
Chris Lattner5f667a62004-05-07 22:09:22 +00001393 Value *PtrOp = GEP.getOperand(0);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001394
Duncan Sandsc133c542010-11-22 16:32:50 +00001395 // Eliminate unneeded casts for indices, and replace indices which displace
1396 // by multiples of a zero size type with zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001397 bool MadeChange = false;
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001398 Type *IntPtrTy =
1399 DL.getIntPtrType(GEP.getPointerOperandType()->getScalarType());
Duncan Sandsc133c542010-11-22 16:32:50 +00001400
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001401 gep_type_iterator GTI = gep_type_begin(GEP);
1402 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end(); I != E;
1403 ++I, ++GTI) {
1404 // Skip indices into struct types.
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001405 if (GTI.isStruct())
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001406 continue;
Duncan Sandsc133c542010-11-22 16:32:50 +00001407
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001408 // Index type should have the same width as IntPtr
1409 Type *IndexTy = (*I)->getType();
1410 Type *NewIndexType = IndexTy->isVectorTy() ?
1411 VectorType::get(IntPtrTy, IndexTy->getVectorNumElements()) : IntPtrTy;
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001412
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001413 // If the element type has zero size then any index over it is equivalent
1414 // to an index of zero, so replace it with zero if it is not zero already.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001415 Type *EltTy = GTI.getIndexedType();
1416 if (EltTy->isSized() && DL.getTypeAllocSize(EltTy) == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001417 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001418 *I = Constant::getNullValue(NewIndexType);
Duncan Sandsc133c542010-11-22 16:32:50 +00001419 MadeChange = true;
1420 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001421
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001422 if (IndexTy != NewIndexType) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001423 // If we are using a wider index than needed for this platform, shrink
1424 // it to what we need. If narrower, sign-extend it to what we need.
1425 // This explicit cast can make subsequent optimizations more obvious.
Elena Demikhovsky121d49b2015-11-15 08:19:35 +00001426 *I = Builder->CreateIntCast(*I, NewIndexType, true);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001427 MadeChange = true;
Chris Lattner69193f92004-04-05 01:30:19 +00001428 }
Chris Lattner9bf53ff2007-03-25 20:43:09 +00001429 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001430 if (MadeChange)
1431 return &GEP;
Chris Lattner69193f92004-04-05 01:30:19 +00001432
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001433 // Check to see if the inputs to the PHI node are getelementptr instructions.
1434 if (PHINode *PN = dyn_cast<PHINode>(PtrOp)) {
1435 GetElementPtrInst *Op1 = dyn_cast<GetElementPtrInst>(PN->getOperand(0));
1436 if (!Op1)
1437 return nullptr;
1438
Daniel Jasper5add63f2015-03-19 11:05:08 +00001439 // Don't fold a GEP into itself through a PHI node. This can only happen
1440 // through the back-edge of a loop. Folding a GEP into itself means that
1441 // the value of the previous iteration needs to be stored in the meantime,
1442 // thus requiring an additional register variable to be live, but not
1443 // actually achieving anything (the GEP still needs to be executed once per
1444 // loop iteration).
1445 if (Op1 == &GEP)
1446 return nullptr;
1447
David Majnemere61e4bf2016-06-21 05:10:24 +00001448 int DI = -1;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001449
1450 for (auto I = PN->op_begin()+1, E = PN->op_end(); I !=E; ++I) {
1451 GetElementPtrInst *Op2 = dyn_cast<GetElementPtrInst>(*I);
1452 if (!Op2 || Op1->getNumOperands() != Op2->getNumOperands())
1453 return nullptr;
1454
Daniel Jasper5add63f2015-03-19 11:05:08 +00001455 // As for Op1 above, don't try to fold a GEP into itself.
1456 if (Op2 == &GEP)
1457 return nullptr;
1458
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001459 // Keep track of the type as we walk the GEP.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001460 Type *CurTy = nullptr;
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001461
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001462 for (unsigned J = 0, F = Op1->getNumOperands(); J != F; ++J) {
1463 if (Op1->getOperand(J)->getType() != Op2->getOperand(J)->getType())
1464 return nullptr;
1465
1466 if (Op1->getOperand(J) != Op2->getOperand(J)) {
1467 if (DI == -1) {
1468 // We have not seen any differences yet in the GEPs feeding the
1469 // PHI yet, so we record this one if it is allowed to be a
1470 // variable.
1471
1472 // The first two arguments can vary for any GEP, the rest have to be
1473 // static for struct slots
Chandler Carruth3012a1b2014-05-29 23:05:52 +00001474 if (J > 1 && CurTy->isStructTy())
1475 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001476
1477 DI = J;
1478 } else {
1479 // The GEP is different by more than one input. While this could be
1480 // extended to support GEPs that vary by more than one variable it
1481 // doesn't make sense since it greatly increases the complexity and
1482 // would result in an R+R+R addressing mode which no backend
1483 // directly supports and would need to be broken into several
1484 // simpler instructions anyway.
1485 return nullptr;
1486 }
1487 }
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001488
1489 // Sink down a layer of the type for the next iteration.
1490 if (J > 0) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001491 if (J == 1) {
1492 CurTy = Op1->getSourceElementType();
1493 } else if (CompositeType *CT = dyn_cast<CompositeType>(CurTy)) {
Chandler Carruthfdc0e0b2014-05-29 23:21:12 +00001494 CurTy = CT->getTypeAtIndex(Op1->getOperand(J));
1495 } else {
1496 CurTy = nullptr;
1497 }
1498 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001499 }
1500 }
1501
Silviu Barangab892e352015-10-26 10:25:05 +00001502 // If not all GEPs are identical we'll have to create a new PHI node.
1503 // Check that the old PHI node has only one use so that it will get
1504 // removed.
1505 if (DI != -1 && !PN->hasOneUse())
1506 return nullptr;
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001507
Silviu Barangab892e352015-10-26 10:25:05 +00001508 GetElementPtrInst *NewGEP = cast<GetElementPtrInst>(Op1->clone());
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001509 if (DI == -1) {
1510 // All the GEPs feeding the PHI are identical. Clone one down into our
1511 // BB so that it can be merged with the current GEP.
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001512 GEP.getParent()->getInstList().insert(
1513 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001514 } else {
1515 // All the GEPs feeding the PHI differ at a single offset. Clone a GEP
1516 // into the current block so it can be merged, and create a new PHI to
1517 // set that index.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001518 PHINode *NewPN;
1519 {
1520 IRBuilderBase::InsertPointGuard Guard(*Builder);
1521 Builder->SetInsertPoint(PN);
1522 NewPN = Builder->CreatePHI(Op1->getOperand(DI)->getType(),
1523 PN->getNumOperands());
1524 }
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001525
1526 for (auto &I : PN->operands())
1527 NewPN->addIncoming(cast<GEPOperator>(I)->getOperand(DI),
1528 PN->getIncomingBlock(I));
1529
1530 NewGEP->setOperand(DI, NewPN);
Akira Hatanaka1defd5a2015-02-18 03:30:11 +00001531 GEP.getParent()->getInstList().insert(
1532 GEP.getParent()->getFirstInsertionPt(), NewGEP);
Louis Gerbargc6b506a2014-05-29 20:29:47 +00001533 NewGEP->setOperand(DI, NewPN);
1534 }
1535
1536 GEP.setOperand(0, NewGEP);
1537 PtrOp = NewGEP;
1538 }
1539
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001540 // Combine Indices - If the source pointer to this getelementptr instruction
1541 // is a getelementptr instruction, combine the indices of the two
1542 // getelementptr instructions into a single instruction.
1543 //
Dan Gohman31a9b982009-07-28 01:40:03 +00001544 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001545 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
Craig Topperf40110f2014-04-25 05:29:35 +00001546 return nullptr;
Rafael Espindola40325672011-07-11 03:43:47 +00001547
Duncan Sands533c8ae2012-10-23 08:28:26 +00001548 // Note that if our source is a gep chain itself then we wait for that
Chris Lattner5f667a62004-05-07 22:09:22 +00001549 // chain to be resolved before we perform this transformation. This
1550 // avoids us creating a TON of code in some cases.
Rafael Espindolaa3a44f3f2011-07-31 04:43:41 +00001551 if (GEPOperator *SrcGEP =
1552 dyn_cast<GEPOperator>(Src->getOperand(0)))
1553 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
Craig Topperf40110f2014-04-25 05:29:35 +00001554 return nullptr; // Wait until our source is folded to completion.
Chris Lattner5f667a62004-05-07 22:09:22 +00001555
Chris Lattneraf6094f2007-02-15 22:48:32 +00001556 SmallVector<Value*, 8> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00001557
1558 // Find out whether the last index in the source GEP is a sequential idx.
1559 bool EndsWithSequential = false;
Chris Lattnerb2995e12009-08-30 05:30:55 +00001560 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1561 I != E; ++I)
Peter Collingbourneab85225b2016-12-02 02:24:42 +00001562 EndsWithSequential = I.isSequential();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001563
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001564 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00001565 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00001566 // Replace: gep (gep %P, long B), long A, ...
1567 // With: T = long A+B; gep %P, T, ...
1568 //
Chris Lattner06c687b2009-08-30 05:08:50 +00001569 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1570 Value *GO1 = GEP.getOperand(1);
Davide Italiano2ef8c4e2017-01-19 18:51:56 +00001571
1572 // If they aren't the same type, then the input hasn't been processed
1573 // by the loop above yet (which canonicalizes sequential index types to
1574 // intptr_t). Just avoid transforming this until the input has been
1575 // normalized.
1576 if (SO1->getType() != GO1->getType())
1577 return nullptr;
1578
1579 Value* Sum = SimplifyAddInst(GO1, SO1, false, false, DL, &TLI, &DT, &AC);
1580 // Only do the combine when we are sure the cost after the
1581 // merge is never more than that before the merge.
1582 if (Sum == nullptr)
1583 return nullptr;
Chris Lattner5f667a62004-05-07 22:09:22 +00001584
Chris Lattnerb2995e12009-08-30 05:30:55 +00001585 // Update the GEP in place if possible.
Chris Lattner06c687b2009-08-30 05:08:50 +00001586 if (Src->getNumOperands() == 2) {
1587 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner5f667a62004-05-07 22:09:22 +00001588 GEP.setOperand(1, Sum);
1589 return &GEP;
Chris Lattner5f667a62004-05-07 22:09:22 +00001590 }
Chris Lattnerb2995e12009-08-30 05:30:55 +00001591 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerd7b6e912009-08-30 04:49:01 +00001592 Indices.push_back(Sum);
Chris Lattnerb2995e12009-08-30 05:30:55 +00001593 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00001595 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner06c687b2009-08-30 05:08:50 +00001596 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001597 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerb2995e12009-08-30 05:30:55 +00001598 Indices.append(Src->op_begin()+1, Src->op_end());
1599 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001600 }
1601
Dan Gohman1b849082009-09-07 23:54:19 +00001602 if (!Indices.empty())
David Blaikie096b1da2015-03-14 19:53:33 +00001603 return GEP.isInBounds() && Src->isInBounds()
1604 ? GetElementPtrInst::CreateInBounds(
1605 Src->getSourceElementType(), Src->getOperand(0), Indices,
1606 GEP.getName())
1607 : GetElementPtrInst::Create(Src->getSourceElementType(),
1608 Src->getOperand(0), Indices,
1609 GEP.getName());
Chris Lattnere26bf172009-08-30 05:00:50 +00001610 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001611
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001612 if (GEP.getNumIndices() == 1) {
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001613 unsigned AS = GEP.getPointerAddressSpace();
David Majnemerd2df5012014-09-01 21:10:02 +00001614 if (GEP.getOperand(1)->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001615 DL.getPointerSizeInBits(AS)) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001616 Type *Ty = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001617 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty);
David Majnemerd2df5012014-09-01 21:10:02 +00001618
1619 bool Matched = false;
1620 uint64_t C;
1621 Value *V = nullptr;
1622 if (TyAllocSize == 1) {
1623 V = GEP.getOperand(1);
1624 Matched = true;
1625 } else if (match(GEP.getOperand(1),
1626 m_AShr(m_Value(V), m_ConstantInt(C)))) {
1627 if (TyAllocSize == 1ULL << C)
1628 Matched = true;
1629 } else if (match(GEP.getOperand(1),
1630 m_SDiv(m_Value(V), m_ConstantInt(C)))) {
1631 if (TyAllocSize == C)
1632 Matched = true;
1633 }
1634
1635 if (Matched) {
1636 // Canonicalize (gep i8* X, -(ptrtoint Y))
1637 // to (inttoptr (sub (ptrtoint X), (ptrtoint Y)))
1638 // The GEP pattern is emitted by the SCEV expander for certain kinds of
1639 // pointer arithmetic.
1640 if (match(V, m_Neg(m_PtrToInt(m_Value())))) {
1641 Operator *Index = cast<Operator>(V);
1642 Value *PtrToInt = Builder->CreatePtrToInt(PtrOp, Index->getType());
1643 Value *NewSub = Builder->CreateSub(PtrToInt, Index->getOperand(1));
1644 return CastInst::Create(Instruction::IntToPtr, NewSub, GEP.getType());
1645 }
1646 // Canonicalize (gep i8* X, (ptrtoint Y)-(ptrtoint X))
1647 // to (bitcast Y)
1648 Value *Y;
1649 if (match(V, m_Sub(m_PtrToInt(m_Value(Y)),
1650 m_PtrToInt(m_Specific(GEP.getOperand(0)))))) {
1651 return CastInst::CreatePointerBitCastOrAddrSpaceCast(Y,
1652 GEP.getType());
1653 }
1654 }
Matt Arsenaultbfa37e52013-10-03 18:15:57 +00001655 }
Benjamin Kramere6461e32013-09-20 14:38:44 +00001656 }
1657
Matthew Simpsonc8f0aec2017-03-29 18:23:08 +00001658 // We do not handle pointer-vector geps here.
1659 if (GEP.getType()->isVectorTy())
1660 return nullptr;
1661
Chris Lattner06c687b2009-08-30 05:08:50 +00001662 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
Chris Lattnere903f382010-01-05 07:42:10 +00001663 Value *StrippedPtr = PtrOp->stripPointerCasts();
Matthew Simpsonc8f0aec2017-03-29 18:23:08 +00001664 PointerType *StrippedPtrTy = cast<PointerType>(StrippedPtr->getType());
Nadav Rotema8f35622012-03-26 21:00:53 +00001665
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001666 if (StrippedPtr != PtrOp) {
Chris Lattner8574aba2009-11-27 00:29:05 +00001667 bool HasZeroPointerIndex = false;
1668 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1669 HasZeroPointerIndex = C->isZero();
Nadav Rotema069c6c2011-04-05 14:29:52 +00001670
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001671 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1672 // into : GEP [10 x i8]* X, i32 0, ...
1673 //
1674 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1675 // into : GEP i8* X, ...
Nadav Rotema069c6c2011-04-05 14:29:52 +00001676 //
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001677 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnere26bf172009-08-30 05:00:50 +00001678 if (HasZeroPointerIndex) {
Chris Lattner229907c2011-07-18 04:54:35 +00001679 if (ArrayType *CATy =
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001680 dyn_cast<ArrayType>(GEP.getSourceElementType())) {
Duncan Sands5795a602009-03-02 09:18:21 +00001681 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
Chris Lattnere903f382010-01-05 07:42:10 +00001682 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001683 // -> GEP i8* X, ...
Chris Lattnere903f382010-01-05 07:42:10 +00001684 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
David Blaikie096b1da2015-03-14 19:53:33 +00001685 GetElementPtrInst *Res = GetElementPtrInst::Create(
1686 StrippedPtrTy->getElementType(), StrippedPtr, Idx, GEP.getName());
Chris Lattnere903f382010-01-05 07:42:10 +00001687 Res->setIsInBounds(GEP.isInBounds());
Eli Bendersky9966b262014-04-03 17:51:58 +00001688 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace())
1689 return Res;
1690 // Insert Res, and create an addrspacecast.
1691 // e.g.,
1692 // GEP (addrspacecast i8 addrspace(1)* X to [0 x i8]*), i32 0, ...
1693 // ->
1694 // %0 = GEP i8 addrspace(1)* X, ...
1695 // addrspacecast i8 addrspace(1)* %0 to i8*
1696 return new AddrSpaceCastInst(Builder->Insert(Res), GEP.getType());
Chris Lattnerc2f2cf82009-08-30 20:36:46 +00001697 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001698
Chris Lattner229907c2011-07-18 04:54:35 +00001699 if (ArrayType *XATy =
Chris Lattnere903f382010-01-05 07:42:10 +00001700 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
Duncan Sands5795a602009-03-02 09:18:21 +00001701 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattner567b81f2005-09-13 00:40:14 +00001702 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5795a602009-03-02 09:18:21 +00001703 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattner567b81f2005-09-13 00:40:14 +00001704 // At this point, we know that the cast source type is a pointer
1705 // to an array of the same type as the destination pointer
1706 // array. Because the array type is never stepped over (there
1707 // is a leading zero) we can fold the cast into this GEP.
Eli Bendersky9966b262014-04-03 17:51:58 +00001708 if (StrippedPtrTy->getAddressSpace() == GEP.getAddressSpace()) {
1709 GEP.setOperand(0, StrippedPtr);
David Blaikie73cf8722015-05-05 18:03:48 +00001710 GEP.setSourceElementType(XATy);
Eli Bendersky9966b262014-04-03 17:51:58 +00001711 return &GEP;
1712 }
1713 // Cannot replace the base pointer directly because StrippedPtr's
1714 // address space is different. Instead, create a new GEP followed by
1715 // an addrspacecast.
1716 // e.g.,
1717 // GEP (addrspacecast [10 x i8] addrspace(1)* X to [0 x i8]*),
1718 // i32 0, ...
1719 // ->
1720 // %0 = GEP [10 x i8] addrspace(1)* X, ...
1721 // addrspacecast i8 addrspace(1)* %0 to i8*
1722 SmallVector<Value*, 8> Idx(GEP.idx_begin(), GEP.idx_end());
David Blaikieaa41cd52015-04-03 21:33:42 +00001723 Value *NewGEP = GEP.isInBounds()
1724 ? Builder->CreateInBoundsGEP(
1725 nullptr, StrippedPtr, Idx, GEP.getName())
1726 : Builder->CreateGEP(nullptr, StrippedPtr, Idx,
1727 GEP.getName());
Eli Bendersky9966b262014-04-03 17:51:58 +00001728 return new AddrSpaceCastInst(NewGEP, GEP.getType());
Chris Lattner567b81f2005-09-13 00:40:14 +00001729 }
Duncan Sands5795a602009-03-02 09:18:21 +00001730 }
1731 }
Chris Lattner567b81f2005-09-13 00:40:14 +00001732 } else if (GEP.getNumOperands() == 2) {
1733 // Transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001734 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1735 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattner229907c2011-07-18 04:54:35 +00001736 Type *SrcElTy = StrippedPtrTy->getElementType();
Eduard Burtescu19eb0312016-01-19 17:28:00 +00001737 Type *ResElTy = GEP.getSourceElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001738 if (SrcElTy->isArrayTy() &&
1739 DL.getTypeAllocSize(SrcElTy->getArrayElementType()) ==
1740 DL.getTypeAllocSize(ResElTy)) {
1741 Type *IdxType = DL.getIntPtrType(GEP.getType());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001742 Value *Idx[2] = { Constant::getNullValue(IdxType), GEP.getOperand(1) };
David Blaikie68d535c2015-03-24 22:38:16 +00001743 Value *NewGEP =
1744 GEP.isInBounds()
David Blaikieaa41cd52015-04-03 21:33:42 +00001745 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, Idx,
1746 GEP.getName())
1747 : Builder->CreateGEP(nullptr, StrippedPtr, Idx, GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001748
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001749 // V and GEP are both pointer types --> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001750 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1751 GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001752 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001753
Chris Lattner2a893292005-09-13 18:36:04 +00001754 // Transform things like:
Duncan Sands533c8ae2012-10-23 08:28:26 +00001755 // %V = mul i64 %N, 4
1756 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1757 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001758 if (ResElTy->isSized() && SrcElTy->isSized()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001759 // Check that changing the type amounts to dividing the index by a scale
1760 // factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001761 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1762 uint64_t SrcSize = DL.getTypeAllocSize(SrcElTy);
Duncan Sands533c8ae2012-10-23 08:28:26 +00001763 if (ResSize && SrcSize % ResSize == 0) {
1764 Value *Idx = GEP.getOperand(1);
1765 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1766 uint64_t Scale = SrcSize / ResSize;
1767
1768 // Earlier transforms ensure that the index has type IntPtrType, which
1769 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001770 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001771 "Index not cast to pointer width?");
1772
1773 bool NSW;
1774 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1775 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1776 // If the multiplication NewIdx * Scale may overflow then the new
1777 // GEP may not be "inbounds".
David Blaikie68d535c2015-03-24 22:38:16 +00001778 Value *NewGEP =
1779 GEP.isInBounds() && NSW
David Blaikieaa41cd52015-04-03 21:33:42 +00001780 ? Builder->CreateInBoundsGEP(nullptr, StrippedPtr, NewIdx,
David Blaikie68d535c2015-03-24 22:38:16 +00001781 GEP.getName())
David Blaikieaa41cd52015-04-03 21:33:42 +00001782 : Builder->CreateGEP(nullptr, StrippedPtr, NewIdx,
1783 GEP.getName());
Matt Arsenaultaa689f52014-02-14 00:49:12 +00001784
Duncan Sands533c8ae2012-10-23 08:28:26 +00001785 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001786 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1787 GEP.getType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001788 }
1789 }
1790 }
1791
1792 // Similarly, transform things like:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001793 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner2a893292005-09-13 18:36:04 +00001794 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz309e5a72007-12-12 15:21:32 +00001795 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001796 if (ResElTy->isSized() && SrcElTy->isSized() && SrcElTy->isArrayTy()) {
Duncan Sands533c8ae2012-10-23 08:28:26 +00001797 // Check that changing to the array element type amounts to dividing the
1798 // index by a scale factor.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001799 uint64_t ResSize = DL.getTypeAllocSize(ResElTy);
1800 uint64_t ArrayEltSize =
1801 DL.getTypeAllocSize(SrcElTy->getArrayElementType());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001802 if (ResSize && ArrayEltSize % ResSize == 0) {
1803 Value *Idx = GEP.getOperand(1);
1804 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1805 uint64_t Scale = ArrayEltSize / ResSize;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001806
Duncan Sands533c8ae2012-10-23 08:28:26 +00001807 // Earlier transforms ensure that the index has type IntPtrType, which
1808 // considerably simplifies the logic by eliminating implicit casts.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001809 assert(Idx->getType() == DL.getIntPtrType(GEP.getType()) &&
Duncan Sands533c8ae2012-10-23 08:28:26 +00001810 "Index not cast to pointer width?");
1811
1812 bool NSW;
1813 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1814 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1815 // If the multiplication NewIdx * Scale may overflow then the new
1816 // GEP may not be "inbounds".
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001817 Value *Off[2] = {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001818 Constant::getNullValue(DL.getIntPtrType(GEP.getType())),
1819 NewIdx};
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +00001820
David Blaikieaa41cd52015-04-03 21:33:42 +00001821 Value *NewGEP = GEP.isInBounds() && NSW
1822 ? Builder->CreateInBoundsGEP(
1823 SrcElTy, StrippedPtr, Off, GEP.getName())
1824 : Builder->CreateGEP(SrcElTy, StrippedPtr, Off,
1825 GEP.getName());
Duncan Sands533c8ae2012-10-23 08:28:26 +00001826 // The NewGEP must be pointer typed, so must the old one -> BitCast
Manuel Jacob405fb182014-07-16 20:13:45 +00001827 return CastInst::CreatePointerBitCastOrAddrSpaceCast(NewGEP,
1828 GEP.getType());
Chris Lattner2a893292005-09-13 18:36:04 +00001829 }
1830 }
Chris Lattner2a893292005-09-13 18:36:04 +00001831 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00001832 }
Chris Lattnerca081252001-12-14 16:52:21 +00001833 }
Nadav Rotema069c6c2011-04-05 14:29:52 +00001834
Matt Arsenault4815f092014-08-12 19:46:13 +00001835 // addrspacecast between types is canonicalized as a bitcast, then an
1836 // addrspacecast. To take advantage of the below bitcast + struct GEP, look
1837 // through the addrspacecast.
1838 if (AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(PtrOp)) {
1839 // X = bitcast A addrspace(1)* to B addrspace(1)*
1840 // Y = addrspacecast A addrspace(1)* to B addrspace(2)*
1841 // Z = gep Y, <...constant indices...>
1842 // Into an addrspacecasted GEP of the struct.
1843 if (BitCastInst *BC = dyn_cast<BitCastInst>(ASC->getOperand(0)))
1844 PtrOp = BC;
1845 }
1846
Chris Lattnerfef138b2009-01-09 05:44:56 +00001847 /// See if we can simplify:
Chris Lattner97fd3592009-08-30 05:55:36 +00001848 /// X = bitcast A* to B*
Chris Lattnerfef138b2009-01-09 05:44:56 +00001849 /// Y = gep X, <...constant indices...>
1850 /// into a gep of the original struct. This is important for SROA and alias
1851 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattnera784a2c2009-01-09 04:53:57 +00001852 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Matt Arsenault98f34e32013-08-19 22:17:34 +00001853 Value *Operand = BCI->getOperand(0);
1854 PointerType *OpType = cast<PointerType>(Operand->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001855 unsigned OffsetBits = DL.getPointerTypeSizeInBits(GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001856 APInt Offset(OffsetBits, 0);
1857 if (!isa<BitCastInst>(Operand) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001858 GEP.accumulateConstantOffset(DL, Offset)) {
Nadav Rotema069c6c2011-04-05 14:29:52 +00001859
Chris Lattnerfef138b2009-01-09 05:44:56 +00001860 // If this GEP instruction doesn't move the pointer, just replace the GEP
1861 // with a bitcast of the real input to the dest type.
Nuno Lopesb6ad9822012-12-30 16:25:48 +00001862 if (!Offset) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001863 // If the bitcast is of an allocation, and the allocation will be
1864 // converted to match the type of the cast, don't touch this.
Justin Bogner99798402016-08-05 01:06:44 +00001865 if (isa<AllocaInst>(Operand) || isAllocationFn(Operand, &TLI)) {
Chris Lattnerfef138b2009-01-09 05:44:56 +00001866 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1867 if (Instruction *I = visitBitCast(*BCI)) {
1868 if (I != BCI) {
1869 I->takeName(BCI);
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001870 BCI->getParent()->getInstList().insert(BCI->getIterator(), I);
Sanjay Patel4b198802016-02-01 22:23:39 +00001871 replaceInstUsesWith(*BCI, I);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001872 }
1873 return &GEP;
Chris Lattnera784a2c2009-01-09 04:53:57 +00001874 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001875 }
Matt Arsenault4815f092014-08-12 19:46:13 +00001876
1877 if (Operand->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1878 return new AddrSpaceCastInst(Operand, GEP.getType());
Matt Arsenault98f34e32013-08-19 22:17:34 +00001879 return new BitCastInst(Operand, GEP.getType());
Chris Lattnera784a2c2009-01-09 04:53:57 +00001880 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001881
Chris Lattnerfef138b2009-01-09 05:44:56 +00001882 // Otherwise, if the offset is non-zero, we need to find out if there is a
1883 // field at Offset in 'A's type. If so, we can pull the cast through the
1884 // GEP.
1885 SmallVector<Value*, 8> NewIndices;
Matt Arsenaultd79f7d92013-08-19 22:17:40 +00001886 if (FindElementAtOffset(OpType, Offset.getSExtValue(), NewIndices)) {
David Blaikieaa41cd52015-04-03 21:33:42 +00001887 Value *NGEP =
1888 GEP.isInBounds()
1889 ? Builder->CreateInBoundsGEP(nullptr, Operand, NewIndices)
1890 : Builder->CreateGEP(nullptr, Operand, NewIndices);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001891
Chris Lattner59663412009-08-30 18:50:58 +00001892 if (NGEP->getType() == GEP.getType())
Sanjay Patel4b198802016-02-01 22:23:39 +00001893 return replaceInstUsesWith(GEP, NGEP);
Chris Lattnerfef138b2009-01-09 05:44:56 +00001894 NGEP->takeName(&GEP);
Matt Arsenault4815f092014-08-12 19:46:13 +00001895
1896 if (NGEP->getType()->getPointerAddressSpace() != GEP.getAddressSpace())
1897 return new AddrSpaceCastInst(NGEP, GEP.getType());
Chris Lattnerfef138b2009-01-09 05:44:56 +00001898 return new BitCastInst(NGEP, GEP.getType());
1899 }
Chris Lattnera784a2c2009-01-09 04:53:57 +00001900 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00001901 }
1902
David Majnemer4e4f4432016-08-07 07:58:00 +00001903 if (!GEP.isInBounds()) {
1904 unsigned PtrWidth =
1905 DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
1906 APInt BasePtrOffset(PtrWidth, 0);
1907 Value *UnderlyingPtrOp =
1908 PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
1909 BasePtrOffset);
1910 if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
1911 if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
1912 BasePtrOffset.isNonNegative()) {
1913 APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
1914 if (BasePtrOffset.ule(AllocSize)) {
1915 return GetElementPtrInst::CreateInBounds(
1916 PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
1917 }
1918 }
1919 }
1920 }
1921
Craig Topperf40110f2014-04-25 05:29:35 +00001922 return nullptr;
Chris Lattnerca081252001-12-14 16:52:21 +00001923}
1924
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001925static bool isNeverEqualToUnescapedAlloc(Value *V, const TargetLibraryInfo *TLI,
1926 Instruction *AI) {
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001927 if (isa<ConstantPointerNull>(V))
1928 return true;
1929 if (auto *LI = dyn_cast<LoadInst>(V))
1930 return isa<GlobalVariable>(LI->getPointerOperand());
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001931 // Two distinct allocations will never be equal.
1932 // We rely on LookThroughBitCast in isAllocLikeFn being false, since looking
1933 // through bitcasts of V can cause
1934 // the result statement below to be true, even when AI and V (ex:
1935 // i8* ->i32* ->i8* of AI) are the same allocations.
1936 return isAllocLikeFn(V, TLI) && V != AI;
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001937}
1938
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001939static bool
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001940isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1941 const TargetLibraryInfo *TLI) {
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001942 SmallVector<Instruction*, 4> Worklist;
1943 Worklist.push_back(AI);
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00001944
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001945 do {
1946 Instruction *PI = Worklist.pop_back_val();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001947 for (User *U : PI->users()) {
1948 Instruction *I = cast<Instruction>(U);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001949 switch (I->getOpcode()) {
1950 default:
1951 // Give up the moment we see something we can't handle.
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00001952 return false;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001953
1954 case Instruction::BitCast:
1955 case Instruction::GetElementPtr:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001956 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001957 Worklist.push_back(I);
1958 continue;
1959
1960 case Instruction::ICmp: {
1961 ICmpInst *ICI = cast<ICmpInst>(I);
1962 // We can fold eq/ne comparisons with null to false/true, respectively.
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001963 // We also fold comparisons in some conditions provided the alloc has
Anna Thomas95f68aa2016-04-25 13:58:05 +00001964 // not escaped (see isNeverEqualToUnescapedAlloc).
Sanjoy Dasa085cfc2016-04-21 19:26:45 +00001965 if (!ICI->isEquality())
1966 return false;
1967 unsigned OtherIndex = (ICI->getOperand(0) == PI) ? 1 : 0;
Sanjoy Dasf97229d2016-04-22 20:52:25 +00001968 if (!isNeverEqualToUnescapedAlloc(ICI->getOperand(OtherIndex), TLI, AI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001969 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001970 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001971 continue;
1972 }
1973
1974 case Instruction::Call:
1975 // Ignore no-op and store intrinsics.
1976 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1977 switch (II->getIntrinsicID()) {
1978 default:
1979 return false;
1980
1981 case Intrinsic::memmove:
1982 case Intrinsic::memcpy:
1983 case Intrinsic::memset: {
1984 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1985 if (MI->isVolatile() || MI->getRawDest() != PI)
1986 return false;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001987 LLVM_FALLTHROUGH;
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001988 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001989 case Intrinsic::dbg_declare:
1990 case Intrinsic::dbg_value:
1991 case Intrinsic::invariant_start:
1992 case Intrinsic::invariant_end:
1993 case Intrinsic::lifetime_start:
1994 case Intrinsic::lifetime_end:
1995 case Intrinsic::objectsize:
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00001996 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00001997 continue;
1998 }
1999 }
2000
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002001 if (isFreeCall(I, TLI)) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002002 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002003 continue;
2004 }
2005 return false;
2006
2007 case Instruction::Store: {
2008 StoreInst *SI = cast<StoreInst>(I);
2009 if (SI->isVolatile() || SI->getPointerOperand() != PI)
2010 return false;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002011 Users.emplace_back(I);
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002012 continue;
2013 }
2014 }
2015 llvm_unreachable("missing a return?");
Nuno Lopesfa0dffc2012-07-06 23:09:25 +00002016 }
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002017 } while (!Worklist.empty());
Duncan Sandsf162eac2010-05-27 19:09:06 +00002018 return true;
2019}
2020
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002021Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
Duncan Sandsf162eac2010-05-27 19:09:06 +00002022 // If we have a malloc call which is only used in any amount of comparisons
2023 // to null and free calls, delete the calls and replace the comparisons with
2024 // true or false as appropriate.
Nick Lewycky50f49662011-08-03 00:43:35 +00002025 SmallVector<WeakVH, 64> Users;
Justin Bogner99798402016-08-05 01:06:44 +00002026 if (isAllocSiteRemovable(&MI, Users, &TLI)) {
Nick Lewycky50f49662011-08-03 00:43:35 +00002027 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
Petar Jovanovic921c2b42016-03-09 14:12:47 +00002028 // Lowering all @llvm.objectsize calls first because they may
2029 // use a bitcast/GEP of the alloca we are removing.
2030 if (!Users[i])
2031 continue;
2032
2033 Instruction *I = cast<Instruction>(&*Users[i]);
2034
2035 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2036 if (II->getIntrinsicID() == Intrinsic::objectsize) {
George Burgess IV3f089142016-12-20 23:46:36 +00002037 ConstantInt *Result = lowerObjectSizeCall(II, DL, &TLI,
2038 /*MustSucceed=*/true);
2039 replaceInstUsesWith(*I, Result);
Petar Jovanovic921c2b42016-03-09 14:12:47 +00002040 eraseInstFromFunction(*I);
2041 Users[i] = nullptr; // Skip examining in the next loop.
2042 }
2043 }
2044 }
2045 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
2046 if (!Users[i])
2047 continue;
2048
2049 Instruction *I = cast<Instruction>(&*Users[i]);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002050
Nick Lewycky50f49662011-08-03 00:43:35 +00002051 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002052 replaceInstUsesWith(*C,
Nick Lewyckye8ae02d2011-08-02 22:08:01 +00002053 ConstantInt::get(Type::getInt1Ty(C->getContext()),
2054 C->isFalseWhenEqual()));
Nick Lewycky50f49662011-08-03 00:43:35 +00002055 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002056 replaceInstUsesWith(*I, UndefValue::get(I->getType()));
Duncan Sandsf162eac2010-05-27 19:09:06 +00002057 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002058 eraseInstFromFunction(*I);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002059 }
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002060
2061 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
Nuno Lopes9ac46612012-06-28 22:31:24 +00002062 // Replace invoke with a NOP intrinsic to maintain the original CFG
Sanjay Patelaf674fb2015-12-14 17:24:23 +00002063 Module *M = II->getModule();
Nuno Lopes9ac46612012-06-28 22:31:24 +00002064 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
2065 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
Dmitri Gribenko3238fb72013-05-05 00:40:33 +00002066 None, "", II->getParent());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002067 }
Sanjay Patel4b198802016-02-01 22:23:39 +00002068 return eraseInstFromFunction(MI);
Duncan Sandsf162eac2010-05-27 19:09:06 +00002069 }
Craig Topperf40110f2014-04-25 05:29:35 +00002070 return nullptr;
Duncan Sandsf162eac2010-05-27 19:09:06 +00002071}
2072
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002073/// \brief Move the call to free before a NULL test.
2074///
2075/// Check if this free is accessed after its argument has been test
2076/// against NULL (property 0).
2077/// If yes, it is legal to move this call in its predecessor block.
2078///
2079/// The move is performed only if the block containing the call to free
2080/// will be removed, i.e.:
2081/// 1. it has only one predecessor P, and P has two successors
2082/// 2. it contains the call and an unconditional branch
2083/// 3. its successor is the same as its predecessor's successor
2084///
2085/// The profitability is out-of concern here and this function should
2086/// be called only if the caller knows this transformation would be
2087/// profitable (e.g., for code size).
2088static Instruction *
2089tryToMoveFreeBeforeNullTest(CallInst &FI) {
2090 Value *Op = FI.getArgOperand(0);
2091 BasicBlock *FreeInstrBB = FI.getParent();
2092 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
2093
2094 // Validate part of constraint #1: Only one predecessor
2095 // FIXME: We can extend the number of predecessor, but in that case, we
2096 // would duplicate the call to free in each predecessor and it may
2097 // not be profitable even for code size.
2098 if (!PredBB)
Craig Topperf40110f2014-04-25 05:29:35 +00002099 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002100
2101 // Validate constraint #2: Does this block contains only the call to
2102 // free and an unconditional branch?
2103 // FIXME: We could check if we can speculate everything in the
2104 // predecessor block
2105 if (FreeInstrBB->size() != 2)
Craig Topperf40110f2014-04-25 05:29:35 +00002106 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002107 BasicBlock *SuccBB;
2108 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002109 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002110
2111 // Validate the rest of constraint #1 by matching on the pred branch.
2112 TerminatorInst *TI = PredBB->getTerminator();
2113 BasicBlock *TrueBB, *FalseBB;
2114 ICmpInst::Predicate Pred;
2115 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
Craig Topperf40110f2014-04-25 05:29:35 +00002116 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002117 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
Craig Topperf40110f2014-04-25 05:29:35 +00002118 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002119
2120 // Validate constraint #3: Ensure the null case just falls through.
2121 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
Craig Topperf40110f2014-04-25 05:29:35 +00002122 return nullptr;
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002123 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
2124 "Broken CFG: missing edge from predecessor to successor");
2125
2126 FI.moveBefore(TI);
2127 return &FI;
2128}
Duncan Sandsf162eac2010-05-27 19:09:06 +00002129
2130
Gabor Greif75f69432010-06-24 12:21:15 +00002131Instruction *InstCombiner::visitFree(CallInst &FI) {
2132 Value *Op = FI.getArgOperand(0);
Victor Hernandeze2971492009-10-24 04:23:03 +00002133
2134 // free undef -> unreachable.
2135 if (isa<UndefValue>(Op)) {
2136 // Insert a new store to null because we cannot modify the CFG here.
Eli Friedman41e509a2011-05-18 23:58:37 +00002137 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
2138 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
Sanjay Patel4b198802016-02-01 22:23:39 +00002139 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002140 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002141
Victor Hernandeze2971492009-10-24 04:23:03 +00002142 // If we have 'free null' delete the instruction. This can happen in stl code
2143 // when lots of inlining happens.
2144 if (isa<ConstantPointerNull>(Op))
Sanjay Patel4b198802016-02-01 22:23:39 +00002145 return eraseInstFromFunction(FI);
Victor Hernandeze2971492009-10-24 04:23:03 +00002146
Quentin Colombet3b2db0b2013-01-07 18:37:41 +00002147 // If we optimize for code size, try to move the call to free before the null
2148 // test so that simplify cfg can remove the empty block and dead code
2149 // elimination the branch. I.e., helps to turn something like:
2150 // if (foo) free(foo);
2151 // into
2152 // free(foo);
2153 if (MinimizeSize)
2154 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
2155 return I;
2156
Craig Topperf40110f2014-04-25 05:29:35 +00002157 return nullptr;
Victor Hernandeze2971492009-10-24 04:23:03 +00002158}
Chris Lattner8427bff2003-12-07 01:24:23 +00002159
Hal Finkel93873cc12014-09-07 21:28:34 +00002160Instruction *InstCombiner::visitReturnInst(ReturnInst &RI) {
2161 if (RI.getNumOperands() == 0) // ret void
2162 return nullptr;
Chris Lattner14a251b2007-04-15 00:07:55 +00002163
Hal Finkel93873cc12014-09-07 21:28:34 +00002164 Value *ResultOp = RI.getOperand(0);
2165 Type *VTy = ResultOp->getType();
2166 if (!VTy->isIntegerTy())
2167 return nullptr;
2168
2169 // There might be assume intrinsics dominating this return that completely
2170 // determine the value. If so, constant fold it.
2171 unsigned BitWidth = VTy->getPrimitiveSizeInBits();
2172 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2173 computeKnownBits(ResultOp, KnownZero, KnownOne, 0, &RI);
2174 if ((KnownZero|KnownOne).isAllOnesValue())
2175 RI.setOperand(0, Constant::getIntegerValue(VTy, KnownOne));
2176
2177 return nullptr;
2178}
Chris Lattner31f486c2005-01-31 05:36:43 +00002179
Chris Lattner9eef8a72003-06-04 04:46:00 +00002180Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2181 // Change br (not X), label True, label False to: br X, label False, True
Craig Topperf40110f2014-04-25 05:29:35 +00002182 Value *X = nullptr;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002183 BasicBlock *TrueDest;
2184 BasicBlock *FalseDest;
Dan Gohman5476cfd2009-08-12 16:23:25 +00002185 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00002186 !isa<Constant>(X)) {
2187 // Swap Destinations and condition...
2188 BI.setCondition(X);
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002189 BI.swapSuccessors();
Chris Lattnerd4252a72004-07-30 07:50:03 +00002190 return &BI;
2191 }
2192
Philip Reames71c40352015-03-10 22:52:37 +00002193 // If the condition is irrelevant, remove the use so that other
2194 // transforms on the condition become more effective.
2195 if (BI.isConditional() &&
2196 BI.getSuccessor(0) == BI.getSuccessor(1) &&
2197 !isa<UndefValue>(BI.getCondition())) {
2198 BI.setCondition(UndefValue::get(BI.getCondition()->getType()));
2199 return &BI;
2200 }
2201
Alp Tokercb402912014-01-24 17:20:08 +00002202 // Canonicalize fcmp_one -> fcmp_oeq
Reid Spencer266e42b2006-12-23 06:05:41 +00002203 FCmpInst::Predicate FPred; Value *Y;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002204 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002205 TrueDest, FalseDest)) &&
2206 BI.getCondition()->hasOneUse())
2207 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
2208 FPred == FCmpInst::FCMP_OGE) {
2209 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
2210 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002211
Chris Lattner905976b2009-08-30 06:13:40 +00002212 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002213 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002214 Worklist.Add(Cond);
Reid Spencer266e42b2006-12-23 06:05:41 +00002215 return &BI;
2216 }
2217
Alp Tokercb402912014-01-24 17:20:08 +00002218 // Canonicalize icmp_ne -> icmp_eq
Reid Spencer266e42b2006-12-23 06:05:41 +00002219 ICmpInst::Predicate IPred;
2220 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner905976b2009-08-30 06:13:40 +00002221 TrueDest, FalseDest)) &&
2222 BI.getCondition()->hasOneUse())
2223 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
2224 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
2225 IPred == ICmpInst::ICMP_SGE) {
2226 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
2227 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
2228 // Swap Destinations and condition.
Chandler Carruth3e8aa652011-10-17 01:11:57 +00002229 BI.swapSuccessors();
Chris Lattner905976b2009-08-30 06:13:40 +00002230 Worklist.Add(Cond);
Chris Lattnere967b342003-06-04 05:10:11 +00002231 return &BI;
2232 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002233
Craig Topperf40110f2014-04-25 05:29:35 +00002234 return nullptr;
Chris Lattner9eef8a72003-06-04 04:46:00 +00002235}
Chris Lattner1085bdf2002-11-04 16:18:53 +00002236
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002237Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
2238 Value *Cond = SI.getCondition();
Sanjay Patele730ce82016-12-12 16:13:52 +00002239 Value *Op0;
2240 ConstantInt *AddRHS;
2241 if (match(Cond, m_Add(m_Value(Op0), m_ConstantInt(AddRHS)))) {
2242 // Change 'switch (X+4) case 1:' into 'switch (X) case -3'.
2243 for (SwitchInst::CaseIt CaseIter : SI.cases()) {
2244 Constant *NewCase = ConstantExpr::getSub(CaseIter.getCaseValue(), AddRHS);
2245 assert(isa<ConstantInt>(NewCase) &&
2246 "Result of expression should be constant");
2247 CaseIter.setValue(cast<ConstantInt>(NewCase));
2248 }
2249 SI.setCondition(Op0);
2250 return &SI;
2251 }
2252
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002253 unsigned BitWidth = cast<IntegerType>(Cond->getType())->getBitWidth();
2254 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002255 computeKnownBits(Cond, KnownZero, KnownOne, 0, &SI);
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002256 unsigned LeadingKnownZeros = KnownZero.countLeadingOnes();
2257 unsigned LeadingKnownOnes = KnownOne.countLeadingOnes();
2258
2259 // Compute the number of leading bits we can ignore.
Sanjay Patel7521e1b2016-06-30 15:32:45 +00002260 // TODO: A better way to determine this would use ComputeNumSignBits().
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002261 for (auto &C : SI.cases()) {
2262 LeadingKnownZeros = std::min(
2263 LeadingKnownZeros, C.getCaseValue()->getValue().countLeadingZeros());
2264 LeadingKnownOnes = std::min(
2265 LeadingKnownOnes, C.getCaseValue()->getValue().countLeadingOnes());
2266 }
2267
2268 unsigned NewWidth = BitWidth - std::max(LeadingKnownZeros, LeadingKnownOnes);
2269
Sanjay Patel7c6eab52016-06-30 14:51:21 +00002270 // Shrink the condition operand if the new type is smaller than the old type.
2271 // This may produce a non-standard type for the switch, but that's ok because
2272 // the backend should extend back to a legal type for the target.
Sanjay Patel7521e1b2016-06-30 15:32:45 +00002273 if (NewWidth > 0 && NewWidth < BitWidth) {
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002274 IntegerType *Ty = IntegerType::get(SI.getContext(), NewWidth);
2275 Builder->SetInsertPoint(&SI);
Sanjay Patel7c6eab52016-06-30 14:51:21 +00002276 Value *NewCond = Builder->CreateTrunc(Cond, Ty, "trunc");
Akira Hatanaka5c221ef2014-10-16 06:00:46 +00002277 SI.setCondition(NewCond);
2278
Sanjay Patel87e2f672016-12-12 15:52:56 +00002279 for (SwitchInst::CaseIt CaseIter : SI.cases()) {
2280 APInt TruncatedCase = CaseIter.getCaseValue()->getValue().trunc(NewWidth);
2281 CaseIter.setValue(ConstantInt::get(SI.getContext(), TruncatedCase));
2282 }
Sanjay Patelabbc2ac2016-05-13 21:51:17 +00002283 return &SI;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002284 }
Bruno Cardoso Lopesf6cf8ad2014-12-19 17:12:35 +00002285
Sanjay Patele730ce82016-12-12 16:13:52 +00002286 return nullptr;
Chris Lattner4c9c20a2004-07-03 00:26:11 +00002287}
2288
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002289Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002290 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002291
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002292 if (!EV.hasIndices())
Sanjay Patel4b198802016-02-01 22:23:39 +00002293 return replaceInstUsesWith(EV, Agg);
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002294
David Majnemer25a796e2015-07-13 01:15:46 +00002295 if (Value *V =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002296 SimplifyExtractValueInst(Agg, EV.getIndices(), DL, &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00002297 return replaceInstUsesWith(EV, V);
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002298
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002299 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
2300 // We're extracting from an insertvalue instruction, compare the indices
2301 const unsigned *exti, *exte, *insi, *inse;
2302 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
2303 exte = EV.idx_end(), inse = IV->idx_end();
2304 exti != exte && insi != inse;
2305 ++exti, ++insi) {
2306 if (*insi != *exti)
2307 // The insert and extract both reference distinctly different elements.
2308 // This means the extract is not influenced by the insert, and we can
2309 // replace the aggregate operand of the extract with the aggregate
2310 // operand of the insert. i.e., replace
2311 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2312 // %E = extractvalue { i32, { i32 } } %I, 0
2313 // with
2314 // %E = extractvalue { i32, { i32 } } %A, 0
2315 return ExtractValueInst::Create(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002316 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002317 }
2318 if (exti == exte && insi == inse)
2319 // Both iterators are at the end: Index lists are identical. Replace
2320 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2321 // %C = extractvalue { i32, { i32 } } %B, 1, 0
2322 // with "i32 42"
Sanjay Patel4b198802016-02-01 22:23:39 +00002323 return replaceInstUsesWith(EV, IV->getInsertedValueOperand());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002324 if (exti == exte) {
2325 // The extract list is a prefix of the insert list. i.e. replace
2326 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
2327 // %E = extractvalue { i32, { i32 } } %I, 1
2328 // with
2329 // %X = extractvalue { i32, { i32 } } %A, 1
2330 // %E = insertvalue { i32 } %X, i32 42, 0
2331 // by switching the order of the insert and extract (though the
2332 // insertvalue should be left in, since it may have other uses).
Chris Lattner59663412009-08-30 18:50:58 +00002333 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +00002334 EV.getIndices());
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002335 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002336 makeArrayRef(insi, inse));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002337 }
2338 if (insi == inse)
2339 // The insert list is a prefix of the extract list
2340 // We can simply remove the common indices from the extract and make it
2341 // operate on the inserted value instead of the insertvalue result.
2342 // i.e., replace
2343 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
2344 // %E = extractvalue { i32, { i32 } } %I, 1, 0
2345 // with
2346 // %E extractvalue { i32 } { i32 42 }, 0
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002347 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
Frits van Bommel717d7ed2011-07-18 12:00:32 +00002348 makeArrayRef(exti, exte));
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002349 }
Chris Lattner39c07b22009-11-09 07:07:56 +00002350 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
2351 // We're extracting from an intrinsic, see if we're the only user, which
2352 // allows us to simplify multiple result intrinsics to simpler things that
Gabor Greif75f69432010-06-24 12:21:15 +00002353 // just get one value.
Chris Lattner39c07b22009-11-09 07:07:56 +00002354 if (II->hasOneUse()) {
2355 // Check if we're grabbing the overflow bit or the result of a 'with
2356 // overflow' intrinsic. If it's the latter we can remove the intrinsic
2357 // and replace it with a traditional binary instruction.
2358 switch (II->getIntrinsicID()) {
2359 case Intrinsic::uadd_with_overflow:
2360 case Intrinsic::sadd_with_overflow:
2361 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002362 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002363 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2364 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002365 return BinaryOperator::CreateAdd(LHS, RHS);
2366 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002367
Chris Lattner3e635d22010-12-19 19:43:52 +00002368 // If the normal result of the add is dead, and the RHS is a constant,
2369 // we can transform this into a range comparison.
2370 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
Chris Lattner4fb9dd42010-12-19 23:24:04 +00002371 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
2372 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
2373 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
2374 ConstantExpr::getNot(CI));
Chris Lattner39c07b22009-11-09 07:07:56 +00002375 break;
2376 case Intrinsic::usub_with_overflow:
2377 case Intrinsic::ssub_with_overflow:
2378 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002379 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002380 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2381 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002382 return BinaryOperator::CreateSub(LHS, RHS);
2383 }
2384 break;
2385 case Intrinsic::umul_with_overflow:
2386 case Intrinsic::smul_with_overflow:
2387 if (*EV.idx_begin() == 0) { // Normal result.
Gabor Greif75f69432010-06-24 12:21:15 +00002388 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Sanjay Patel4b198802016-02-01 22:23:39 +00002389 replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2390 eraseInstFromFunction(*II);
Chris Lattner39c07b22009-11-09 07:07:56 +00002391 return BinaryOperator::CreateMul(LHS, RHS);
2392 }
2393 break;
2394 default:
2395 break;
2396 }
2397 }
2398 }
Frits van Bommel28218aa2010-11-29 21:56:20 +00002399 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
2400 // If the (non-volatile) load only has one use, we can rewrite this to a
Mehdi Amini1c131b32015-12-15 01:44:07 +00002401 // load from a GEP. This reduces the size of the load. If a load is used
2402 // only by extractvalue instructions then this either must have been
2403 // optimized before, or it is a struct with padding, in which case we
2404 // don't want to do the transformation as it loses padding knowledge.
Eli Friedman8bc586e2011-08-15 22:09:40 +00002405 if (L->isSimple() && L->hasOneUse()) {
Frits van Bommel28218aa2010-11-29 21:56:20 +00002406 // extractvalue has integer indices, getelementptr has Value*s. Convert.
2407 SmallVector<Value*, 4> Indices;
2408 // Prefix an i32 0 since we need the first element.
2409 Indices.push_back(Builder->getInt32(0));
2410 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
2411 I != E; ++I)
2412 Indices.push_back(Builder->getInt32(*I));
2413
2414 // We need to insert these at the location of the old load, not at that of
2415 // the extractvalue.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002416 Builder->SetInsertPoint(L);
David Blaikieaa41cd52015-04-03 21:33:42 +00002417 Value *GEP = Builder->CreateInBoundsGEP(L->getType(),
2418 L->getPointerOperand(), Indices);
Frits van Bommel28218aa2010-11-29 21:56:20 +00002419 // Returning the load directly will cause the main loop to insert it in
Sanjay Patel4b198802016-02-01 22:23:39 +00002420 // the wrong spot, so use replaceInstUsesWith().
2421 return replaceInstUsesWith(EV, Builder->CreateLoad(GEP));
Frits van Bommel28218aa2010-11-29 21:56:20 +00002422 }
2423 // We could simplify extracts from other values. Note that nested extracts may
2424 // already be simplified implicitly by the above: extract (extract (insert) )
Matthijs Kooijmanc1d74772008-07-16 12:55:45 +00002425 // will be translated into extract ( insert ( extract ) ) first and then just
Frits van Bommel28218aa2010-11-29 21:56:20 +00002426 // the value inserted, if appropriate. Similarly for extracts from single-use
2427 // loads: extract (extract (load)) will be translated to extract (load (gep))
2428 // and if again single-use then via load (gep (gep)) to load (gep).
2429 // However, double extracts from e.g. function arguments or return values
2430 // aren't handled yet.
Craig Topperf40110f2014-04-25 05:29:35 +00002431 return nullptr;
Matthijs Kooijmanb2fc72b2008-06-11 14:05:05 +00002432}
2433
Sanjay Patel84dca492015-09-21 15:33:26 +00002434/// Return 'true' if the given typeinfo will match anything.
Reid Kleckner4af64152015-01-28 01:17:38 +00002435static bool isCatchAll(EHPersonality Personality, Constant *TypeInfo) {
Duncan Sands5c055792011-09-30 13:12:16 +00002436 switch (Personality) {
Reid Kleckner4af64152015-01-28 01:17:38 +00002437 case EHPersonality::GNU_C:
Saleem Abdulrasoold2f705d2016-05-31 01:48:07 +00002438 case EHPersonality::GNU_C_SjLj:
Bjorn Steinbrink37ca4622016-03-15 20:57:07 +00002439 case EHPersonality::Rust:
2440 // The GCC C EH and Rust personality only exists to support cleanups, so
2441 // it's not clear what the semantics of catch clauses are.
Duncan Sands5c055792011-09-30 13:12:16 +00002442 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002443 case EHPersonality::Unknown:
2444 return false;
2445 case EHPersonality::GNU_Ada:
Duncan Sands5c055792011-09-30 13:12:16 +00002446 // While __gnat_all_others_value will match any Ada exception, it doesn't
2447 // match foreign exceptions (or didn't, before gcc-4.7).
2448 return false;
Reid Kleckner4af64152015-01-28 01:17:38 +00002449 case EHPersonality::GNU_CXX:
Saleem Abdulrasoold2f705d2016-05-31 01:48:07 +00002450 case EHPersonality::GNU_CXX_SjLj:
Reid Kleckner4af64152015-01-28 01:17:38 +00002451 case EHPersonality::GNU_ObjC:
Reid Kleckner96d01132015-02-11 01:23:16 +00002452 case EHPersonality::MSVC_X86SEH:
Reid Kleckner4af64152015-01-28 01:17:38 +00002453 case EHPersonality::MSVC_Win64SEH:
2454 case EHPersonality::MSVC_CXX:
Joseph Tremoulet2afea542015-10-06 20:28:16 +00002455 case EHPersonality::CoreCLR:
Duncan Sands5c055792011-09-30 13:12:16 +00002456 return TypeInfo->isNullValue();
2457 }
Reid Kleckner4af64152015-01-28 01:17:38 +00002458 llvm_unreachable("invalid enum");
Duncan Sands5c055792011-09-30 13:12:16 +00002459}
2460
2461static bool shorter_filter(const Value *LHS, const Value *RHS) {
2462 return
2463 cast<ArrayType>(LHS->getType())->getNumElements()
2464 <
2465 cast<ArrayType>(RHS->getType())->getNumElements();
2466}
2467
2468Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
2469 // The logic here should be correct for any real-world personality function.
2470 // However if that turns out not to be true, the offending logic can always
2471 // be conditioned on the personality function, like the catch-all logic is.
David Majnemer7fddecc2015-06-17 20:52:32 +00002472 EHPersonality Personality =
2473 classifyEHPersonality(LI.getParent()->getParent()->getPersonalityFn());
Duncan Sands5c055792011-09-30 13:12:16 +00002474
2475 // Simplify the list of clauses, eg by removing repeated catch clauses
2476 // (these are often created by inlining).
2477 bool MakeNewInstruction = false; // If true, recreate using the following:
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002478 SmallVector<Constant *, 16> NewClauses; // - Clauses for the new instruction;
Duncan Sands5c055792011-09-30 13:12:16 +00002479 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
2480
2481 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
2482 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
2483 bool isLastClause = i + 1 == e;
2484 if (LI.isCatch(i)) {
2485 // A catch clause.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002486 Constant *CatchClause = LI.getClause(i);
Rafael Espindola78598d92014-06-04 19:01:48 +00002487 Constant *TypeInfo = CatchClause->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002488
2489 // If we already saw this clause, there is no point in having a second
2490 // copy of it.
David Blaikie70573dc2014-11-19 07:49:26 +00002491 if (AlreadyCaught.insert(TypeInfo).second) {
Duncan Sands5c055792011-09-30 13:12:16 +00002492 // This catch clause was not already seen.
2493 NewClauses.push_back(CatchClause);
2494 } else {
2495 // Repeated catch clause - drop the redundant copy.
2496 MakeNewInstruction = true;
2497 }
2498
2499 // If this is a catch-all then there is no point in keeping any following
2500 // clauses or marking the landingpad as having a cleanup.
2501 if (isCatchAll(Personality, TypeInfo)) {
2502 if (!isLastClause)
2503 MakeNewInstruction = true;
2504 CleanupFlag = false;
2505 break;
2506 }
2507 } else {
2508 // A filter clause. If any of the filter elements were already caught
2509 // then they can be dropped from the filter. It is tempting to try to
2510 // exploit the filter further by saying that any typeinfo that does not
2511 // occur in the filter can't be caught later (and thus can be dropped).
2512 // However this would be wrong, since typeinfos can match without being
2513 // equal (for example if one represents a C++ class, and the other some
2514 // class derived from it).
2515 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002516 Constant *FilterClause = LI.getClause(i);
Duncan Sands5c055792011-09-30 13:12:16 +00002517 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
2518 unsigned NumTypeInfos = FilterType->getNumElements();
2519
2520 // An empty filter catches everything, so there is no point in keeping any
2521 // following clauses or marking the landingpad as having a cleanup. By
2522 // dealing with this case here the following code is made a bit simpler.
2523 if (!NumTypeInfos) {
2524 NewClauses.push_back(FilterClause);
2525 if (!isLastClause)
2526 MakeNewInstruction = true;
2527 CleanupFlag = false;
2528 break;
2529 }
2530
2531 bool MakeNewFilter = false; // If true, make a new filter.
2532 SmallVector<Constant *, 16> NewFilterElts; // New elements.
2533 if (isa<ConstantAggregateZero>(FilterClause)) {
2534 // Not an empty filter - it contains at least one null typeinfo.
2535 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
2536 Constant *TypeInfo =
2537 Constant::getNullValue(FilterType->getElementType());
2538 // If this typeinfo is a catch-all then the filter can never match.
2539 if (isCatchAll(Personality, TypeInfo)) {
2540 // Throw the filter away.
2541 MakeNewInstruction = true;
2542 continue;
2543 }
2544
2545 // There is no point in having multiple copies of this typeinfo, so
2546 // discard all but the first copy if there is more than one.
2547 NewFilterElts.push_back(TypeInfo);
2548 if (NumTypeInfos > 1)
2549 MakeNewFilter = true;
2550 } else {
2551 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
2552 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
2553 NewFilterElts.reserve(NumTypeInfos);
2554
2555 // Remove any filter elements that were already caught or that already
2556 // occurred in the filter. While there, see if any of the elements are
2557 // catch-alls. If so, the filter can be discarded.
2558 bool SawCatchAll = false;
2559 for (unsigned j = 0; j != NumTypeInfos; ++j) {
Rafael Espindola78598d92014-06-04 19:01:48 +00002560 Constant *Elt = Filter->getOperand(j);
2561 Constant *TypeInfo = Elt->stripPointerCasts();
Duncan Sands5c055792011-09-30 13:12:16 +00002562 if (isCatchAll(Personality, TypeInfo)) {
2563 // This element is a catch-all. Bail out, noting this fact.
2564 SawCatchAll = true;
2565 break;
2566 }
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002567
2568 // Even if we've seen a type in a catch clause, we don't want to
2569 // remove it from the filter. An unexpected type handler may be
2570 // set up for a call site which throws an exception of the same
2571 // type caught. In order for the exception thrown by the unexpected
Simon Pilgrim7d18a702016-11-20 13:19:49 +00002572 // handler to propagate correctly, the filter must be correctly
Andrew Kaylorde642ce2015-11-17 20:13:04 +00002573 // described for the call site.
2574 //
2575 // Example:
2576 //
2577 // void unexpected() { throw 1;}
2578 // void foo() throw (int) {
2579 // std::set_unexpected(unexpected);
2580 // try {
2581 // throw 2.0;
2582 // } catch (int i) {}
2583 // }
2584
Duncan Sands5c055792011-09-30 13:12:16 +00002585 // There is no point in having multiple copies of the same typeinfo in
2586 // a filter, so only add it if we didn't already.
David Blaikie70573dc2014-11-19 07:49:26 +00002587 if (SeenInFilter.insert(TypeInfo).second)
Duncan Sands5c055792011-09-30 13:12:16 +00002588 NewFilterElts.push_back(cast<Constant>(Elt));
2589 }
2590 // A filter containing a catch-all cannot match anything by definition.
2591 if (SawCatchAll) {
2592 // Throw the filter away.
2593 MakeNewInstruction = true;
2594 continue;
2595 }
2596
2597 // If we dropped something from the filter, make a new one.
2598 if (NewFilterElts.size() < NumTypeInfos)
2599 MakeNewFilter = true;
2600 }
2601 if (MakeNewFilter) {
2602 FilterType = ArrayType::get(FilterType->getElementType(),
2603 NewFilterElts.size());
2604 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
2605 MakeNewInstruction = true;
2606 }
2607
2608 NewClauses.push_back(FilterClause);
2609
2610 // If the new filter is empty then it will catch everything so there is
2611 // no point in keeping any following clauses or marking the landingpad
2612 // as having a cleanup. The case of the original filter being empty was
2613 // already handled above.
2614 if (MakeNewFilter && !NewFilterElts.size()) {
2615 assert(MakeNewInstruction && "New filter but not a new instruction!");
2616 CleanupFlag = false;
2617 break;
2618 }
2619 }
2620 }
2621
2622 // If several filters occur in a row then reorder them so that the shortest
2623 // filters come first (those with the smallest number of elements). This is
2624 // advantageous because shorter filters are more likely to match, speeding up
2625 // unwinding, but mostly because it increases the effectiveness of the other
2626 // filter optimizations below.
2627 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
2628 unsigned j;
2629 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
2630 for (j = i; j != e; ++j)
2631 if (!isa<ArrayType>(NewClauses[j]->getType()))
2632 break;
2633
2634 // Check whether the filters are already sorted by length. We need to know
2635 // if sorting them is actually going to do anything so that we only make a
2636 // new landingpad instruction if it does.
2637 for (unsigned k = i; k + 1 < j; ++k)
2638 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
2639 // Not sorted, so sort the filters now. Doing an unstable sort would be
2640 // correct too but reordering filters pointlessly might confuse users.
2641 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
2642 shorter_filter);
2643 MakeNewInstruction = true;
2644 break;
2645 }
2646
2647 // Look for the next batch of filters.
2648 i = j + 1;
2649 }
2650
2651 // If typeinfos matched if and only if equal, then the elements of a filter L
2652 // that occurs later than a filter F could be replaced by the intersection of
2653 // the elements of F and L. In reality two typeinfos can match without being
2654 // equal (for example if one represents a C++ class, and the other some class
2655 // derived from it) so it would be wrong to perform this transform in general.
2656 // However the transform is correct and useful if F is a subset of L. In that
2657 // case L can be replaced by F, and thus removed altogether since repeating a
2658 // filter is pointless. So here we look at all pairs of filters F and L where
2659 // L follows F in the list of clauses, and remove L if every element of F is
2660 // an element of L. This can occur when inlining C++ functions with exception
2661 // specifications.
2662 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2663 // Examine each filter in turn.
2664 Value *Filter = NewClauses[i];
2665 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2666 if (!FTy)
2667 // Not a filter - skip it.
2668 continue;
2669 unsigned FElts = FTy->getNumElements();
2670 // Examine each filter following this one. Doing this backwards means that
2671 // we don't have to worry about filters disappearing under us when removed.
2672 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2673 Value *LFilter = NewClauses[j];
2674 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2675 if (!LTy)
2676 // Not a filter - skip it.
2677 continue;
2678 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2679 // an element of LFilter, then discard LFilter.
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00002680 SmallVectorImpl<Constant *>::iterator J = NewClauses.begin() + j;
Duncan Sands5c055792011-09-30 13:12:16 +00002681 // If Filter is empty then it is a subset of LFilter.
2682 if (!FElts) {
2683 // Discard LFilter.
2684 NewClauses.erase(J);
2685 MakeNewInstruction = true;
2686 // Move on to the next filter.
2687 continue;
2688 }
2689 unsigned LElts = LTy->getNumElements();
2690 // If Filter is longer than LFilter then it cannot be a subset of it.
2691 if (FElts > LElts)
2692 // Move on to the next filter.
2693 continue;
2694 // At this point we know that LFilter has at least one element.
2695 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002696 // Filter is a subset of LFilter iff Filter contains only zeros (as we
Duncan Sands5c055792011-09-30 13:12:16 +00002697 // already know that Filter is not longer than LFilter).
2698 if (isa<ConstantAggregateZero>(Filter)) {
2699 assert(FElts <= LElts && "Should have handled this case earlier!");
2700 // Discard LFilter.
2701 NewClauses.erase(J);
2702 MakeNewInstruction = true;
2703 }
2704 // Move on to the next filter.
2705 continue;
2706 }
2707 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2708 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2709 // Since Filter is non-empty and contains only zeros, it is a subset of
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002710 // LFilter iff LFilter contains a zero.
Duncan Sands5c055792011-09-30 13:12:16 +00002711 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2712 for (unsigned l = 0; l != LElts; ++l)
2713 if (LArray->getOperand(l)->isNullValue()) {
2714 // LFilter contains a zero - discard it.
2715 NewClauses.erase(J);
2716 MakeNewInstruction = true;
2717 break;
2718 }
2719 // Move on to the next filter.
2720 continue;
2721 }
2722 // At this point we know that both filters are ConstantArrays. Loop over
2723 // operands to see whether every element of Filter is also an element of
2724 // LFilter. Since filters tend to be short this is probably faster than
2725 // using a method that scales nicely.
2726 ConstantArray *FArray = cast<ConstantArray>(Filter);
2727 bool AllFound = true;
2728 for (unsigned f = 0; f != FElts; ++f) {
2729 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2730 AllFound = false;
2731 for (unsigned l = 0; l != LElts; ++l) {
2732 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2733 if (LTypeInfo == FTypeInfo) {
2734 AllFound = true;
2735 break;
2736 }
2737 }
2738 if (!AllFound)
2739 break;
2740 }
2741 if (AllFound) {
2742 // Discard LFilter.
2743 NewClauses.erase(J);
2744 MakeNewInstruction = true;
2745 }
2746 // Move on to the next filter.
2747 }
2748 }
2749
2750 // If we changed any of the clauses, replace the old landingpad instruction
2751 // with a new one.
2752 if (MakeNewInstruction) {
2753 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
Duncan Sands5c055792011-09-30 13:12:16 +00002754 NewClauses.size());
2755 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2756 NLI->addClause(NewClauses[i]);
2757 // A landing pad with no clauses must have the cleanup flag set. It is
2758 // theoretically possible, though highly unlikely, that we eliminated all
2759 // clauses. If so, force the cleanup flag to true.
2760 if (NewClauses.empty())
2761 CleanupFlag = true;
2762 NLI->setCleanup(CleanupFlag);
2763 return NLI;
2764 }
2765
2766 // Even if none of the clauses changed, we may nonetheless have understood
2767 // that the cleanup flag is pointless. Clear it if so.
2768 if (LI.isCleanup() != CleanupFlag) {
2769 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2770 LI.setCleanup(CleanupFlag);
2771 return &LI;
2772 }
2773
Craig Topperf40110f2014-04-25 05:29:35 +00002774 return nullptr;
Duncan Sands5c055792011-09-30 13:12:16 +00002775}
2776
Sanjay Patel84dca492015-09-21 15:33:26 +00002777/// Try to move the specified instruction from its current block into the
2778/// beginning of DestBlock, which can only happen if it's safe to move the
2779/// instruction past all of the instructions between it and the end of its
2780/// block.
Chris Lattner39c98bb2004-12-08 23:43:58 +00002781static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2782 assert(I->hasOneUse() && "Invariants didn't hold!");
2783
Bill Wendlinge86965e2011-08-15 21:14:31 +00002784 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
David Majnemer60c994b2015-08-08 03:51:49 +00002785 if (isa<PHINode>(I) || I->isEHPad() || I->mayHaveSideEffects() ||
Bill Wendlinga9ee09f2011-08-17 20:36:44 +00002786 isa<TerminatorInst>(I))
Chris Lattnera4ee1f52008-05-09 15:07:33 +00002787 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002788
Chris Lattner39c98bb2004-12-08 23:43:58 +00002789 // Do not sink alloca instructions out of the entry block.
Dan Gohmandcb291f2007-03-22 16:38:57 +00002790 if (isa<AllocaInst>(I) && I->getParent() ==
2791 &DestBlock->getParent()->getEntryBlock())
Chris Lattner39c98bb2004-12-08 23:43:58 +00002792 return false;
2793
David Majnemerfe3f9d12016-04-01 17:28:17 +00002794 // Do not sink into catchswitch blocks.
2795 if (isa<CatchSwitchInst>(DestBlock->getTerminator()))
2796 return false;
2797
Fiona Glasera8b653a2015-11-03 22:23:39 +00002798 // Do not sink convergent call instructions.
2799 if (auto *CI = dyn_cast<CallInst>(I)) {
2800 if (CI->isConvergent())
2801 return false;
2802 }
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002803 // We can only sink load instructions if there is nothing between the load and
2804 // the end of block that could change the value.
Chris Lattner49a594e2008-05-08 17:37:37 +00002805 if (I->mayReadFromMemory()) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002806 for (BasicBlock::iterator Scan = I->getIterator(),
2807 E = I->getParent()->end();
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002808 Scan != E; ++Scan)
2809 if (Scan->mayWriteToMemory())
2810 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00002811 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002812
Bill Wendling8ddfc092011-08-16 20:45:24 +00002813 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002814 I->moveBefore(&*InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00002815 ++NumSunkInst;
2816 return true;
2817}
2818
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002819bool InstCombiner::run() {
Chris Lattner97fd3592009-08-30 05:55:36 +00002820 while (!Worklist.isEmpty()) {
2821 Instruction *I = Worklist.RemoveOne();
Craig Topperf40110f2014-04-25 05:29:35 +00002822 if (I == nullptr) continue; // skip null values.
Chris Lattnerca081252001-12-14 16:52:21 +00002823
Chris Lattner1443bc52006-05-11 17:11:52 +00002824 // Check to see if we can DCE the instruction.
Justin Bogner99798402016-08-05 01:06:44 +00002825 if (isInstructionTriviallyDead(I, &TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002826 DEBUG(dbgs() << "IC: DCE: " << *I << '\n');
Sanjay Patel4b198802016-02-01 22:23:39 +00002827 eraseInstFromFunction(*I);
Chris Lattner905976b2009-08-30 06:13:40 +00002828 ++NumDeadInst;
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002829 MadeIRChange = true;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002830 continue;
2831 }
Chris Lattner99f48c62002-09-02 04:59:56 +00002832
Chris Lattner1443bc52006-05-11 17:11:52 +00002833 // Instruction isn't dead, see if we can constant propagate it.
David Majnemer7fddecc2015-06-17 20:52:32 +00002834 if (!I->use_empty() &&
2835 (I->getNumOperands() == 0 || isa<Constant>(I->getOperand(0)))) {
Justin Bogner99798402016-08-05 01:06:44 +00002836 if (Constant *C = ConstantFoldInstruction(I, DL, &TLI)) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002837 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnercd517ff2005-01-28 19:32:01 +00002838
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002839 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002840 replaceInstUsesWith(*I, C);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002841 ++NumConstProp;
Justin Bogner99798402016-08-05 01:06:44 +00002842 if (isInstructionTriviallyDead(I, &TLI))
David Majnemer522a9112016-07-22 04:54:44 +00002843 eraseInstFromFunction(*I);
Chris Lattnerdd1f68a2009-10-15 04:13:44 +00002844 MadeIRChange = true;
2845 continue;
2846 }
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002847 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002848
Matthias Braunc31032d2016-03-09 18:47:11 +00002849 // In general, it is possible for computeKnownBits to determine all bits in
2850 // a value even when the operands are not all constants.
Sanjay Patelc96f6db2016-09-16 21:20:36 +00002851 Type *Ty = I->getType();
2852 if (ExpensiveCombines && !I->use_empty() && Ty->isIntOrIntVectorTy()) {
2853 unsigned BitWidth = Ty->getScalarSizeInBits();
Hal Finkelf2199b22015-10-23 20:37:08 +00002854 APInt KnownZero(BitWidth, 0);
2855 APInt KnownOne(BitWidth, 0);
2856 computeKnownBits(I, KnownZero, KnownOne, /*Depth*/0, I);
2857 if ((KnownZero | KnownOne).isAllOnesValue()) {
Sanjay Patelc96f6db2016-09-16 21:20:36 +00002858 Constant *C = ConstantInt::get(Ty, KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00002859 DEBUG(dbgs() << "IC: ConstFold (all bits known) to: " << *C <<
2860 " from: " << *I << '\n');
2861
2862 // Add operands to the worklist.
Sanjay Patel4b198802016-02-01 22:23:39 +00002863 replaceInstUsesWith(*I, C);
Hal Finkelf2199b22015-10-23 20:37:08 +00002864 ++NumConstProp;
Justin Bogner99798402016-08-05 01:06:44 +00002865 if (isInstructionTriviallyDead(I, &TLI))
David Majnemer522a9112016-07-22 04:54:44 +00002866 eraseInstFromFunction(*I);
Hal Finkelf2199b22015-10-23 20:37:08 +00002867 MadeIRChange = true;
2868 continue;
2869 }
2870 }
2871
Chris Lattner39c98bb2004-12-08 23:43:58 +00002872 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfa1211f2008-07-23 00:34:11 +00002873 if (I->hasOneUse()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002874 BasicBlock *BB = I->getParent();
Chandler Carruthcdf47882014-03-09 03:16:01 +00002875 Instruction *UserInst = cast<Instruction>(*I->user_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002876 BasicBlock *UserParent;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002877
Chris Lattner6b9044d2009-10-14 15:21:58 +00002878 // Get the block the use occurs in.
2879 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002880 UserParent = PN->getIncomingBlock(*I->use_begin());
Chris Lattner6b9044d2009-10-14 15:21:58 +00002881 else
2882 UserParent = UserInst->getParent();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002883
Chris Lattner39c98bb2004-12-08 23:43:58 +00002884 if (UserParent != BB) {
2885 bool UserIsSuccessor = false;
2886 // See if the user is one of our successors.
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002887 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2888 if (*SI == UserParent) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002889 UserIsSuccessor = true;
2890 break;
2891 }
2892
2893 // If the user is one of our immediate successors, and if that successor
2894 // only has us as a predecessors (we'd have to split the critical edge
2895 // otherwise), we can keep going.
Jun Bum Limec8b8cc2016-08-22 18:21:56 +00002896 if (UserIsSuccessor && UserParent->getUniquePredecessor()) {
Chris Lattner39c98bb2004-12-08 23:43:58 +00002897 // Okay, the CFG is simple enough, try to sink this instruction.
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002898 if (TryToSinkInstruction(I, UserParent)) {
David Majnemerfe3f9d12016-04-01 17:28:17 +00002899 DEBUG(dbgs() << "IC: Sink: " << *I << '\n');
Aditya Nandakumar0b5a6742014-07-11 21:49:39 +00002900 MadeIRChange = true;
2901 // We'll add uses of the sunk instruction below, but since sinking
2902 // can expose opportunities for it's *operands* add them to the
2903 // worklist
2904 for (Use &U : I->operands())
2905 if (Instruction *OpI = dyn_cast<Instruction>(U.get()))
2906 Worklist.Add(OpI);
2907 }
2908 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00002909 }
2910 }
2911
Chris Lattner022a5822009-08-30 07:44:24 +00002912 // Now that we have an instruction, try combining it to simplify it.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002913 Builder->SetInsertPoint(I);
Eli Friedman96254a02011-05-18 01:28:27 +00002914 Builder->SetCurrentDebugLocation(I->getDebugLoc());
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002915
Reid Spencer755d0e72007-03-26 17:44:01 +00002916#ifndef NDEBUG
2917 std::string OrigI;
2918#endif
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002919 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002920 DEBUG(dbgs() << "IC: Visiting: " << OrigI << '\n');
Jeffrey Yasskindafd08e2009-10-08 00:12:24 +00002921
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002922 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00002923 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00002924 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00002925 if (Result != I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002926 DEBUG(dbgs() << "IC: Old = " << *I << '\n'
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002927 << " New = " << *Result << '\n');
2928
Duncan P. N. Exon Smithec819c02015-03-30 19:49:49 +00002929 if (I->getDebugLoc())
Eli Friedman35211c62011-05-27 00:19:40 +00002930 Result->setDebugLoc(I->getDebugLoc());
Chris Lattner396dbfe2004-06-09 05:08:07 +00002931 // Everything uses the new instruction now.
2932 I->replaceAllUsesWith(Result);
2933
Jim Grosbache7abae02011-10-05 20:53:43 +00002934 // Move the name to the new instruction first.
2935 Result->takeName(I);
2936
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002937 // Push the new instruction and any users onto the worklist.
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002938 Worklist.AddUsersToWorkList(*Result);
Craig Toppere625d742017-03-31 21:35:30 +00002939 Worklist.Add(Result);
Jim Grosbach8f9acfa2011-10-05 20:44:29 +00002940
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002941 // Insert the new instruction into the basic block...
2942 BasicBlock *InstParent = I->getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002943 BasicBlock::iterator InsertPos = I->getIterator();
Chris Lattner7515cab2004-11-14 19:13:23 +00002944
Eli Friedmana49b8282011-11-01 04:49:29 +00002945 // If we replace a PHI with something that isn't a PHI, fix up the
2946 // insertion point.
2947 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2948 InsertPos = InstParent->getFirstInsertionPt();
Chris Lattner7515cab2004-11-14 19:13:23 +00002949
2950 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00002951
Sanjay Patel4b198802016-02-01 22:23:39 +00002952 eraseInstFromFunction(*I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002953 } else {
Matt Arsenaulte6db7602013-09-05 19:48:28 +00002954 DEBUG(dbgs() << "IC: Mod = " << OrigI << '\n'
Chris Lattnerb25de3f2009-08-23 04:37:46 +00002955 << " New = " << *I << '\n');
Chris Lattner7d2a5392004-03-13 23:54:27 +00002956
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002957 // If the instruction was modified, it's possible that it is now dead.
2958 // if so, remove it.
Justin Bogner99798402016-08-05 01:06:44 +00002959 if (isInstructionTriviallyDead(I, &TLI)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002960 eraseInstFromFunction(*I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00002961 } else {
Chris Lattnerbacd05c2009-08-30 06:22:51 +00002962 Worklist.AddUsersToWorkList(*I);
Craig Toppere625d742017-03-31 21:35:30 +00002963 Worklist.Add(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002964 }
Chris Lattner053c0932002-05-14 15:24:07 +00002965 }
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002966 MadeIRChange = true;
Chris Lattnerca081252001-12-14 16:52:21 +00002967 }
2968 }
2969
Chris Lattner97fd3592009-08-30 05:55:36 +00002970 Worklist.Zap();
Chris Lattnerff5f1e42009-08-31 06:57:37 +00002971 return MadeIRChange;
Chris Lattner04805fa2002-02-26 21:46:54 +00002972}
2973
Sanjay Patel84dca492015-09-21 15:33:26 +00002974/// Walk the function in depth-first order, adding all reachable code to the
2975/// worklist.
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002976///
2977/// This has a couple of tricks to make the code faster and more powerful. In
2978/// particular, we constant fold and DCE instructions as we go, to avoid adding
2979/// them to the worklist (this significantly speeds up instcombine on code where
2980/// many instructions are dead or constant). Additionally, if we find a branch
2981/// whose condition is a known constant, we only visit the reachable successors.
2982///
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002983static bool AddReachableCodeToWorklist(BasicBlock *BB, const DataLayout &DL,
2984 SmallPtrSetImpl<BasicBlock *> &Visited,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002985 InstCombineWorklist &ICWorklist,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002986 const TargetLibraryInfo *TLI) {
2987 bool MadeIRChange = false;
2988 SmallVector<BasicBlock*, 256> Worklist;
2989 Worklist.push_back(BB);
Hal Finkel60db0582014-09-07 18:57:58 +00002990
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002991 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
David Majnemerd536f232016-07-29 03:27:26 +00002992 DenseMap<Constant *, Constant *> FoldedConstants;
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002993
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002994 do {
2995 BB = Worklist.pop_back_val();
Jakub Staszakcfc46f82012-05-06 13:52:31 +00002996
Chandler Carruthdf5747a2015-01-21 11:38:17 +00002997 // We have now visited this block! If we've already been here, ignore it.
2998 if (!Visited.insert(BB).second)
2999 continue;
Chris Lattner960a5432007-03-03 02:04:50 +00003000
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003001 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003002 Instruction *Inst = &*BBI++;
Devang Patelaad34d82011-03-17 22:18:16 +00003003
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003004 // DCE instruction if trivially dead.
3005 if (isInstructionTriviallyDead(Inst, TLI)) {
3006 ++NumDeadInst;
3007 DEBUG(dbgs() << "IC: DCE: " << *Inst << '\n');
3008 Inst->eraseFromParent();
3009 continue;
3010 }
Jakub Staszakcfc46f82012-05-06 13:52:31 +00003011
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003012 // ConstantProp instruction if trivially constant.
David Majnemer7fddecc2015-06-17 20:52:32 +00003013 if (!Inst->use_empty() &&
3014 (Inst->getNumOperands() == 0 || isa<Constant>(Inst->getOperand(0))))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003015 if (Constant *C = ConstantFoldInstruction(Inst, DL, TLI)) {
3016 DEBUG(dbgs() << "IC: ConstFold to: " << *C << " from: "
3017 << *Inst << '\n');
3018 Inst->replaceAllUsesWith(C);
3019 ++NumConstProp;
David Majnemer522a9112016-07-22 04:54:44 +00003020 if (isInstructionTriviallyDead(Inst, TLI))
3021 Inst->eraseFromParent();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003022 continue;
3023 }
3024
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003025 // See if we can constant fold its operands.
Craig Topper36f2e0e2017-03-24 02:58:02 +00003026 for (Use &U : Inst->operands()) {
3027 if (!isa<ConstantVector>(U) && !isa<ConstantExpr>(U))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003028 continue;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003029
Craig Topper36f2e0e2017-03-24 02:58:02 +00003030 auto *C = cast<Constant>(U);
David Majnemerd536f232016-07-29 03:27:26 +00003031 Constant *&FoldRes = FoldedConstants[C];
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003032 if (!FoldRes)
David Majnemerd536f232016-07-29 03:27:26 +00003033 FoldRes = ConstantFoldConstant(C, DL, TLI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003034 if (!FoldRes)
David Majnemerd536f232016-07-29 03:27:26 +00003035 FoldRes = C;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003036
David Majnemerd536f232016-07-29 03:27:26 +00003037 if (FoldRes != C) {
Craig Topperdf73e7c2017-03-24 02:57:59 +00003038 DEBUG(dbgs() << "IC: ConstFold operand of: " << *Inst
3039 << "\n Old = " << *C
Craig Topperd92d2fc2017-03-20 16:31:14 +00003040 << "\n New = " << *FoldRes << '\n');
Craig Topper36f2e0e2017-03-24 02:58:02 +00003041 U = FoldRes;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003042 MadeIRChange = true;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003043 }
3044 }
3045
3046 InstrsForInstCombineWorklist.push_back(Inst);
3047 }
3048
3049 // Recursively visit successors. If this is a branch or switch on a
3050 // constant, only visit the reachable successor.
3051 TerminatorInst *TI = BB->getTerminator();
3052 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
3053 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
3054 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
3055 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
3056 Worklist.push_back(ReachableBB);
3057 continue;
3058 }
3059 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
3060 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
3061 // See if this is an explicit destination.
3062 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
3063 i != e; ++i)
3064 if (i.getCaseValue() == Cond) {
3065 BasicBlock *ReachableBB = i.getCaseSuccessor();
3066 Worklist.push_back(ReachableBB);
3067 continue;
3068 }
3069
3070 // Otherwise it is the default destination.
3071 Worklist.push_back(SI->getDefaultDest());
3072 continue;
3073 }
3074 }
3075
Pete Cooperebcd7482015-08-06 20:22:46 +00003076 for (BasicBlock *SuccBB : TI->successors())
3077 Worklist.push_back(SuccBB);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003078 } while (!Worklist.empty());
3079
3080 // Once we've found all of the instructions to add to instcombine's worklist,
3081 // add them in reverse order. This way instcombine will visit from the top
3082 // of the function down. This jives well with the way that it adds all uses
3083 // of instructions to the worklist after doing a transformation, thus avoiding
3084 // some N^2 behavior in pathological cases.
Craig Topper42526d32015-10-22 16:35:56 +00003085 ICWorklist.AddInitialGroup(InstrsForInstCombineWorklist);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003086
3087 return MadeIRChange;
3088}
3089
3090/// \brief Populate the IC worklist from a function, and prune any dead basic
3091/// blocks discovered in the process.
3092///
3093/// This also does basic constant propagation and other forward fixing to make
3094/// the combiner itself run much faster.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003095static bool prepareICWorklistFromFunction(Function &F, const DataLayout &DL,
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003096 TargetLibraryInfo *TLI,
3097 InstCombineWorklist &ICWorklist) {
3098 bool MadeIRChange = false;
3099
3100 // Do a depth-first traversal of the function, populate the worklist with
3101 // the reachable instructions. Ignore blocks that are not reachable. Keep
3102 // track of which blocks we visit.
Matthias Braunb30f2f512016-01-30 01:24:31 +00003103 SmallPtrSet<BasicBlock *, 32> Visited;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003104 MadeIRChange |=
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003105 AddReachableCodeToWorklist(&F.front(), DL, Visited, ICWorklist, TLI);
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003106
3107 // Do a quick scan over the function. If we find any blocks that are
3108 // unreachable, remove any instructions inside of them. This prevents
3109 // the instcombine code from having to deal with some bad special cases.
Benjamin Kramer135f7352016-06-26 12:28:59 +00003110 for (BasicBlock &BB : F) {
3111 if (Visited.count(&BB))
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003112 continue;
3113
Benjamin Kramer135f7352016-06-26 12:28:59 +00003114 unsigned NumDeadInstInBB = removeAllNonTerminatorAndEHPadInstructions(&BB);
David Majnemer35c46d32016-01-24 05:26:18 +00003115 MadeIRChange |= NumDeadInstInBB > 0;
3116 NumDeadInst += NumDeadInstInBB;
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003117 }
3118
3119 return MadeIRChange;
Chris Lattner960a5432007-03-03 02:04:50 +00003120}
3121
Mehdi Amini46a43552015-03-04 18:43:29 +00003122static bool
3123combineInstructionsOverFunction(Function &F, InstCombineWorklist &Worklist,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003124 AliasAnalysis *AA, AssumptionCache &AC,
3125 TargetLibraryInfo &TLI, DominatorTree &DT,
Matthias Braunc31032d2016-03-09 18:47:11 +00003126 bool ExpensiveCombines = true,
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003127 LoopInfo *LI = nullptr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003128 auto &DL = F.getParent()->getDataLayout();
Matthias Braunc31032d2016-03-09 18:47:11 +00003129 ExpensiveCombines |= EnableExpensiveCombines;
Chandler Carruth83ba2692015-01-24 04:19:17 +00003130
3131 /// Builder - This is an IRBuilder that automatically inserts new
3132 /// instructions into the worklist when they are created.
Justin Bogner19dd0da2016-08-04 23:41:01 +00003133 IRBuilder<TargetFolder, IRBuilderCallbackInserter> Builder(
3134 F.getContext(), TargetFolder(DL),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003135 IRBuilderCallbackInserter([&Worklist, &AC](Instruction *I) {
Justin Bogner19dd0da2016-08-04 23:41:01 +00003136 Worklist.Add(I);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003137
3138 using namespace llvm::PatternMatch;
3139 if (match(I, m_Intrinsic<Intrinsic::assume>()))
3140 AC.registerAssumption(cast<CallInst>(I));
Justin Bogner19dd0da2016-08-04 23:41:01 +00003141 }));
Chandler Carruth83ba2692015-01-24 04:19:17 +00003142
3143 // Lower dbg.declare intrinsics otherwise their value may be clobbered
3144 // by instcombiner.
3145 bool DbgDeclaresChanged = LowerDbgDeclare(F);
3146
3147 // Iterate while there is work to do.
3148 int Iteration = 0;
3149 for (;;) {
3150 ++Iteration;
3151 DEBUG(dbgs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
3152 << F.getName() << "\n");
3153
Sanjay Patel24b77d12016-01-31 16:33:33 +00003154 bool Changed = prepareICWorklistFromFunction(F, DL, &TLI, Worklist);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003155
Matthias Braunc31032d2016-03-09 18:47:11 +00003156 InstCombiner IC(Worklist, &Builder, F.optForMinSize(), ExpensiveCombines,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003157 AA, AC, TLI, DT, DL, LI);
Davide Italiano2133bf52017-02-07 17:56:50 +00003158 IC.MaxArraySizeForCombine = MaxArraySize;
Sanjay Patel24b77d12016-01-31 16:33:33 +00003159 Changed |= IC.run();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003160
3161 if (!Changed)
3162 break;
3163 }
3164
3165 return DbgDeclaresChanged || Iteration > 1;
3166}
3167
3168PreservedAnalyses InstCombinePass::run(Function &F,
Sean Silva36e0d012016-08-09 00:28:15 +00003169 FunctionAnalysisManager &AM) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003170 auto &AC = AM.getResult<AssumptionAnalysis>(F);
Chandler Carruthb47f8012016-03-11 11:05:24 +00003171 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
3172 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003173
Chandler Carruthb47f8012016-03-11 11:05:24 +00003174 auto *LI = AM.getCachedResult<LoopAnalysis>(F);
Chandler Carruth83ba2692015-01-24 04:19:17 +00003175
Bjorn Steinbrink83505342015-07-10 06:55:49 +00003176 // FIXME: The AliasAnalysis is not yet supported in the new pass manager
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003177 if (!combineInstructionsOverFunction(F, Worklist, nullptr, AC, TLI, DT,
Matthias Braunc31032d2016-03-09 18:47:11 +00003178 ExpensiveCombines, LI))
Chandler Carruth83ba2692015-01-24 04:19:17 +00003179 // No changes, all analyses are preserved.
3180 return PreservedAnalyses::all();
3181
3182 // Mark all the analyses that instcombine updates as preserved.
Chandler Carruth83ba2692015-01-24 04:19:17 +00003183 PreservedAnalyses PA;
Chandler Carruthca68a3e2017-01-15 06:32:49 +00003184 PA.preserveSet<CFGAnalyses>();
Chandler Carruth5edfd4d2017-01-14 23:25:22 +00003185 PA.preserve<AAManager>();
Chandler Carruth5edfd4d2017-01-14 23:25:22 +00003186 PA.preserve<GlobalsAA>();
Chandler Carruth83ba2692015-01-24 04:19:17 +00003187 return PA;
3188}
3189
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003190void InstructionCombiningPass::getAnalysisUsage(AnalysisUsage &AU) const {
3191 AU.setPreservesCFG();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003192 AU.addRequired<AAResultsWrapperPass>();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003193 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003194 AU.addRequired<TargetLibraryInfoWrapperPass>();
3195 AU.addRequired<DominatorTreeWrapperPass>();
3196 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthac072702016-02-19 03:12:14 +00003197 AU.addPreserved<AAResultsWrapperPass>();
3198 AU.addPreserved<BasicAAWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +00003199 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003200}
3201
3202bool InstructionCombiningPass::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +00003203 if (skipFunction(F))
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003204 return false;
3205
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003206 // Required analyses.
Chandler Carruth7b560d42015-09-09 17:55:00 +00003207 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003208 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003209 auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
3210 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthdf5747a2015-01-21 11:38:17 +00003211
3212 // Optional analyses.
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003213 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
3214 auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
3215
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003216 return combineInstructionsOverFunction(F, Worklist, AA, AC, TLI, DT,
Matthias Braunc31032d2016-03-09 18:47:11 +00003217 ExpensiveCombines, LI);
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003218}
3219
3220char InstructionCombiningPass::ID = 0;
3221INITIALIZE_PASS_BEGIN(InstructionCombiningPass, "instcombine",
3222 "Combine redundant instructions", false, false)
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003223INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003224INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3225INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +00003226INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
3227INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chandler Carruth1edb9d62015-01-20 22:44:35 +00003228INITIALIZE_PASS_END(InstructionCombiningPass, "instcombine",
3229 "Combine redundant instructions", false, false)
3230
3231// Initialization Routines
3232void llvm::initializeInstCombine(PassRegistry &Registry) {
3233 initializeInstructionCombiningPassPass(Registry);
3234}
3235
3236void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
3237 initializeInstructionCombiningPassPass(*unwrap(R));
3238}
3239
Matthias Braunc31032d2016-03-09 18:47:11 +00003240FunctionPass *llvm::createInstructionCombiningPass(bool ExpensiveCombines) {
3241 return new InstructionCombiningPass(ExpensiveCombines);
Chris Lattner04805fa2002-02-26 21:46:54 +00003242}