blob: e66c89b500bbc51e399f90fb3f03c4080dba8d0d [file] [log] [blame]
Chandler Carrutha9174582015-01-22 05:25:13 +00001//===- InstCombineInternal.h - InstCombine pass internals -------*- C++ -*-===//
Chris Lattner35522b72010-01-04 07:12:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chandler Carrutha9174582015-01-22 05:25:13 +00009/// \file
10///
11/// This file provides internal interfaces used to implement the InstCombine.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner35522b72010-01-04 07:12:23 +000014
Chandler Carrutha9174582015-01-22 05:25:13 +000015#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
Chris Lattner35522b72010-01-04 07:12:23 +000017
Bjorn Steinbrink83505342015-07-10 06:55:49 +000018#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000019#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth5175b9a2015-01-20 08:35:24 +000020#include "llvm/Analysis/LoopInfo.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000021#include "llvm/Analysis/TargetFolder.h"
Chandler Carruth802d7552012-12-04 07:12:27 +000022#include "llvm/Analysis/ValueTracking.h"
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +000023#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000025#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/IntrinsicInst.h"
27#include "llvm/IR/Operator.h"
Hal Finkel74c2f352014-09-07 12:44:26 +000028#include "llvm/IR/PatternMatch.h"
Chris Lattner35522b72010-01-04 07:12:23 +000029#include "llvm/Pass.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000030#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
Chris Lattner35522b72010-01-04 07:12:23 +000031
Chandler Carruth964daaa2014-04-22 02:55:47 +000032#define DEBUG_TYPE "instcombine"
33
Chris Lattner35522b72010-01-04 07:12:23 +000034namespace llvm {
Chandler Carruthd70cc602014-05-07 17:36:59 +000035class CallSite;
36class DataLayout;
Hal Finkel60db0582014-09-07 18:57:58 +000037class DominatorTree;
Chandler Carruthd70cc602014-05-07 17:36:59 +000038class TargetLibraryInfo;
39class DbgDeclareInst;
40class MemIntrinsic;
41class MemSetInst;
Jakub Staszak190db2f2013-01-14 23:16:36 +000042
Chandler Carruth3a622162015-01-20 19:27:58 +000043/// \brief Assign a complexity or rank value to LLVM Values.
44///
45/// This routine maps IR values to various complexity ranks:
46/// 0 -> undef
47/// 1 -> Constants
48/// 2 -> Other non-instructions
49/// 3 -> Arguments
50/// 3 -> Unary operations
51/// 4 -> Other instructions
Chris Lattner2188e402010-01-04 07:37:31 +000052static inline unsigned getComplexity(Value *V) {
53 if (isa<Instruction>(V)) {
Chandler Carruthd70cc602014-05-07 17:36:59 +000054 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
Chris Lattner2188e402010-01-04 07:37:31 +000055 BinaryOperator::isNot(V))
56 return 3;
57 return 4;
58 }
Chandler Carruthd70cc602014-05-07 17:36:59 +000059 if (isa<Argument>(V))
60 return 3;
Chris Lattner2188e402010-01-04 07:37:31 +000061 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
62}
Chris Lattner35522b72010-01-04 07:12:23 +000063
Chandler Carruth3a622162015-01-20 19:27:58 +000064/// \brief Add one to a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +000065static inline Constant *AddOne(Constant *C) {
66 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
67}
Chandler Carruth3a622162015-01-20 19:27:58 +000068/// \brief Subtract one from a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +000069static inline Constant *SubOne(Constant *C) {
70 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
71}
72
Sanjoy Das82ea3d42015-02-24 00:08:41 +000073/// \brief Return true if the specified value is free to invert (apply ~ to).
74/// This happens in cases where the ~ can be eliminated. If WillInvertAllUses
75/// is true, work under the assumption that the caller intends to remove all
76/// uses of V and only keep uses of ~V.
77///
78static inline bool IsFreeToInvert(Value *V, bool WillInvertAllUses) {
79 // ~(~(X)) -> X.
80 if (BinaryOperator::isNot(V))
81 return true;
82
83 // Constants can be considered to be not'ed values.
84 if (isa<ConstantInt>(V))
85 return true;
86
87 // Compares can be inverted if all of their uses are being modified to use the
88 // ~V.
89 if (isa<CmpInst>(V))
90 return WillInvertAllUses;
91
92 // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
93 // - Constant) - A` if we are willing to invert all of the uses.
94 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
95 if (BO->getOpcode() == Instruction::Add ||
96 BO->getOpcode() == Instruction::Sub)
97 if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
98 return WillInvertAllUses;
99
100 return false;
101}
102
Sanjoy Dasb0984472015-04-08 04:27:22 +0000103
104/// \brief Specific patterns of overflow check idioms that we match.
105enum OverflowCheckFlavor {
106 OCF_UNSIGNED_ADD,
107 OCF_SIGNED_ADD,
108 OCF_UNSIGNED_SUB,
109 OCF_SIGNED_SUB,
110 OCF_UNSIGNED_MUL,
111 OCF_SIGNED_MUL,
112
113 OCF_INVALID
114};
115
116/// \brief Returns the OverflowCheckFlavor corresponding to a overflow_with_op
117/// intrinsic.
118static inline OverflowCheckFlavor
119IntrinsicIDToOverflowCheckFlavor(unsigned ID) {
120 switch (ID) {
121 default:
122 return OCF_INVALID;
123 case Intrinsic::uadd_with_overflow:
124 return OCF_UNSIGNED_ADD;
125 case Intrinsic::sadd_with_overflow:
126 return OCF_SIGNED_ADD;
127 case Intrinsic::usub_with_overflow:
128 return OCF_UNSIGNED_SUB;
129 case Intrinsic::ssub_with_overflow:
130 return OCF_SIGNED_SUB;
131 case Intrinsic::umul_with_overflow:
132 return OCF_UNSIGNED_MUL;
133 case Intrinsic::smul_with_overflow:
134 return OCF_SIGNED_MUL;
135 }
136}
137
Chandler Carruth3a622162015-01-20 19:27:58 +0000138/// \brief An IRBuilder inserter that adds new instructions to the instcombine
139/// worklist.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000140class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000141 : public IRBuilderDefaultInserter {
Chris Lattner35522b72010-01-04 07:12:23 +0000142 InstCombineWorklist &Worklist;
Chandler Carruth66b31302015-01-04 12:03:27 +0000143 AssumptionCache *AC;
Chandler Carruthd70cc602014-05-07 17:36:59 +0000144
Chris Lattner35522b72010-01-04 07:12:23 +0000145public:
Chandler Carruth66b31302015-01-04 12:03:27 +0000146 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
147 : Worklist(WL), AC(AC) {}
Jakub Staszak190db2f2013-01-14 23:16:36 +0000148
Chandler Carruthd70cc602014-05-07 17:36:59 +0000149 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
150 BasicBlock::iterator InsertPt) const {
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000151 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
Chris Lattner35522b72010-01-04 07:12:23 +0000152 Worklist.Add(I);
Hal Finkel74c2f352014-09-07 12:44:26 +0000153
154 using namespace llvm::PatternMatch;
Benjamin Kramer63207bc2014-10-25 18:09:01 +0000155 if (match(I, m_Intrinsic<Intrinsic::assume>()))
Chandler Carruth66b31302015-01-04 12:03:27 +0000156 AC->registerAssumption(cast<CallInst>(I));
Chris Lattner35522b72010-01-04 07:12:23 +0000157 }
158};
Jakub Staszak190db2f2013-01-14 23:16:36 +0000159
Chandler Carruth3a622162015-01-20 19:27:58 +0000160/// \brief The core instruction combiner logic.
161///
162/// This class provides both the logic to recursively visit instructions and
163/// combine them, as well as the pass infrastructure for running this as part
164/// of the LLVM pass pipeline.
Duncan Sands6c5e4352010-05-11 20:16:09 +0000165class LLVM_LIBRARY_VISIBILITY InstCombiner
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000166 : public InstVisitor<InstCombiner, Instruction *> {
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000167 // FIXME: These members shouldn't be public.
Chris Lattner35522b72010-01-04 07:12:23 +0000168public:
Chandler Carruth3a622162015-01-20 19:27:58 +0000169 /// \brief A worklist of the instructions that need to be simplified.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000170 InstCombineWorklist &Worklist;
Chris Lattner35522b72010-01-04 07:12:23 +0000171
Chandler Carruth3a622162015-01-20 19:27:58 +0000172 /// \brief An IRBuilder that automatically inserts new instructions into the
173 /// worklist.
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000174 typedef IRBuilder<TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattner35522b72010-01-04 07:12:23 +0000175 BuilderTy *Builder;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000176
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000177private:
178 // Mode in which we are running the combiner.
179 const bool MinimizeSize;
Matthias Braunc31032d2016-03-09 18:47:11 +0000180 /// Enable combines that trigger rarely but are costly in compiletime.
181 const bool ExpensiveCombines;
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000182
Bjorn Steinbrink83505342015-07-10 06:55:49 +0000183 AliasAnalysis *AA;
184
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000185 // Required analyses.
186 // FIXME: These can never be null and should be references.
187 AssumptionCache *AC;
188 TargetLibraryInfo *TLI;
189 DominatorTree *DT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000190 const DataLayout &DL;
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000191
192 // Optional analyses. When non-null, these can both be used to do better
193 // combining and will be updated to reflect any changes.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000194 LoopInfo *LI;
195
196 bool MadeIRChange;
Chris Lattner35522b72010-01-04 07:12:23 +0000197
198public:
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000199 InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
Matthias Braunc31032d2016-03-09 18:47:11 +0000200 bool MinimizeSize, bool ExpensiveCombines, AliasAnalysis *AA,
Bjorn Steinbrink83505342015-07-10 06:55:49 +0000201 AssumptionCache *AC, TargetLibraryInfo *TLI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000202 DominatorTree *DT, const DataLayout &DL, LoopInfo *LI)
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000203 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
Matthias Braunc31032d2016-03-09 18:47:11 +0000204 ExpensiveCombines(ExpensiveCombines), AA(AA), AC(AC), TLI(TLI), DT(DT),
205 DL(DL), LI(LI), MadeIRChange(false) {}
Jakub Staszak190db2f2013-01-14 23:16:36 +0000206
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000207 /// \brief Run the combiner over the entire worklist until it is empty.
208 ///
209 /// \returns true if the IR is changed.
210 bool run();
Chris Lattner35522b72010-01-04 07:12:23 +0000211
Chandler Carruth66b31302015-01-04 12:03:27 +0000212 AssumptionCache *getAssumptionCache() const { return AC; }
Hal Finkel74c2f352014-09-07 12:44:26 +0000213
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000214 const DataLayout &getDataLayout() const { return DL; }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000215
Hal Finkel60db0582014-09-07 18:57:58 +0000216 DominatorTree *getDominatorTree() const { return DT; }
Chris Lattner35522b72010-01-04 07:12:23 +0000217
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000218 LoopInfo *getLoopInfo() const { return LI; }
219
Chad Rosier43a33062011-12-02 01:26:24 +0000220 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
221
Chris Lattner35522b72010-01-04 07:12:23 +0000222 // Visitation implementation - Implement instruction combining for different
223 // instruction types. The semantics are as follows:
224 // Return Value:
225 // null - No change was made
226 // I - Change was made, I is still valid, I may be dead though
227 // otherwise - Change was made, replace I with returned instruction
228 //
229 Instruction *visitAdd(BinaryOperator &I);
230 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner229907c2011-07-18 04:54:35 +0000231 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
Chris Lattner35522b72010-01-04 07:12:23 +0000232 Instruction *visitSub(BinaryOperator &I);
233 Instruction *visitFSub(BinaryOperator &I);
234 Instruction *visitMul(BinaryOperator &I);
Benjamin Kramer76b15d02014-01-19 13:36:27 +0000235 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
Shuxin Yangdf0e61e2013-01-07 21:39:23 +0000236 Instruction *InsertBefore);
Chris Lattner35522b72010-01-04 07:12:23 +0000237 Instruction *visitFMul(BinaryOperator &I);
238 Instruction *visitURem(BinaryOperator &I);
239 Instruction *visitSRem(BinaryOperator &I);
240 Instruction *visitFRem(BinaryOperator &I);
241 bool SimplifyDivRemOfSelect(BinaryOperator &I);
242 Instruction *commonRemTransforms(BinaryOperator &I);
243 Instruction *commonIRemTransforms(BinaryOperator &I);
244 Instruction *commonDivTransforms(BinaryOperator &I);
245 Instruction *commonIDivTransforms(BinaryOperator &I);
246 Instruction *visitUDiv(BinaryOperator &I);
247 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel2a559512011-01-29 17:50:27 +0000248 Instruction *visitFDiv(BinaryOperator &I);
Erik Ecksteind1817522014-12-03 10:39:15 +0000249 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
Chris Lattner067459c2010-03-05 08:46:26 +0000250 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
251 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner35522b72010-01-04 07:12:23 +0000252 Instruction *visitAnd(BinaryOperator &I);
Hal Finkel60db0582014-09-07 18:57:58 +0000253 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
Chris Lattner067459c2010-03-05 08:46:26 +0000254 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000255 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
256 Value *B, Value *C);
David Majnemer5d1aeba2014-08-21 05:14:48 +0000257 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
258 Value *B, Value *C);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000259 Instruction *visitOr(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000260 Instruction *visitXor(BinaryOperator &I);
261 Instruction *visitShl(BinaryOperator &I);
262 Instruction *visitAShr(BinaryOperator &I);
263 Instruction *visitLShr(BinaryOperator &I);
264 Instruction *commonShiftTransforms(BinaryOperator &I);
265 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
266 Constant *RHSC);
267 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
268 GlobalVariable *GV, CmpInst &ICI,
Craig Toppere73658d2014-04-28 04:05:08 +0000269 ConstantInt *AndCst = nullptr);
Chris Lattner35522b72010-01-04 07:12:23 +0000270 Instruction *visitFCmpInst(FCmpInst &I);
271 Instruction *visitICmpInst(ICmpInst &I);
272 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000273 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
Chris Lattner35522b72010-01-04 07:12:23 +0000274 ConstantInt *RHS);
275 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
276 ConstantInt *DivRHS);
Chris Lattnerd369f572011-02-13 07:43:07 +0000277 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
278 ConstantInt *DivRHS);
Suyog Sarda3a8c2c12014-07-22 19:19:36 +0000279 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
280 ConstantInt *CI1, ConstantInt *CI2);
David Majnemer59939ac2014-10-19 08:23:08 +0000281 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
282 ConstantInt *CI1, ConstantInt *CI2);
Benjamin Kramer0e2d1622013-09-20 22:12:42 +0000283 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
284 ICmpInst::Predicate Pred);
Chris Lattner35522b72010-01-04 07:12:23 +0000285 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
286 ICmpInst::Predicate Cond, Instruction &I);
Hans Wennborgf1f36512015-10-07 00:20:07 +0000287 Instruction *FoldAllocaCmp(ICmpInst &ICI, AllocaInst *Alloca, Value *Other);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000288 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattner35522b72010-01-04 07:12:23 +0000289 BinaryOperator &I);
290 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000291 Instruction *commonPointerCastTransforms(CastInst &CI);
292 Instruction *visitTrunc(TruncInst &CI);
293 Instruction *visitZExt(ZExtInst &CI);
294 Instruction *visitSExt(SExtInst &CI);
295 Instruction *visitFPTrunc(FPTruncInst &CI);
296 Instruction *visitFPExt(CastInst &CI);
297 Instruction *visitFPToUI(FPToUIInst &FI);
298 Instruction *visitFPToSI(FPToSIInst &FI);
299 Instruction *visitUIToFP(CastInst &CI);
300 Instruction *visitSIToFP(CastInst &CI);
301 Instruction *visitPtrToInt(PtrToIntInst &CI);
302 Instruction *visitIntToPtr(IntToPtrInst &CI);
303 Instruction *visitBitCast(BitCastInst &CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +0000304 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000305 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
306 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
Chris Lattner35522b72010-01-04 07:12:23 +0000307 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
308 Value *A, Value *B, Instruction &Outer,
309 SelectPatternFlavor SPF2, Value *C);
Mehdi Aminib9a0fa42015-02-16 21:47:54 +0000310 Instruction *FoldItoFPtoI(Instruction &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000311 Instruction *visitSelectInst(SelectInst &SI);
312 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
313 Instruction *visitCallInst(CallInst &CI);
314 Instruction *visitInvokeInst(InvokeInst &II);
315
316 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
317 Instruction *visitPHINode(PHINode &PN);
318 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
319 Instruction *visitAllocaInst(AllocaInst &AI);
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000320 Instruction *visitAllocSite(Instruction &FI);
Gabor Greif75f69432010-06-24 12:21:15 +0000321 Instruction *visitFree(CallInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000322 Instruction *visitLoadInst(LoadInst &LI);
323 Instruction *visitStoreInst(StoreInst &SI);
324 Instruction *visitBranchInst(BranchInst &BI);
325 Instruction *visitSwitchInst(SwitchInst &SI);
Hal Finkel93873cc12014-09-07 21:28:34 +0000326 Instruction *visitReturnInst(ReturnInst &RI);
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000327 Instruction *visitInsertValueInst(InsertValueInst &IV);
Chris Lattner35522b72010-01-04 07:12:23 +0000328 Instruction *visitInsertElementInst(InsertElementInst &IE);
329 Instruction *visitExtractElementInst(ExtractElementInst &EI);
330 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
331 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Duncan Sands5c055792011-09-30 13:12:16 +0000332 Instruction *visitLandingPadInst(LandingPadInst &LI);
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +0000333 Instruction *visitVAStartInst(VAStartInst &I);
334 Instruction *visitVACopyInst(VACopyInst &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000335
336 // visitInstruction - Specify what to return for unhandled instructions...
Craig Toppere73658d2014-04-28 04:05:08 +0000337 Instruction *visitInstruction(Instruction &I) { return nullptr; }
Chris Lattner35522b72010-01-04 07:12:23 +0000338
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +0000339 // True when DB dominates all uses of DI execpt UI.
340 // UI must be in the same block as DI.
341 // The routine checks that the DI parent and DB are different.
342 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
343 const BasicBlock *DB) const;
344
345 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
346 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
347 const unsigned SIOpd);
348
Chris Lattner35522b72010-01-04 07:12:23 +0000349private:
Sanjay Patel55dcd402015-09-21 16:09:37 +0000350 bool ShouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
Chris Lattner229907c2011-07-18 04:54:35 +0000351 bool ShouldChangeType(Type *From, Type *To) const;
Chris Lattner2188e402010-01-04 07:37:31 +0000352 Value *dyn_castNegVal(Value *V) const;
Chandler Carruthd70cc602014-05-07 17:36:59 +0000353 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
David Blaikie87ca1b62015-03-27 20:56:11 +0000354 Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000355 SmallVectorImpl<Value *> &NewIndices);
Chris Lattner2b295a02010-01-04 07:53:58 +0000356 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000357
Chandler Carruth3a622162015-01-20 19:27:58 +0000358 /// \brief Classify whether a cast is worth optimizing.
359 ///
360 /// Returns true if the cast from "V to Ty" actually results in any code
361 /// being generated and is interesting to optimize out. If the cast can be
362 /// eliminated by some other simple transformation, we prefer to do the
363 /// simplification first.
Chandler Carruthd70cc602014-05-07 17:36:59 +0000364 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
Chris Lattner229907c2011-07-18 04:54:35 +0000365 Type *Ty);
Chris Lattner2188e402010-01-04 07:37:31 +0000366
Sanjoy Dasb0984472015-04-08 04:27:22 +0000367 /// \brief Try to optimize a sequence of instructions checking if an operation
368 /// on LHS and RHS overflows.
369 ///
Sanjoy Das6f5dca72015-08-28 19:09:31 +0000370 /// If this overflow check is done via one of the overflow check intrinsics,
371 /// then CtxI has to be the call instruction calling that intrinsic. If this
372 /// overflow check is done by arithmetic followed by a compare, then CtxI has
373 /// to be the arithmetic instruction.
374 ///
Sanjoy Dasb0984472015-04-08 04:27:22 +0000375 /// If a simplification is possible, stores the simplified result of the
376 /// operation in OperationResult and result of the overflow check in
377 /// OverflowResult, and return true. If no simplification is possible,
378 /// returns false.
379 bool OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, Value *RHS,
380 Instruction &CtxI, Value *&OperationResult,
381 Constant *&OverflowResult);
382
Chris Lattner35522b72010-01-04 07:12:23 +0000383 Instruction *visitCallSite(CallSite CS);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000384 Instruction *tryOptimizeCall(CallInst *CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000385 bool transformConstExprCastCall(CallSite CS);
Duncan Sandsa0984362011-09-06 13:37:06 +0000386 Instruction *transformCallThroughTrampoline(CallSite CS,
387 IntrinsicInst *Tramp);
Chris Lattner35522b72010-01-04 07:12:23 +0000388 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
389 bool DoXform = true);
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000390 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000391 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction &CxtI);
392 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
393 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
394 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction &CxtI);
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000395 Value *EmitGEPOffset(User *GEP);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000396 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000397 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
Sanjay Patel40e7ba02016-02-23 16:36:07 +0000398 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
Guozhi Wei7b390ec2016-03-17 18:47:20 +0000399 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000400
401public:
Chandler Carruth3a622162015-01-20 19:27:58 +0000402 /// \brief Inserts an instruction \p New before instruction \p Old
403 ///
404 /// Also adds the new instruction to the worklist and returns \p New so that
405 /// it is suitable for use as the return from the visitation patterns.
Chris Lattner35522b72010-01-04 07:12:23 +0000406 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Craig Toppere73658d2014-04-28 04:05:08 +0000407 assert(New && !New->getParent() &&
Chris Lattner35522b72010-01-04 07:12:23 +0000408 "New instruction already inserted into a basic block!");
409 BasicBlock *BB = Old.getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000410 BB->getInstList().insert(Old.getIterator(), New); // Insert inst
Chris Lattner35522b72010-01-04 07:12:23 +0000411 Worklist.Add(New);
412 return New;
413 }
Eli Friedman6efb64e2011-05-19 01:20:42 +0000414
Chandler Carruth3a622162015-01-20 19:27:58 +0000415 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
Eli Friedman6efb64e2011-05-19 01:20:42 +0000416 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
417 New->setDebugLoc(Old.getDebugLoc());
418 return InsertNewInstBefore(New, Old);
419 }
420
Chandler Carruth3a622162015-01-20 19:27:58 +0000421 /// \brief A combiner-aware RAUW-like routine.
422 ///
423 /// This method is to be used when an instruction is found to be dead,
Sanjay Patelf2ea8a22016-01-06 00:23:12 +0000424 /// replaceable with another preexisting expression. Here we add all uses of
Chandler Carruth3a622162015-01-20 19:27:58 +0000425 /// I to the worklist, replace all uses of I with the new value, then return
426 /// I, so that the inst combiner will know that I was modified.
Sanjay Patel4b198802016-02-01 22:23:39 +0000427 Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
Owen Anderson51b75b8c2015-03-10 05:13:47 +0000428 // If there are no uses to replace, then we return nullptr to indicate that
429 // no changes were made to the program.
430 if (I.use_empty()) return nullptr;
431
Chandler Carruthd70cc602014-05-07 17:36:59 +0000432 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000433
Chris Lattner35522b72010-01-04 07:12:23 +0000434 // If we are replacing the instruction with itself, this must be in a
435 // segment of unreachable code, so just clobber the instruction.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000436 if (&I == V)
Chris Lattner35522b72010-01-04 07:12:23 +0000437 V = UndefValue::get(I.getType());
Frits van Bommeld14d9912011-03-27 23:32:31 +0000438
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000439 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000440 << " with " << *V << '\n');
Frits van Bommeld14d9912011-03-27 23:32:31 +0000441
Chris Lattner35522b72010-01-04 07:12:23 +0000442 I.replaceAllUsesWith(V);
443 return &I;
444 }
445
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000446 /// Creates a result tuple for an overflow intrinsic \p II with a given
Sanjoy Dasb0984472015-04-08 04:27:22 +0000447 /// \p Result and a constant \p Overflow value.
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000448 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
Sanjoy Dasb0984472015-04-08 04:27:22 +0000449 Constant *Overflow) {
450 Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000451 StructType *ST = cast<StructType>(II->getType());
452 Constant *Struct = ConstantStruct::get(ST, V);
453 return InsertValueInst::Create(Struct, Result, 0);
454 }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000455
Chandler Carruth3a622162015-01-20 19:27:58 +0000456 /// \brief Combiner aware instruction erasure.
457 ///
458 /// When dealing with an instruction that has side effects or produces a void
459 /// value, we can't rely on DCE to delete the instruction. Instead, visit
460 /// methods should return the value returned by this function.
Sanjay Patel4b198802016-02-01 22:23:39 +0000461 Instruction *eraseInstFromFunction(Instruction &I) {
Matt Arsenaulte6db7602013-09-05 19:48:28 +0000462 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
Chris Lattner35522b72010-01-04 07:12:23 +0000463
464 assert(I.use_empty() && "Cannot erase instruction that is used!");
465 // Make sure that we reprocess all operands now that we reduced their
466 // use counts.
467 if (I.getNumOperands() < 8) {
Sanjay Patel8af7fbc32016-01-31 16:34:48 +0000468 for (Use &Operand : I.operands())
469 if (auto *Inst = dyn_cast<Instruction>(Operand))
470 Worklist.Add(Inst);
Chris Lattner35522b72010-01-04 07:12:23 +0000471 }
472 Worklist.Remove(&I);
473 I.eraseFromParent();
474 MadeIRChange = true;
Chandler Carruthd70cc602014-05-07 17:36:59 +0000475 return nullptr; // Don't do anything with FI
Chris Lattner35522b72010-01-04 07:12:23 +0000476 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000477
Jay Foada0653a32014-05-14 21:14:37 +0000478 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 unsigned Depth, Instruction *CxtI) const {
Chandler Carruth66b31302015-01-04 12:03:27 +0000480 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
481 DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000482 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000483
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000484 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
Hal Finkel60db0582014-09-07 18:57:58 +0000485 Instruction *CxtI = nullptr) const {
Chandler Carruth66b31302015-01-04 12:03:27 +0000486 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000487 }
Hal Finkel60db0582014-09-07 18:57:58 +0000488 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
489 Instruction *CxtI = nullptr) const {
Chandler Carruth66b31302015-01-04 12:03:27 +0000490 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000491 }
David Majnemer54c2ca22014-12-26 09:10:14 +0000492 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
493 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
Chandler Carruth66b31302015-01-04 12:03:27 +0000494 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
David Majnemer54c2ca22014-12-26 09:10:14 +0000495 DT);
496 }
David Majnemer491331a2015-01-02 07:29:43 +0000497 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
498 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000499 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
David Majnemer491331a2015-01-02 07:29:43 +0000500 }
David Majnemer5310c1e2015-01-07 00:39:50 +0000501 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
502 const Instruction *CxtI) {
503 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
504 }
Chris Lattner35522b72010-01-04 07:12:23 +0000505
506private:
Chandler Carruth3a622162015-01-20 19:27:58 +0000507 /// \brief Performs a few simplifications for operators which are associative
508 /// or commutative.
Duncan Sands641baf12010-11-13 15:10:37 +0000509 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000510
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000511 /// \brief Tries to simplify binary operations which some other binary
512 /// operation distributes over.
Chandler Carruth3a622162015-01-20 19:27:58 +0000513 ///
514 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
515 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
516 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
517 /// value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000518 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000519
Chandler Carruth3a622162015-01-20 19:27:58 +0000520 /// \brief Attempts to replace V with a simpler value based on the demanded
521 /// bits.
Chandler Carruthd70cc602014-05-07 17:36:59 +0000522 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
Hal Finkel60db0582014-09-07 18:57:58 +0000523 APInt &KnownOne, unsigned Depth,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000524 Instruction *CxtI);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000525 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
526 APInt &KnownOne, unsigned Depth = 0);
Shuxin Yang63e999e2012-12-04 00:04:54 +0000527 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
528 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
529 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
530 APInt DemandedMask, APInt &KnownZero,
531 APInt &KnownOne);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000532
Chandler Carruth3a622162015-01-20 19:27:58 +0000533 /// \brief Tries to simplify operands to an integer instruction based on its
534 /// demanded bits.
Chris Lattner35522b72010-01-04 07:12:23 +0000535 bool SimplifyDemandedInstructionBits(Instruction &Inst);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000536
Chris Lattner35522b72010-01-04 07:12:23 +0000537 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000538 APInt &UndefElts, unsigned Depth = 0);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000539
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000540 Value *SimplifyVectorOp(BinaryOperator &Inst);
Simon Pilgrimbe24ab32014-12-04 09:44:01 +0000541 Value *SimplifyBSwap(BinaryOperator &Inst);
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000542
Chris Lattner35522b72010-01-04 07:12:23 +0000543 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
544 // which has a PHI node as operand #0, see if we can fold the instruction
545 // into the PHI (which is only possible if all operands to the PHI are
546 // constants).
547 //
Chris Lattnerea7131a2011-01-16 05:14:26 +0000548 Instruction *FoldOpIntoPhi(Instruction &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000549
Chandler Carruth3a622162015-01-20 19:27:58 +0000550 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
551 /// its operands.
Chris Lattner35522b72010-01-04 07:12:23 +0000552 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
553 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
554 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
555 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Sanjay Patel95334072015-09-27 20:34:31 +0000556 Instruction *FoldPHIArgZextsIntoPHI(PHINode &PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000557
Chris Lattner35522b72010-01-04 07:12:23 +0000558 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
559 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000560
Chris Lattner35522b72010-01-04 07:12:23 +0000561 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
562 bool isSub, Instruction &I);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000563 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
564 bool Inside);
Chris Lattner35522b72010-01-04 07:12:23 +0000565 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
James Molloy37b82e72015-12-11 10:04:51 +0000566 Instruction *MatchBSwapOrBitReverse(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000567 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000568 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner35522b72010-01-04 07:12:23 +0000569 Instruction *SimplifyMemSet(MemSetInst *MI);
570
Chris Lattner229907c2011-07-18 04:54:35 +0000571 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
Duncan Sands533c8ae2012-10-23 08:28:26 +0000572
Chandler Carruth3a622162015-01-20 19:27:58 +0000573 /// \brief Returns a value X such that Val = X * Scale, or null if none.
574 ///
575 /// If the multiplication is known not to overflow then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +0000576 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
Chris Lattner35522b72010-01-04 07:12:23 +0000577};
578
Chris Lattner35522b72010-01-04 07:12:23 +0000579} // end namespace llvm.
580
Chandler Carruth964daaa2014-04-22 02:55:47 +0000581#undef DEBUG_TYPE
582
Chris Lattner35522b72010-01-04 07:12:23 +0000583#endif