blob: 07e2122545016692022605554cc2ee4e20deed36 [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//===----------------------------------------------------------------------===//
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00009//
Chandler Carrutha9174582015-01-22 05:25:13 +000010/// \file
11///
12/// This file provides internal interfaces used to implement the InstCombine.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000013//
Chandler Carrutha9174582015-01-22 05:25:13 +000014//===----------------------------------------------------------------------===//
Chris Lattner35522b72010-01-04 07:12:23 +000015
Chandler Carrutha9174582015-01-22 05:25:13 +000016#ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
17#define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
Chris Lattner35522b72010-01-04 07:12:23 +000018
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/ArrayRef.h"
Bjorn Steinbrink83505342015-07-10 06:55:49 +000020#include "llvm/Analysis/AliasAnalysis.h"
Daniel Berlin2c75c632017-04-26 20:56:07 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruth452a0072014-03-04 11:59:06 +000022#include "llvm/Analysis/TargetFolder.h"
Chandler Carruth802d7552012-12-04 07:12:27 +000023#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000024#include "llvm/IR/Argument.h"
25#include "llvm/IR/BasicBlock.h"
26#include "llvm/IR/Constant.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DerivedTypes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/IRBuilder.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000030#include "llvm/IR/InstVisitor.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000031#include "llvm/IR/InstrTypes.h"
32#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000034#include "llvm/IR/Intrinsics.h"
David Green1e44c3b2018-10-02 09:48:34 +000035#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000036#include "llvm/IR/Use.h"
37#include "llvm/IR/Value.h"
38#include "llvm/Support/Casting.h"
39#include "llvm/Support/Compiler.h"
40#include "llvm/Support/Debug.h"
Craig Topper1a36b7d2017-05-15 06:39:41 +000041#include "llvm/Support/KnownBits.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruth83ba2692015-01-24 04:19:17 +000043#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
David Green1e44c3b2018-10-02 09:48:34 +000044#include "llvm/Transforms/Utils/Local.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000045#include <cassert>
46#include <cstdint>
Chris Lattner35522b72010-01-04 07:12:23 +000047
Chandler Carruth964daaa2014-04-22 02:55:47 +000048#define DEBUG_TYPE "instcombine"
49
David Green1e44c3b2018-10-02 09:48:34 +000050using namespace llvm::PatternMatch;
51
Chris Lattner35522b72010-01-04 07:12:23 +000052namespace llvm {
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000053
54class APInt;
55class AssumptionCache;
Chandler Carruthd70cc602014-05-07 17:36:59 +000056class CallSite;
57class DataLayout;
Hal Finkel60db0582014-09-07 18:57:58 +000058class DominatorTree;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000059class GEPOperator;
60class GlobalVariable;
61class LoopInfo;
Adam Nemetea06e6e2017-07-26 19:03:18 +000062class OptimizationRemarkEmitter;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000063class TargetLibraryInfo;
64class User;
Jakub Staszak190db2f2013-01-14 23:16:36 +000065
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000066/// Assign a complexity or rank value to LLVM Values. This is used to reduce
67/// the amount of pattern matching needed for compares and commutative
68/// instructions. For example, if we have:
69/// icmp ugt X, Constant
70/// or
71/// xor (add X, Constant), cast Z
72///
73/// We do not have to consider the commuted variants of these patterns because
74/// canonicalization based on complexity guarantees the above ordering.
Chandler Carruth3a622162015-01-20 19:27:58 +000075///
76/// This routine maps IR values to various complexity ranks:
77/// 0 -> undef
78/// 1 -> Constants
79/// 2 -> Other non-instructions
80/// 3 -> Arguments
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000081/// 4 -> Cast and (f)neg/not instructions
82/// 5 -> Other instructions
Chris Lattner2188e402010-01-04 07:37:31 +000083static inline unsigned getComplexity(Value *V) {
84 if (isa<Instruction>(V)) {
Sanjay Patel47579b22018-10-13 16:15:37 +000085 if (isa<CastInst>(V) || match(V, m_Neg(m_Value())) ||
86 match(V, m_Not(m_Value())) || match(V, m_FNeg(m_Value())))
Sanjay Patel73fc8dd2017-02-03 21:43:34 +000087 return 4;
88 return 5;
Chris Lattner2188e402010-01-04 07:37:31 +000089 }
Chandler Carruthd70cc602014-05-07 17:36:59 +000090 if (isa<Argument>(V))
91 return 3;
Chris Lattner2188e402010-01-04 07:37:31 +000092 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
93}
Chris Lattner35522b72010-01-04 07:12:23 +000094
Sanjay Patelb2e70032017-05-17 14:21:19 +000095/// Predicate canonicalization reduces the number of patterns that need to be
96/// matched by other transforms. For example, we may swap the operands of a
97/// conditional branch or select to create a compare with a canonical (inverted)
98/// predicate which is then more likely to be matched with other values.
99static inline bool isCanonicalPredicate(CmpInst::Predicate Pred) {
100 switch (Pred) {
101 case CmpInst::ICMP_NE:
102 case CmpInst::ICMP_ULE:
103 case CmpInst::ICMP_SLE:
104 case CmpInst::ICMP_UGE:
105 case CmpInst::ICMP_SGE:
106 // TODO: There are 16 FCMP predicates. Should others be (not) canonical?
107 case CmpInst::FCMP_ONE:
108 case CmpInst::FCMP_OLE:
109 case CmpInst::FCMP_OGE:
110 return false;
111 default:
112 return true;
113 }
114}
115
Sanjay Patele800df8e2017-06-22 15:28:01 +0000116/// Return the source operand of a potentially bitcasted value while optionally
117/// checking if it has one use. If there is no bitcast or the one use check is
118/// not met, return the input value itself.
119static inline Value *peekThroughBitcast(Value *V, bool OneUseOnly = false) {
120 if (auto *BitCast = dyn_cast<BitCastInst>(V))
121 if (!OneUseOnly || BitCast->hasOneUse())
122 return BitCast->getOperand(0);
123
124 // V is not a bitcast or V has more than one use and OneUseOnly is true.
125 return V;
126}
127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000128/// Add one to a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +0000129static inline Constant *AddOne(Constant *C) {
130 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
131}
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000132
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000133/// Subtract one from a Constant
Benjamin Kramer970f4952014-01-19 16:56:10 +0000134static inline Constant *SubOne(Constant *C) {
135 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
136}
137
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000138/// Return true if the specified value is free to invert (apply ~ to).
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000139/// This happens in cases where the ~ can be eliminated. If WillInvertAllUses
140/// is true, work under the assumption that the caller intends to remove all
141/// uses of V and only keep uses of ~V.
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000142static inline bool IsFreeToInvert(Value *V, bool WillInvertAllUses) {
143 // ~(~(X)) -> X.
Sanjay Patel95790c52018-10-23 16:54:28 +0000144 if (match(V, m_Not(m_Value())))
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000145 return true;
146
147 // Constants can be considered to be not'ed values.
148 if (isa<ConstantInt>(V))
149 return true;
150
Sanjay Patel611f9f92016-10-27 17:30:50 +0000151 // A vector of constant integers can be inverted easily.
Craig Topperbcf511c2017-06-30 21:09:34 +0000152 if (V->getType()->isVectorTy() && isa<Constant>(V)) {
Sanjay Patel611f9f92016-10-27 17:30:50 +0000153 unsigned NumElts = V->getType()->getVectorNumElements();
154 for (unsigned i = 0; i != NumElts; ++i) {
Craig Topperbcf511c2017-06-30 21:09:34 +0000155 Constant *Elt = cast<Constant>(V)->getAggregateElement(i);
Sanjay Patel611f9f92016-10-27 17:30:50 +0000156 if (!Elt)
157 return false;
158
159 if (isa<UndefValue>(Elt))
160 continue;
161
162 if (!isa<ConstantInt>(Elt))
163 return false;
164 }
165 return true;
166 }
167
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000168 // Compares can be inverted if all of their uses are being modified to use the
169 // ~V.
170 if (isa<CmpInst>(V))
171 return WillInvertAllUses;
172
173 // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
174 // - Constant) - A` if we are willing to invert all of the uses.
175 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
176 if (BO->getOpcode() == Instruction::Add ||
177 BO->getOpcode() == Instruction::Sub)
178 if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
179 return WillInvertAllUses;
180
David Green1e44c3b2018-10-02 09:48:34 +0000181 // Selects with invertible operands are freely invertible
182 if (match(V, m_Select(m_Value(), m_Not(m_Value()), m_Not(m_Value()))))
183 return WillInvertAllUses;
184
Sanjoy Das82ea3d42015-02-24 00:08:41 +0000185 return false;
186}
187
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000188/// Specific patterns of overflow check idioms that we match.
Sanjoy Dasb0984472015-04-08 04:27:22 +0000189enum OverflowCheckFlavor {
190 OCF_UNSIGNED_ADD,
191 OCF_SIGNED_ADD,
192 OCF_UNSIGNED_SUB,
193 OCF_SIGNED_SUB,
194 OCF_UNSIGNED_MUL,
195 OCF_SIGNED_MUL,
196
197 OCF_INVALID
198};
199
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000200/// Returns the OverflowCheckFlavor corresponding to a overflow_with_op
Sanjoy Dasb0984472015-04-08 04:27:22 +0000201/// intrinsic.
202static inline OverflowCheckFlavor
203IntrinsicIDToOverflowCheckFlavor(unsigned ID) {
204 switch (ID) {
205 default:
206 return OCF_INVALID;
207 case Intrinsic::uadd_with_overflow:
208 return OCF_UNSIGNED_ADD;
209 case Intrinsic::sadd_with_overflow:
210 return OCF_SIGNED_ADD;
211 case Intrinsic::usub_with_overflow:
212 return OCF_UNSIGNED_SUB;
213 case Intrinsic::ssub_with_overflow:
214 return OCF_SIGNED_SUB;
215 case Intrinsic::umul_with_overflow:
216 return OCF_UNSIGNED_MUL;
217 case Intrinsic::smul_with_overflow:
218 return OCF_SIGNED_MUL;
219 }
220}
221
Sanjay Patela6272532018-07-09 16:16:51 +0000222/// Some binary operators require special handling to avoid poison and undefined
Sanjay Patel3e5c0512018-06-21 14:59:35 +0000223/// behavior. If a constant vector has undef elements, replace those undefs with
Sanjay Patel69faf4642018-07-09 23:22:47 +0000224/// identity constants if possible because those are always safe to execute.
225/// If no identity constant exists, replace undef with some other safe constant.
Sanjay Patela6272532018-07-09 16:16:51 +0000226static inline Constant *getSafeVectorConstantForBinop(
Sanjay Patel69faf4642018-07-09 23:22:47 +0000227 BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant) {
228 assert(In->getType()->isVectorTy() && "Not expecting scalars here");
Sanjay Patel3e5c0512018-06-21 14:59:35 +0000229
Sanjay Patel69faf4642018-07-09 23:22:47 +0000230 Type *EltTy = In->getType()->getVectorElementType();
231 auto *SafeC = ConstantExpr::getBinOpIdentity(Opcode, EltTy, IsRHSConstant);
232 if (!SafeC) {
233 // TODO: Should this be available as a constant utility function? It is
234 // similar to getBinOpAbsorber().
235 if (IsRHSConstant) {
236 switch (Opcode) {
237 case Instruction::SRem: // X % 1 = 0
238 case Instruction::URem: // X %u 1 = 0
239 SafeC = ConstantInt::get(EltTy, 1);
240 break;
241 case Instruction::FRem: // X % 1.0 (doesn't simplify, but it is safe)
242 SafeC = ConstantFP::get(EltTy, 1.0);
243 break;
244 default:
245 llvm_unreachable("Only rem opcodes have no identity constant for RHS");
246 }
247 } else {
248 switch (Opcode) {
249 case Instruction::Shl: // 0 << X = 0
250 case Instruction::LShr: // 0 >>u X = 0
251 case Instruction::AShr: // 0 >> X = 0
252 case Instruction::SDiv: // 0 / X = 0
253 case Instruction::UDiv: // 0 /u X = 0
254 case Instruction::SRem: // 0 % X = 0
255 case Instruction::URem: // 0 %u X = 0
256 case Instruction::Sub: // 0 - X (doesn't simplify, but it is safe)
257 case Instruction::FSub: // 0.0 - X (doesn't simplify, but it is safe)
258 case Instruction::FDiv: // 0.0 / X (doesn't simplify, but it is safe)
259 case Instruction::FRem: // 0.0 % X = 0
260 SafeC = Constant::getNullValue(EltTy);
261 break;
262 default:
263 llvm_unreachable("Expected to find identity constant for opcode");
264 }
265 }
266 }
267 assert(SafeC && "Must have safe constant for binop");
268 unsigned NumElts = In->getType()->getVectorNumElements();
Sanjay Patel3e5c0512018-06-21 14:59:35 +0000269 SmallVector<Constant *, 16> Out(NumElts);
270 for (unsigned i = 0; i != NumElts; ++i) {
271 Constant *C = In->getAggregateElement(i);
Sanjay Patel69faf4642018-07-09 23:22:47 +0000272 Out[i] = isa<UndefValue>(C) ? SafeC : C;
Sanjay Patel3e5c0512018-06-21 14:59:35 +0000273 }
274 return ConstantVector::get(Out);
275}
276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277/// The core instruction combiner logic.
Chandler Carruth3a622162015-01-20 19:27:58 +0000278///
279/// This class provides both the logic to recursively visit instructions and
Craig Topper28ec3462016-12-28 03:12:42 +0000280/// combine them.
Duncan Sands6c5e4352010-05-11 20:16:09 +0000281class LLVM_LIBRARY_VISIBILITY InstCombiner
Chandler Carruth1edb9d62015-01-20 22:44:35 +0000282 : public InstVisitor<InstCombiner, Instruction *> {
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000283 // FIXME: These members shouldn't be public.
Chris Lattner35522b72010-01-04 07:12:23 +0000284public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285 /// A worklist of the instructions that need to be simplified.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000286 InstCombineWorklist &Worklist;
Chris Lattner35522b72010-01-04 07:12:23 +0000287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000288 /// An IRBuilder that automatically inserts new instructions into the
Chandler Carruth3a622162015-01-20 19:27:58 +0000289 /// worklist.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000290 using BuilderTy = IRBuilder<TargetFolder, IRBuilderCallbackInserter>;
Craig Topperbb4069e2017-07-07 23:16:26 +0000291 BuilderTy &Builder;
Jakub Staszak190db2f2013-01-14 23:16:36 +0000292
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000293private:
294 // Mode in which we are running the combiner.
295 const bool MinimizeSize;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000296
Matthias Braunc31032d2016-03-09 18:47:11 +0000297 /// Enable combines that trigger rarely but are costly in compiletime.
298 const bool ExpensiveCombines;
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000299
Bjorn Steinbrink83505342015-07-10 06:55:49 +0000300 AliasAnalysis *AA;
301
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000302 // Required analyses.
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000303 AssumptionCache &AC;
Justin Bogner99798402016-08-05 01:06:44 +0000304 TargetLibraryInfo &TLI;
305 DominatorTree &DT;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 const DataLayout &DL;
Daniel Berlin2c75c632017-04-26 20:56:07 +0000307 const SimplifyQuery SQ;
Adam Nemetea06e6e2017-07-26 19:03:18 +0000308 OptimizationRemarkEmitter &ORE;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000309
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000310 // Optional analyses. When non-null, these can both be used to do better
311 // combining and will be updated to reflect any changes.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000312 LoopInfo *LI;
313
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000314 bool MadeIRChange = false;
Chris Lattner35522b72010-01-04 07:12:23 +0000315
316public:
Craig Topperbb4069e2017-07-07 23:16:26 +0000317 InstCombiner(InstCombineWorklist &Worklist, BuilderTy &Builder,
Matthias Braunc31032d2016-03-09 18:47:11 +0000318 bool MinimizeSize, bool ExpensiveCombines, AliasAnalysis *AA,
Daniel Berlin2c75c632017-04-26 20:56:07 +0000319 AssumptionCache &AC, TargetLibraryInfo &TLI, DominatorTree &DT,
Adam Nemetea06e6e2017-07-26 19:03:18 +0000320 OptimizationRemarkEmitter &ORE, const DataLayout &DL,
321 LoopInfo *LI)
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000322 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000323 ExpensiveCombines(ExpensiveCombines), AA(AA), AC(AC), TLI(TLI), DT(DT),
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000324 DL(DL), SQ(DL, &TLI, &DT, &AC), ORE(ORE), LI(LI) {}
Jakub Staszak190db2f2013-01-14 23:16:36 +0000325
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000326 /// Run the combiner over the entire worklist until it is empty.
Chandler Carruthdf5747a2015-01-21 11:38:17 +0000327 ///
328 /// \returns true if the IR is changed.
329 bool run();
Chris Lattner35522b72010-01-04 07:12:23 +0000330
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000331 AssumptionCache &getAssumptionCache() const { return AC; }
332
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000333 const DataLayout &getDataLayout() const { return DL; }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000334
Justin Bogner99798402016-08-05 01:06:44 +0000335 DominatorTree &getDominatorTree() const { return DT; }
Chris Lattner35522b72010-01-04 07:12:23 +0000336
Chandler Carruth5175b9a2015-01-20 08:35:24 +0000337 LoopInfo *getLoopInfo() const { return LI; }
338
Justin Bogner99798402016-08-05 01:06:44 +0000339 TargetLibraryInfo &getTargetLibraryInfo() const { return TLI; }
Chad Rosier43a33062011-12-02 01:26:24 +0000340
Chris Lattner35522b72010-01-04 07:12:23 +0000341 // Visitation implementation - Implement instruction combining for different
342 // instruction types. The semantics are as follows:
343 // Return Value:
344 // null - No change was made
345 // I - Change was made, I is still valid, I may be dead though
346 // otherwise - Change was made, replace I with returned instruction
347 //
348 Instruction *visitAdd(BinaryOperator &I);
349 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner229907c2011-07-18 04:54:35 +0000350 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
Chris Lattner35522b72010-01-04 07:12:23 +0000351 Instruction *visitSub(BinaryOperator &I);
352 Instruction *visitFSub(BinaryOperator &I);
353 Instruction *visitMul(BinaryOperator &I);
354 Instruction *visitFMul(BinaryOperator &I);
355 Instruction *visitURem(BinaryOperator &I);
356 Instruction *visitSRem(BinaryOperator &I);
357 Instruction *visitFRem(BinaryOperator &I);
Sanjay Patelae2e3a42017-10-06 23:20:16 +0000358 bool simplifyDivRemOfSelectWithZeroOp(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000359 Instruction *commonRemTransforms(BinaryOperator &I);
360 Instruction *commonIRemTransforms(BinaryOperator &I);
361 Instruction *commonDivTransforms(BinaryOperator &I);
362 Instruction *commonIDivTransforms(BinaryOperator &I);
363 Instruction *visitUDiv(BinaryOperator &I);
364 Instruction *visitSDiv(BinaryOperator &I);
Frits van Bommel2a559512011-01-29 17:50:27 +0000365 Instruction *visitFDiv(BinaryOperator &I);
Erik Ecksteind1817522014-12-03 10:39:15 +0000366 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
Chris Lattner35522b72010-01-04 07:12:23 +0000367 Instruction *visitAnd(BinaryOperator &I);
Chandler Carruthd70cc602014-05-07 17:36:59 +0000368 Instruction *visitOr(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000369 Instruction *visitXor(BinaryOperator &I);
370 Instruction *visitShl(BinaryOperator &I);
371 Instruction *visitAShr(BinaryOperator &I);
372 Instruction *visitLShr(BinaryOperator &I);
373 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000374 Instruction *visitFCmpInst(FCmpInst &I);
375 Instruction *visitICmpInst(ICmpInst &I);
Matt Arsenaultfed3dc82014-04-14 21:50:37 +0000376 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
Chris Lattner35522b72010-01-04 07:12:23 +0000377 BinaryOperator &I);
378 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000379 Instruction *commonPointerCastTransforms(CastInst &CI);
380 Instruction *visitTrunc(TruncInst &CI);
381 Instruction *visitZExt(ZExtInst &CI);
382 Instruction *visitSExt(SExtInst &CI);
383 Instruction *visitFPTrunc(FPTruncInst &CI);
384 Instruction *visitFPExt(CastInst &CI);
385 Instruction *visitFPToUI(FPToUIInst &FI);
386 Instruction *visitFPToSI(FPToSIInst &FI);
387 Instruction *visitUIToFP(CastInst &CI);
388 Instruction *visitSIToFP(CastInst &CI);
389 Instruction *visitPtrToInt(PtrToIntInst &CI);
390 Instruction *visitIntToPtr(IntToPtrInst &CI);
391 Instruction *visitBitCast(BitCastInst &CI);
Matt Arsenaulta9e95ab2013-11-15 05:45:08 +0000392 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
Mehdi Aminib9a0fa42015-02-16 21:47:54 +0000393 Instruction *FoldItoFPtoI(Instruction &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000394 Instruction *visitSelectInst(SelectInst &SI);
Chris Lattner35522b72010-01-04 07:12:23 +0000395 Instruction *visitCallInst(CallInst &CI);
396 Instruction *visitInvokeInst(InvokeInst &II);
397
398 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
399 Instruction *visitPHINode(PHINode &PN);
400 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
401 Instruction *visitAllocaInst(AllocaInst &AI);
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000402 Instruction *visitAllocSite(Instruction &FI);
Gabor Greif75f69432010-06-24 12:21:15 +0000403 Instruction *visitFree(CallInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000404 Instruction *visitLoadInst(LoadInst &LI);
405 Instruction *visitStoreInst(StoreInst &SI);
406 Instruction *visitBranchInst(BranchInst &BI);
Davide Italianoaec46172017-01-31 18:09:05 +0000407 Instruction *visitFenceInst(FenceInst &FI);
Chris Lattner35522b72010-01-04 07:12:23 +0000408 Instruction *visitSwitchInst(SwitchInst &SI);
Hal Finkel93873cc12014-09-07 21:28:34 +0000409 Instruction *visitReturnInst(ReturnInst &RI);
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000410 Instruction *visitInsertValueInst(InsertValueInst &IV);
Chris Lattner35522b72010-01-04 07:12:23 +0000411 Instruction *visitInsertElementInst(InsertElementInst &IE);
412 Instruction *visitExtractElementInst(ExtractElementInst &EI);
413 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
414 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Duncan Sands5c055792011-09-30 13:12:16 +0000415 Instruction *visitLandingPadInst(LandingPadInst &LI);
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +0000416 Instruction *visitVAStartInst(VAStartInst &I);
417 Instruction *visitVACopyInst(VACopyInst &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000418
Sanjay Patel53523312016-09-12 14:25:46 +0000419 /// Specify what to return for unhandled instructions.
Craig Toppere73658d2014-04-28 04:05:08 +0000420 Instruction *visitInstruction(Instruction &I) { return nullptr; }
Chris Lattner35522b72010-01-04 07:12:23 +0000421
Sanjay Patel53523312016-09-12 14:25:46 +0000422 /// True when DB dominates all uses of DI except UI.
423 /// UI must be in the same block as DI.
424 /// The routine checks that the DI parent and DB are different.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +0000425 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
426 const BasicBlock *DB) const;
427
Sanjay Patel53523312016-09-12 14:25:46 +0000428 /// Try to replace select with select operand SIOpd in SI-ICmp sequence.
Gerolf Hoflehnerec6217c2014-11-21 23:36:44 +0000429 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
430 const unsigned SIOpd);
431
Yaxun Liuba01ed02017-02-10 21:46:07 +0000432 /// Try to replace instruction \p I with value \p V which are pointers
433 /// in different address space.
434 /// \return true if successful.
435 bool replacePointer(Instruction &I, Value *V);
436
Chris Lattner35522b72010-01-04 07:12:23 +0000437private:
Sanjay Patel2217f752017-01-31 17:25:42 +0000438 bool shouldChangeType(unsigned FromBitWidth, unsigned ToBitWidth) const;
439 bool shouldChangeType(Type *From, Type *To) const;
Chris Lattner2188e402010-01-04 07:37:31 +0000440 Value *dyn_castNegVal(Value *V) const;
David Blaikie87ca1b62015-03-27 20:56:11 +0000441 Type *FindElementAtOffset(PointerType *PtrTy, int64_t Offset,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000442 SmallVectorImpl<Value *> &NewIndices);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000443
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000444 /// Classify whether a cast is worth optimizing.
Chandler Carruth3a622162015-01-20 19:27:58 +0000445 ///
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000446 /// This is a helper to decide whether the simplification of
447 /// logic(cast(A), cast(B)) to cast(logic(A, B)) should be performed.
448 ///
449 /// \param CI The cast we are interested in.
450 ///
451 /// \return true if this cast actually results in any code being generated and
452 /// if it cannot already be eliminated by some other transformation.
453 bool shouldOptimizeCast(CastInst *CI);
Chris Lattner2188e402010-01-04 07:37:31 +0000454
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000455 /// Try to optimize a sequence of instructions checking if an operation
Sanjoy Dasb0984472015-04-08 04:27:22 +0000456 /// on LHS and RHS overflows.
457 ///
Sanjoy Das6f5dca72015-08-28 19:09:31 +0000458 /// If this overflow check is done via one of the overflow check intrinsics,
459 /// then CtxI has to be the call instruction calling that intrinsic. If this
460 /// overflow check is done by arithmetic followed by a compare, then CtxI has
461 /// to be the arithmetic instruction.
462 ///
Sanjoy Dasb0984472015-04-08 04:27:22 +0000463 /// If a simplification is possible, stores the simplified result of the
464 /// operation in OperationResult and result of the overflow check in
465 /// OverflowResult, and return true. If no simplification is possible,
466 /// returns false.
467 bool OptimizeOverflowCheck(OverflowCheckFlavor OCF, Value *LHS, Value *RHS,
468 Instruction &CtxI, Value *&OperationResult,
469 Constant *&OverflowResult);
470
Chris Lattner35522b72010-01-04 07:12:23 +0000471 Instruction *visitCallSite(CallSite CS);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000472 Instruction *tryOptimizeCall(CallInst *CI);
Chris Lattner35522b72010-01-04 07:12:23 +0000473 bool transformConstExprCastCall(CallSite CS);
Duncan Sandsa0984362011-09-06 13:37:06 +0000474 Instruction *transformCallThroughTrampoline(CallSite CS,
475 IntrinsicInst *Tramp);
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000476
477 /// Transform (zext icmp) to bitwise / integer operations in order to
478 /// eliminate it.
479 ///
480 /// \param ICI The icmp of the (zext icmp) pair we are interested in.
481 /// \parem CI The zext of the (zext icmp) pair we are interested in.
482 /// \param DoTransform Pass false to just test whether the given (zext icmp)
483 /// would be transformed. Pass true to actually perform the transformation.
484 ///
485 /// \return null if the transformation cannot be performed. If the
486 /// transformation can be performed the new instruction that replaces the
487 /// (zext icmp) pair will be returned (if \p DoTransform is false the
488 /// unmodified \p ICI will be returned in this case).
489 Instruction *transformZExtICmp(ICmpInst *ICI, ZExtInst &CI,
490 bool DoTransform = true);
491
Benjamin Kramer398b8c52011-04-01 20:09:03 +0000492 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000493
Craig Topper2b1fc322017-05-22 06:25:31 +0000494 bool willNotOverflowSignedAdd(const Value *LHS, const Value *RHS,
495 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000496 return computeOverflowForSignedAdd(LHS, RHS, &CxtI) ==
497 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000498 }
499
Craig Topper2b1fc322017-05-22 06:25:31 +0000500 bool willNotOverflowUnsignedAdd(const Value *LHS, const Value *RHS,
501 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000502 return computeOverflowForUnsignedAdd(LHS, RHS, &CxtI) ==
503 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000504 }
505
Sanjay Patel46945b92018-09-14 21:30:07 +0000506 bool willNotOverflowAdd(const Value *LHS, const Value *RHS,
507 const Instruction &CxtI, bool IsSigned) const {
508 return IsSigned ? willNotOverflowSignedAdd(LHS, RHS, CxtI)
509 : willNotOverflowUnsignedAdd(LHS, RHS, CxtI);
510 }
511
Craig Topper2b1fc322017-05-22 06:25:31 +0000512 bool willNotOverflowSignedSub(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000513 const Instruction &CxtI) const {
514 return computeOverflowForSignedSub(LHS, RHS, &CxtI) ==
515 OverflowResult::NeverOverflows;
516 }
517
Craig Topper2b1fc322017-05-22 06:25:31 +0000518 bool willNotOverflowUnsignedSub(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000519 const Instruction &CxtI) const {
520 return computeOverflowForUnsignedSub(LHS, RHS, &CxtI) ==
521 OverflowResult::NeverOverflows;
522 }
523
Sanjay Patel46945b92018-09-14 21:30:07 +0000524 bool willNotOverflowSub(const Value *LHS, const Value *RHS,
525 const Instruction &CxtI, bool IsSigned) const {
526 return IsSigned ? willNotOverflowSignedSub(LHS, RHS, CxtI)
527 : willNotOverflowUnsignedSub(LHS, RHS, CxtI);
528 }
529
Craig Topper2b1fc322017-05-22 06:25:31 +0000530 bool willNotOverflowSignedMul(const Value *LHS, const Value *RHS,
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000531 const Instruction &CxtI) const {
532 return computeOverflowForSignedMul(LHS, RHS, &CxtI) ==
533 OverflowResult::NeverOverflows;
534 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000535
Craig Topper2b1fc322017-05-22 06:25:31 +0000536 bool willNotOverflowUnsignedMul(const Value *LHS, const Value *RHS,
537 const Instruction &CxtI) const {
Craig Topperbb973722017-05-15 02:44:08 +0000538 return computeOverflowForUnsignedMul(LHS, RHS, &CxtI) ==
539 OverflowResult::NeverOverflows;
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000540 }
541
Sanjay Patel46945b92018-09-14 21:30:07 +0000542 bool willNotOverflowMul(const Value *LHS, const Value *RHS,
543 const Instruction &CxtI, bool IsSigned) const {
544 return IsSigned ? willNotOverflowSignedMul(LHS, RHS, CxtI)
545 : willNotOverflowUnsignedMul(LHS, RHS, CxtI);
546 }
547
Sanjay Patel90a36342018-09-14 22:23:35 +0000548 bool willNotOverflow(BinaryOperator::BinaryOps Opcode, const Value *LHS,
549 const Value *RHS, const Instruction &CxtI,
550 bool IsSigned) const {
551 switch (Opcode) {
552 case Instruction::Add: return willNotOverflowAdd(LHS, RHS, CxtI, IsSigned);
553 case Instruction::Sub: return willNotOverflowSub(LHS, RHS, CxtI, IsSigned);
554 case Instruction::Mul: return willNotOverflowMul(LHS, RHS, CxtI, IsSigned);
555 default: llvm_unreachable("Unexpected opcode for overflow query");
556 }
557 }
558
Nuno Lopesa2f6cec2012-05-22 17:19:09 +0000559 Value *EmitGEPOffset(User *GEP);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000560 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
Sanjay Patel40e7ba02016-02-23 16:36:07 +0000561 Instruction *foldCastedBitwiseLogic(BinaryOperator &I);
Sanjay Patel94da1de2017-08-05 15:19:18 +0000562 Instruction *narrowBinOp(TruncInst &Trunc);
Sanjay Patel1d681122018-01-25 16:34:36 +0000563 Instruction *narrowMaskedBinOp(BinaryOperator &And);
Sanjay Patel90a36342018-09-14 22:23:35 +0000564 Instruction *narrowMathIfNoOverflow(BinaryOperator &I);
Sanjay Patelc50e55d2017-08-09 18:37:41 +0000565 Instruction *narrowRotate(TruncInst &Trunc);
Guozhi Weiae541f62016-10-25 20:43:42 +0000566 Instruction *optimizeBitCastFromPhi(CastInst &CI, PHINode *PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000567
Tobias Grosser8ef834c2016-07-19 09:06:08 +0000568 /// Determine if a pair of casts can be replaced by a single cast.
569 ///
570 /// \param CI1 The first of a pair of casts.
571 /// \param CI2 The second of a pair of casts.
572 ///
573 /// \return 0 if the cast pair cannot be eliminated, otherwise returns an
574 /// Instruction::CastOps value for a cast that can replace the pair, casting
575 /// CI1->getSrcTy() to CI2->getDstTy().
576 ///
577 /// \see CastInst::isEliminableCastPair
578 Instruction::CastOps isEliminableCastPair(const CastInst *CI1,
579 const CastInst *CI2);
580
Craig Topperda6ea0d2017-06-16 05:10:37 +0000581 Value *foldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction &CxtI);
Craig Topperf2d3e6d2017-06-15 19:09:51 +0000582 Value *foldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction &CxtI);
Sanjay Patel5e456b92017-05-18 20:53:16 +0000583 Value *foldXorOfICmps(ICmpInst *LHS, ICmpInst *RHS);
584
Sanjay Patel64fc5da2017-09-02 17:53:33 +0000585 /// Optimize (fcmp)&(fcmp) or (fcmp)|(fcmp).
586 /// NOTE: Unlike most of instcombine, this returns a Value which should
587 /// already be inserted into the function.
588 Value *foldLogicOfFCmps(FCmpInst *LHS, FCmpInst *RHS, bool IsAnd);
589
Craig Topperda6ea0d2017-06-16 05:10:37 +0000590 Value *foldAndOrOfICmpsOfAndWithPow2(ICmpInst *LHS, ICmpInst *RHS,
591 bool JoinedByAnd, Instruction &CxtI);
Sanjay Patel3b206302018-10-24 15:17:56 +0000592 Value *matchSelectFromAndOr(Value *A, Value *B, Value *C, Value *D);
593 Value *getSelectCondition(Value *A, Value *B);
594
Chris Lattner35522b72010-01-04 07:12:23 +0000595public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000596 /// Inserts an instruction \p New before instruction \p Old
Chandler Carruth3a622162015-01-20 19:27:58 +0000597 ///
598 /// Also adds the new instruction to the worklist and returns \p New so that
599 /// it is suitable for use as the return from the visitation patterns.
Chris Lattner35522b72010-01-04 07:12:23 +0000600 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Craig Toppere73658d2014-04-28 04:05:08 +0000601 assert(New && !New->getParent() &&
Chris Lattner35522b72010-01-04 07:12:23 +0000602 "New instruction already inserted into a basic block!");
603 BasicBlock *BB = Old.getParent();
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000604 BB->getInstList().insert(Old.getIterator(), New); // Insert inst
Chris Lattner35522b72010-01-04 07:12:23 +0000605 Worklist.Add(New);
606 return New;
607 }
Eli Friedman6efb64e2011-05-19 01:20:42 +0000608
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000609 /// Same as InsertNewInstBefore, but also sets the debug loc.
Eli Friedman6efb64e2011-05-19 01:20:42 +0000610 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
611 New->setDebugLoc(Old.getDebugLoc());
612 return InsertNewInstBefore(New, Old);
613 }
614
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000615 /// A combiner-aware RAUW-like routine.
Chandler Carruth3a622162015-01-20 19:27:58 +0000616 ///
617 /// This method is to be used when an instruction is found to be dead,
Sanjay Patelf2ea8a22016-01-06 00:23:12 +0000618 /// replaceable with another preexisting expression. Here we add all uses of
Chandler Carruth3a622162015-01-20 19:27:58 +0000619 /// I to the worklist, replace all uses of I with the new value, then return
620 /// I, so that the inst combiner will know that I was modified.
Sanjay Patel4b198802016-02-01 22:23:39 +0000621 Instruction *replaceInstUsesWith(Instruction &I, Value *V) {
Owen Anderson51b75b8c2015-03-10 05:13:47 +0000622 // If there are no uses to replace, then we return nullptr to indicate that
623 // no changes were made to the program.
624 if (I.use_empty()) return nullptr;
625
Chandler Carruthd70cc602014-05-07 17:36:59 +0000626 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000627
Chris Lattner35522b72010-01-04 07:12:23 +0000628 // If we are replacing the instruction with itself, this must be in a
629 // segment of unreachable code, so just clobber the instruction.
Jakub Staszak190db2f2013-01-14 23:16:36 +0000630 if (&I == V)
Chris Lattner35522b72010-01-04 07:12:23 +0000631 V = UndefValue::get(I.getType());
Frits van Bommeld14d9912011-03-27 23:32:31 +0000632
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000633 LLVM_DEBUG(dbgs() << "IC: Replacing " << I << "\n"
634 << " with " << *V << '\n');
Frits van Bommeld14d9912011-03-27 23:32:31 +0000635
Chris Lattner35522b72010-01-04 07:12:23 +0000636 I.replaceAllUsesWith(V);
637 return &I;
638 }
639
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000640 /// Creates a result tuple for an overflow intrinsic \p II with a given
Sanjoy Dasb0984472015-04-08 04:27:22 +0000641 /// \p Result and a constant \p Overflow value.
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000642 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
Sanjoy Dasb0984472015-04-08 04:27:22 +0000643 Constant *Overflow) {
644 Constant *V[] = {UndefValue::get(Result->getType()), Overflow};
Erik Eckstein096ff7d2014-12-11 08:02:30 +0000645 StructType *ST = cast<StructType>(II->getType());
646 Constant *Struct = ConstantStruct::get(ST, V);
647 return InsertValueInst::Create(Struct, Result, 0);
648 }
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000649
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000650 /// Combiner aware instruction erasure.
Chandler Carruth3a622162015-01-20 19:27:58 +0000651 ///
652 /// When dealing with an instruction that has side effects or produces a void
653 /// value, we can't rely on DCE to delete the instruction. Instead, visit
654 /// methods should return the value returned by this function.
Sanjay Patel4b198802016-02-01 22:23:39 +0000655 Instruction *eraseInstFromFunction(Instruction &I) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000656 LLVM_DEBUG(dbgs() << "IC: ERASE " << I << '\n');
Adrian Prantlfa9e84e2017-03-16 20:11:54 +0000657 assert(I.use_empty() && "Cannot erase instruction that is used!");
Adrian Prantl47ea6472017-03-16 21:14:09 +0000658 salvageDebugInfo(I);
659
Chris Lattner35522b72010-01-04 07:12:23 +0000660 // Make sure that we reprocess all operands now that we reduced their
661 // use counts.
662 if (I.getNumOperands() < 8) {
Sanjay Patel8af7fbc32016-01-31 16:34:48 +0000663 for (Use &Operand : I.operands())
664 if (auto *Inst = dyn_cast<Instruction>(Operand))
665 Worklist.Add(Inst);
Chris Lattner35522b72010-01-04 07:12:23 +0000666 }
667 Worklist.Remove(&I);
668 I.eraseFromParent();
669 MadeIRChange = true;
Chandler Carruthd70cc602014-05-07 17:36:59 +0000670 return nullptr; // Don't do anything with FI
Chris Lattner35522b72010-01-04 07:12:23 +0000671 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000672
Craig Topper2b1fc322017-05-22 06:25:31 +0000673 void computeKnownBits(const Value *V, KnownBits &Known,
674 unsigned Depth, const Instruction *CxtI) const {
Craig Topper26c41592017-05-15 02:30:27 +0000675 llvm::computeKnownBits(V, Known, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000676 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000677
Craig Topper2b1fc322017-05-22 06:25:31 +0000678 KnownBits computeKnownBits(const Value *V, unsigned Depth,
679 const Instruction *CxtI) const {
Craig Topper1a36b7d2017-05-15 06:39:41 +0000680 return llvm::computeKnownBits(V, DL, Depth, &AC, CxtI, &DT);
681 }
Jakub Staszak190db2f2013-01-14 23:16:36 +0000682
Craig Topperd4039f72017-05-25 21:51:12 +0000683 bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero = false,
684 unsigned Depth = 0,
685 const Instruction *CxtI = nullptr) {
686 return llvm::isKnownToBeAPowerOfTwo(V, DL, OrZero, Depth, &AC, CxtI, &DT);
687 }
688
Craig Topper2b1fc322017-05-22 06:25:31 +0000689 bool MaskedValueIsZero(const Value *V, const APInt &Mask, unsigned Depth = 0,
690 const Instruction *CxtI = nullptr) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000691 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000692 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000693
Craig Topper2b1fc322017-05-22 06:25:31 +0000694 unsigned ComputeNumSignBits(const Value *Op, unsigned Depth = 0,
695 const Instruction *CxtI = nullptr) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000696 return llvm::ComputeNumSignBits(Op, DL, Depth, &AC, CxtI, &DT);
Chris Lattner35522b72010-01-04 07:12:23 +0000697 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000698
Craig Topper2b1fc322017-05-22 06:25:31 +0000699 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
700 const Value *RHS,
701 const Instruction *CxtI) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000702 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
David Majnemer491331a2015-01-02 07:29:43 +0000703 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000704
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000705 OverflowResult computeOverflowForSignedMul(const Value *LHS,
706 const Value *RHS,
707 const Instruction *CxtI) const {
708 return llvm::computeOverflowForSignedMul(LHS, RHS, DL, &AC, CxtI, &DT);
709 }
710
Craig Topper2b1fc322017-05-22 06:25:31 +0000711 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
712 const Value *RHS,
713 const Instruction *CxtI) const {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000714 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
David Majnemer5310c1e2015-01-07 00:39:50 +0000715 }
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000716
Craig Topperbb973722017-05-15 02:44:08 +0000717 OverflowResult computeOverflowForSignedAdd(const Value *LHS,
718 const Value *RHS,
719 const Instruction *CxtI) const {
720 return llvm::computeOverflowForSignedAdd(LHS, RHS, DL, &AC, CxtI, &DT);
721 }
Chris Lattner35522b72010-01-04 07:12:23 +0000722
Omer Paparo Bivasfbb83de2018-05-10 19:46:19 +0000723 OverflowResult computeOverflowForUnsignedSub(const Value *LHS,
724 const Value *RHS,
725 const Instruction *CxtI) const {
726 return llvm::computeOverflowForUnsignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
727 }
728
729 OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
730 const Instruction *CxtI) const {
731 return llvm::computeOverflowForSignedSub(LHS, RHS, DL, &AC, CxtI, &DT);
732 }
733
Davide Italiano2133bf52017-02-07 17:56:50 +0000734 /// Maximum size of array considered when transforming.
David Blaikie4c01af22017-02-07 18:58:17 +0000735 uint64_t MaxArraySizeForCombine;
Davide Italiano2133bf52017-02-07 17:56:50 +0000736
Chris Lattner35522b72010-01-04 07:12:23 +0000737private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000738 /// Performs a few simplifications for operators which are associative
Chandler Carruth3a622162015-01-20 19:27:58 +0000739 /// or commutative.
Duncan Sands641baf12010-11-13 15:10:37 +0000740 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattner35522b72010-01-04 07:12:23 +0000741
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000742 /// Tries to simplify binary operations which some other binary
Chandler Carruthb3d03df2015-01-20 21:10:35 +0000743 /// operation distributes over.
Chandler Carruth3a622162015-01-20 19:27:58 +0000744 ///
745 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
746 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
747 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
748 /// value, or null if it didn't simplify.
Duncan Sandsfbb9ac32010-12-22 13:36:08 +0000749 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sandsadc7771f2010-11-23 14:23:47 +0000750
Sanjoy Das6f1937b2018-04-26 20:52:28 +0000751 /// Tries to simplify add operations using the definition of remainder.
752 ///
753 /// The definition of remainder is X % C = X - (X / C ) * C. The add
754 /// expression X % C0 + (( X / C0 ) % C1) * C0 can be simplified to
755 /// X % (C0 * C1)
756 Value *SimplifyAddWithRemainder(BinaryOperator &I);
757
Quentin Colombetaa103b32017-09-20 17:32:16 +0000758 // Binary Op helper for select operations where the expression can be
759 // efficiently reorganized.
760 Value *SimplifySelectsFeedingBinaryOp(BinaryOperator &I, Value *LHS,
761 Value *RHS);
762
Daniel Berlin2c75c632017-04-26 20:56:07 +0000763 /// This tries to simplify binary operations by factorizing out common terms
764 /// (e. g. "(A*B)+(A*C)" -> "A*(B+C)").
Craig Topper47c8f662017-07-06 18:35:52 +0000765 Value *tryFactorization(BinaryOperator &, Instruction::BinaryOps, Value *,
766 Value *, Value *, Value *);
Daniel Berlin2c75c632017-04-26 20:56:07 +0000767
Anna Thomasd67165c2017-06-23 13:41:45 +0000768 /// Match a select chain which produces one of three values based on whether
769 /// the LHS is less than, equal to, or greater than RHS respectively.
770 /// Return true if we matched a three way compare idiom. The LHS, RHS, Less,
771 /// Equal and Greater values are saved in the matching process and returned to
772 /// the caller.
773 bool matchThreeWayIntCompare(SelectInst *SI, Value *&LHS, Value *&RHS,
774 ConstantInt *&Less, ConstantInt *&Equal,
775 ConstantInt *&Greater);
776
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000777 /// Attempts to replace V with a simpler value based on the demanded
Chandler Carruth3a622162015-01-20 19:27:58 +0000778 /// bits.
Craig Topperb45eabc2017-04-26 16:39:58 +0000779 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, KnownBits &Known,
780 unsigned Depth, Instruction *CxtI);
Craig Topper47596dd2017-03-25 06:52:52 +0000781 bool SimplifyDemandedBits(Instruction *I, unsigned Op,
Craig Topperb45eabc2017-04-26 16:39:58 +0000782 const APInt &DemandedMask, KnownBits &Known,
783 unsigned Depth = 0);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000784
Craig Topperb0076fe2017-04-12 18:05:21 +0000785 /// Helper routine of SimplifyDemandedUseBits. It computes KnownZero/KnownOne
786 /// bits. It also tries to handle simplifications that can be done based on
787 /// DemandedMask, but without modifying the Instruction.
788 Value *SimplifyMultipleUseDemandedBits(Instruction *I,
789 const APInt &DemandedMask,
Craig Topperb45eabc2017-04-26 16:39:58 +0000790 KnownBits &Known,
Craig Topperb0076fe2017-04-12 18:05:21 +0000791 unsigned Depth, Instruction *CxtI);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000792
Shuxin Yang63e999e2012-12-04 00:04:54 +0000793 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
794 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
Sanjay Patelcc663b82017-04-20 22:37:01 +0000795 Value *simplifyShrShlDemandedBits(
Sanjay Patelc9485ca2017-04-20 22:33:54 +0000796 Instruction *Shr, const APInt &ShrOp1, Instruction *Shl,
Craig Topperb45eabc2017-04-26 16:39:58 +0000797 const APInt &ShlOp1, const APInt &DemandedMask, KnownBits &Known);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000798
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000799 /// Tries to simplify operands to an integer instruction based on its
Chandler Carruth3a622162015-01-20 19:27:58 +0000800 /// demanded bits.
Chris Lattner35522b72010-01-04 07:12:23 +0000801 bool SimplifyDemandedInstructionBits(Instruction &Inst);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000802
Nicolai Haehnleb29ee702018-06-21 13:37:31 +0000803 Value *simplifyAMDGCNMemoryIntrinsicDemanded(IntrinsicInst *II,
804 APInt DemandedElts,
805 int DmaskIdx = -1);
806
Chris Lattner35522b72010-01-04 07:12:23 +0000807 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
Chandler Carruthd70cc602014-05-07 17:36:59 +0000808 APInt &UndefElts, unsigned Depth = 0);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000809
Sanjay Patelbbc6d602018-06-02 16:27:44 +0000810 /// Canonicalize the position of binops relative to shufflevector.
Sanjay Patel79dceb22018-10-03 15:20:58 +0000811 Instruction *foldVectorBinop(BinaryOperator &Inst);
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000812
813 /// Given a binary operator, cast instruction, or select which has a PHI node
814 /// as operand #0, see if we can fold the instruction into the PHI (which is
815 /// only possible if all operands to the PHI are constants).
Craig Topperfb71b7d2017-04-14 19:20:12 +0000816 Instruction *foldOpIntoPhi(Instruction &I, PHINode *PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000817
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000818 /// Given an instruction with a select as one operand and a constant as the
819 /// other operand, try to fold the binary operator into the select arguments.
820 /// This also works for Cast instructions, which obviously do not have a
821 /// second operand.
822 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
823
824 /// This is a convenience wrapper function for the above two functions.
Sanjay Patel8fdd87f2018-02-28 16:36:24 +0000825 Instruction *foldBinOpIntoSelectOrPhi(BinaryOperator &I);
Sanjay Pateldb0938f2017-01-10 23:49:07 +0000826
Sanjay Patel8d810fe2017-10-13 16:43:58 +0000827 Instruction *foldAddWithConstant(BinaryOperator &Add);
828
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000829 /// Try to rotate an operation below a PHI node, using PHI nodes for
Chandler Carruth3a622162015-01-20 19:27:58 +0000830 /// its operands.
Chris Lattner35522b72010-01-04 07:12:23 +0000831 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
832 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
833 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
834 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Sanjay Patel95334072015-09-27 20:34:31 +0000835 Instruction *FoldPHIArgZextsIntoPHI(PHINode &PN);
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000836
Xinliang David Li4cdc9da2017-10-10 05:07:54 +0000837 /// If an integer typed PHI has only one use which is an IntToPtr operation,
838 /// replace the PHI with an existing pointer typed PHI if it exists. Otherwise
839 /// insert a new pointer typed PHI and replace the original one.
840 Instruction *FoldIntegerTypedPHI(PHINode &PN);
Chris Lattner35522b72010-01-04 07:12:23 +0000841
Dehao Chenf4646272017-10-02 18:13:14 +0000842 /// Helper function for FoldPHIArgXIntoPHI() to set debug location for the
Robert Lougher2428a402016-12-14 17:49:19 +0000843 /// folded operation.
Dehao Chenf4646272017-10-02 18:13:14 +0000844 void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN);
Robert Lougher2428a402016-12-14 17:49:19 +0000845
Sanjay Patel43395062016-07-21 18:07:40 +0000846 Instruction *foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
847 ICmpInst::Predicate Cond, Instruction &I);
Pete Cooper980a9352016-08-12 17:13:28 +0000848 Instruction *foldAllocaCmp(ICmpInst &ICI, const AllocaInst *Alloca,
849 const Value *Other);
Sanjay Patel43395062016-07-21 18:07:40 +0000850 Instruction *foldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
851 GlobalVariable *GV, CmpInst &ICI,
852 ConstantInt *AndCst = nullptr);
853 Instruction *foldFCmpIntToFPConst(FCmpInst &I, Instruction *LHSI,
854 Constant *RHSC);
Craig Topperbee74792018-08-20 23:04:25 +0000855 Instruction *foldICmpAddOpConst(Value *X, const APInt &C,
Sanjay Patel43395062016-07-21 18:07:40 +0000856 ICmpInst::Predicate Pred);
857 Instruction *foldICmpWithCastAndCast(ICmpInst &ICI);
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000858
Sanjay Patel3151dec2016-09-12 15:24:31 +0000859 Instruction *foldICmpUsingKnownBits(ICmpInst &Cmp);
Sanjay Patel06b127a2016-09-15 14:37:50 +0000860 Instruction *foldICmpWithConstant(ICmpInst &Cmp);
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000861 Instruction *foldICmpInstWithConstant(ICmpInst &Cmp);
Sanjay Patel10494b22016-09-16 16:10:22 +0000862 Instruction *foldICmpInstWithConstantNotInt(ICmpInst &Cmp);
863 Instruction *foldICmpBinOp(ICmpInst &Cmp);
864 Instruction *foldICmpEquality(ICmpInst &Cmp);
Nikolai Bozhenov0e7ebbc2017-10-16 09:19:21 +0000865 Instruction *foldICmpWithZero(ICmpInst &Cmp);
Sanjay Patela3f4f082016-08-16 17:54:36 +0000866
Craig Topper524c44f2017-08-23 05:46:07 +0000867 Instruction *foldICmpSelectConstant(ICmpInst &Cmp, SelectInst *Select,
Anna Thomasd67165c2017-06-23 13:41:45 +0000868 ConstantInt *C);
Daniel Neilson901acfa2018-04-03 17:26:20 +0000869 Instruction *foldICmpBitCastConstant(ICmpInst &Cmp, BitCastInst *Bitcast,
870 const APInt &C);
Craig Topper524c44f2017-08-23 05:46:07 +0000871 Instruction *foldICmpTruncConstant(ICmpInst &Cmp, TruncInst *Trunc,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000872 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000873 Instruction *foldICmpAndConstant(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000874 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000875 Instruction *foldICmpXorConstant(ICmpInst &Cmp, BinaryOperator *Xor,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000876 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000877 Instruction *foldICmpOrConstant(ICmpInst &Cmp, BinaryOperator *Or,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000878 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000879 Instruction *foldICmpMulConstant(ICmpInst &Cmp, BinaryOperator *Mul,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000880 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000881 Instruction *foldICmpShlConstant(ICmpInst &Cmp, BinaryOperator *Shl,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000882 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000883 Instruction *foldICmpShrConstant(ICmpInst &Cmp, BinaryOperator *Shr,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000884 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000885 Instruction *foldICmpUDivConstant(ICmpInst &Cmp, BinaryOperator *UDiv,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000886 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000887 Instruction *foldICmpDivConstant(ICmpInst &Cmp, BinaryOperator *Div,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000888 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000889 Instruction *foldICmpSubConstant(ICmpInst &Cmp, BinaryOperator *Sub,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000890 const APInt &C);
Sanjay Patelc9196c42016-08-22 21:24:29 +0000891 Instruction *foldICmpAddConstant(ICmpInst &Cmp, BinaryOperator *Add,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000892 const APInt &C);
Sanjay Pateld3c7bb282016-08-26 16:42:33 +0000893 Instruction *foldICmpAndConstConst(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000894 const APInt &C1);
Sanjay Patel14e0e182016-08-26 18:28:46 +0000895 Instruction *foldICmpAndShift(ICmpInst &Cmp, BinaryOperator *And,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000896 const APInt &C1, const APInt &C2);
Sanjay Patel8da42cc2016-09-15 22:26:31 +0000897 Instruction *foldICmpShrConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
898 const APInt &C2);
899 Instruction *foldICmpShlConstConst(ICmpInst &I, Value *ShAmt, const APInt &C1,
900 const APInt &C2);
Sanjay Patela3f4f082016-08-16 17:54:36 +0000901
Sanjay Patelf58f68c2016-09-10 15:03:44 +0000902 Instruction *foldICmpBinOpEqualityWithConstant(ICmpInst &Cmp,
903 BinaryOperator *BO,
Craig Topper8ed1aa92017-10-03 05:31:07 +0000904 const APInt &C);
905 Instruction *foldICmpIntrinsicWithConstant(ICmpInst &ICI, const APInt &C);
Sanjay Patel43395062016-07-21 18:07:40 +0000906
Sanjay Patel453ceff2016-09-29 22:18:30 +0000907 // Helpers of visitSelectInst().
Sanjay Patelf7b851f2016-09-30 19:49:22 +0000908 Instruction *foldSelectExtConst(SelectInst &Sel);
Sanjay Patel453ceff2016-09-29 22:18:30 +0000909 Instruction *foldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
910 Instruction *foldSelectIntoOp(SelectInst &SI, Value *, Value *);
911 Instruction *foldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
912 Value *A, Value *B, Instruction &Outer,
913 SelectPatternFlavor SPF2, Value *C);
914 Instruction *foldSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
915
Craig Topper70e4f432017-04-02 17:57:30 +0000916 Instruction *OptAndOp(BinaryOperator *Op, ConstantInt *OpRHS,
Chris Lattner35522b72010-01-04 07:12:23 +0000917 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Jakub Staszak190db2f2013-01-14 23:16:36 +0000918
Sanjay Patel85d79742016-08-31 19:49:56 +0000919 Value *insertRangeTest(Value *V, const APInt &Lo, const APInt &Hi,
920 bool isSigned, bool Inside);
Chris Lattner35522b72010-01-04 07:12:23 +0000921 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Sanjay Patel4a12aa92018-11-10 20:29:25 +0000922 bool mergeStoreIntoSuccessor(StoreInst &SI);
Igor Laevsky900ffa32017-02-08 14:32:04 +0000923
Sanjay Patel60728422018-11-14 16:03:36 +0000924 /// Given an 'or' instruction, check to see if it is part of a bswap idiom.
925 /// If so, return the equivalent bswap intrinsic.
926 Instruction *matchBSwap(BinaryOperator &Or);
927
Daniel Neilson8f30ec62018-05-11 14:30:02 +0000928 Instruction *SimplifyAnyMemTransfer(AnyMemTransferInst *MI);
Daniel Neilsonf6651d42018-05-11 20:04:50 +0000929 Instruction *SimplifyAnyMemSet(AnyMemSetInst *MI);
Chris Lattner35522b72010-01-04 07:12:23 +0000930
Chris Lattner229907c2011-07-18 04:54:35 +0000931 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
Duncan Sands533c8ae2012-10-23 08:28:26 +0000932
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000933 /// Returns a value X such that Val = X * Scale, or null if none.
Chandler Carruth3a622162015-01-20 19:27:58 +0000934 ///
935 /// If the multiplication is known not to overflow then NoSignedWrap is set.
Duncan Sands533c8ae2012-10-23 08:28:26 +0000936 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
Chris Lattner35522b72010-01-04 07:12:23 +0000937};
938
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000939} // end namespace llvm
Chris Lattner35522b72010-01-04 07:12:23 +0000940
Chandler Carruth964daaa2014-04-22 02:55:47 +0000941#undef DEBUG_TYPE
942
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000943#endif // LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H