blob: 17d6f30a35cbccce706791e40ed374e4bae4a690 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===-- InstructionSimplify.h - Fold instrs into simpler forms --*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8//
9// This file declares routines for folding instructions into simpler forms
10// that do not require creating new instructions. This does constant folding
11// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13// ("and i32 %x, %x" -> "%x"). If the simplification is also an instruction
14// then it dominates the original instruction.
15//
16// These routines implicitly resolve undef uses. The easiest way to be safe when
17// using these routines to obtain simplified values for existing instructions is
18// to always replace all uses of the instructions with the resulting simplified
19// values. This will prevent other code from seeing the same undef uses and
20// resolving them to different values.
21//
22// These routines are designed to tolerate moderately incomplete IR, such as
23// instructions that are not connected to basic blocks yet. However, they do
24// require that all the IR that they encounter be valid. In particular, they
25// require that all non-constant values be defined in the same function, and the
26// same call context of that function (and not split between caller and callee
27// contexts of a directly recursive call, for example).
28//
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020029// Additionally, these routines can't simplify to the instructions that are not
30// def-reachable, meaning we can't just scan the basic block for instructions
31// to simplify to.
32//
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010033//===----------------------------------------------------------------------===//
34
35#ifndef LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
36#define LLVM_ANALYSIS_INSTRUCTIONSIMPLIFY_H
37
Andrew Scull0372a572018-11-16 15:47:06 +000038#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Operator.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010040
41namespace llvm {
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020042
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010043template <typename T, typename... TArgs> class AnalysisManager;
44template <class T> class ArrayRef;
45class AssumptionCache;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020046class BinaryOperator;
Andrew Walbran16937d02019-10-22 13:54:20 +010047class CallBase;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010048class DataLayout;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020049class DominatorTree;
50class Function;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010051struct LoopStandardAnalysisResults;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020052class MDNode;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010053class OptimizationRemarkEmitter;
54class Pass;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020055template <class T, unsigned n> class SmallSetVector;
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010056class TargetLibraryInfo;
57class Type;
58class Value;
Andrew Scull0372a572018-11-16 15:47:06 +000059
60/// InstrInfoQuery provides an interface to query additional information for
61/// instructions like metadata or keywords like nsw, which provides conservative
62/// results if the users specified it is safe to use.
63struct InstrInfoQuery {
64 InstrInfoQuery(bool UMD) : UseInstrInfo(UMD) {}
65 InstrInfoQuery() : UseInstrInfo(true) {}
66 bool UseInstrInfo = true;
67
68 MDNode *getMetadata(const Instruction *I, unsigned KindID) const {
69 if (UseInstrInfo)
70 return I->getMetadata(KindID);
71 return nullptr;
72 }
73
74 template <class InstT> bool hasNoUnsignedWrap(const InstT *Op) const {
75 if (UseInstrInfo)
76 return Op->hasNoUnsignedWrap();
77 return false;
78 }
79
80 template <class InstT> bool hasNoSignedWrap(const InstT *Op) const {
81 if (UseInstrInfo)
82 return Op->hasNoSignedWrap();
83 return false;
84 }
85
86 bool isExact(const BinaryOperator *Op) const {
87 if (UseInstrInfo && isa<PossiblyExactOperator>(Op))
88 return cast<PossiblyExactOperator>(Op)->isExact();
89 return false;
90 }
91};
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010092
93struct SimplifyQuery {
94 const DataLayout &DL;
95 const TargetLibraryInfo *TLI = nullptr;
96 const DominatorTree *DT = nullptr;
97 AssumptionCache *AC = nullptr;
98 const Instruction *CxtI = nullptr;
99
Andrew Scull0372a572018-11-16 15:47:06 +0000100 // Wrapper to query additional information for instructions like metadata or
101 // keywords like nsw, which provides conservative results if those cannot
102 // be safely used.
103 const InstrInfoQuery IIQ;
104
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200105 /// Controls whether simplifications are allowed to constrain the range of
106 /// possible values for uses of undef. If it is false, simplifications are not
107 /// allowed to assume a particular value for a use of undef for example.
108 bool CanUseUndef = true;
109
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100110 SimplifyQuery(const DataLayout &DL, const Instruction *CXTI = nullptr)
111 : DL(DL), CxtI(CXTI) {}
112
113 SimplifyQuery(const DataLayout &DL, const TargetLibraryInfo *TLI,
114 const DominatorTree *DT = nullptr,
115 AssumptionCache *AC = nullptr,
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200116 const Instruction *CXTI = nullptr, bool UseInstrInfo = true,
117 bool CanUseUndef = true)
118 : DL(DL), TLI(TLI), DT(DT), AC(AC), CxtI(CXTI), IIQ(UseInstrInfo),
119 CanUseUndef(CanUseUndef) {}
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100120 SimplifyQuery getWithInstruction(Instruction *I) const {
121 SimplifyQuery Copy(*this);
122 Copy.CxtI = I;
123 return Copy;
124 }
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200125 SimplifyQuery getWithoutUndef() const {
126 SimplifyQuery Copy(*this);
127 Copy.CanUseUndef = false;
128 return Copy;
129 }
130
131 /// If CanUseUndef is true, returns whether \p V is undef.
132 /// Otherwise always return false.
133 bool isUndefValue(Value *V) const {
134 if (!CanUseUndef)
135 return false;
136 return isa<UndefValue>(V);
137 }
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100138};
139
140// NOTE: the explicit multiple argument versions of these functions are
141// deprecated.
142// Please use the SimplifyQuery versions in new code.
143
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100144/// Given operand for an FNeg, fold the result or return null.
145Value *SimplifyFNegInst(Value *Op, FastMathFlags FMF,
146 const SimplifyQuery &Q);
147
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100148/// Given operands for an Add, fold the result or return null.
149Value *SimplifyAddInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
150 const SimplifyQuery &Q);
151
152/// Given operands for a Sub, fold the result or return null.
153Value *SimplifySubInst(Value *LHS, Value *RHS, bool isNSW, bool isNUW,
154 const SimplifyQuery &Q);
155
156/// Given operands for an FAdd, fold the result or return null.
157Value *SimplifyFAddInst(Value *LHS, Value *RHS, FastMathFlags FMF,
158 const SimplifyQuery &Q);
159
160/// Given operands for an FSub, fold the result or return null.
161Value *SimplifyFSubInst(Value *LHS, Value *RHS, FastMathFlags FMF,
162 const SimplifyQuery &Q);
163
164/// Given operands for an FMul, fold the result or return null.
165Value *SimplifyFMulInst(Value *LHS, Value *RHS, FastMathFlags FMF,
166 const SimplifyQuery &Q);
167
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200168/// Given operands for the multiplication of a FMA, fold the result or return
169/// null. In contrast to SimplifyFMulInst, this function will not perform
170/// simplifications whose unrounded results differ when rounded to the argument
171/// type.
172Value *SimplifyFMAFMul(Value *LHS, Value *RHS, FastMathFlags FMF,
173 const SimplifyQuery &Q);
174
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100175/// Given operands for a Mul, fold the result or return null.
176Value *SimplifyMulInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
177
178/// Given operands for an SDiv, fold the result or return null.
179Value *SimplifySDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
180
181/// Given operands for a UDiv, fold the result or return null.
182Value *SimplifyUDivInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
183
184/// Given operands for an FDiv, fold the result or return null.
185Value *SimplifyFDivInst(Value *LHS, Value *RHS, FastMathFlags FMF,
186 const SimplifyQuery &Q);
187
188/// Given operands for an SRem, fold the result or return null.
189Value *SimplifySRemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
190
191/// Given operands for a URem, fold the result or return null.
192Value *SimplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
193
194/// Given operands for an FRem, fold the result or return null.
195Value *SimplifyFRemInst(Value *LHS, Value *RHS, FastMathFlags FMF,
196 const SimplifyQuery &Q);
197
198/// Given operands for a Shl, fold the result or return null.
199Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
200 const SimplifyQuery &Q);
201
202/// Given operands for a LShr, fold the result or return null.
203Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
204 const SimplifyQuery &Q);
205
206/// Given operands for a AShr, fold the result or return nulll.
207Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
208 const SimplifyQuery &Q);
209
210/// Given operands for an And, fold the result or return null.
211Value *SimplifyAndInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
212
213/// Given operands for an Or, fold the result or return null.
214Value *SimplifyOrInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
215
216/// Given operands for an Xor, fold the result or return null.
217Value *SimplifyXorInst(Value *LHS, Value *RHS, const SimplifyQuery &Q);
218
219/// Given operands for an ICmpInst, fold the result or return null.
220Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
221 const SimplifyQuery &Q);
222
223/// Given operands for an FCmpInst, fold the result or return null.
224Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
225 FastMathFlags FMF, const SimplifyQuery &Q);
226
227/// Given operands for a SelectInst, fold the result or return null.
228Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
229 const SimplifyQuery &Q);
230
231/// Given operands for a GetElementPtrInst, fold the result or return null.
232Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
233 const SimplifyQuery &Q);
234
235/// Given operands for an InsertValueInst, fold the result or return null.
236Value *SimplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
237 const SimplifyQuery &Q);
238
239/// Given operands for an InsertElement, fold the result or return null.
240Value *SimplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx,
241 const SimplifyQuery &Q);
242
243/// Given operands for an ExtractValueInst, fold the result or return null.
244Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
245 const SimplifyQuery &Q);
246
247/// Given operands for an ExtractElementInst, fold the result or return null.
248Value *SimplifyExtractElementInst(Value *Vec, Value *Idx,
249 const SimplifyQuery &Q);
250
251/// Given operands for a CastInst, fold the result or return null.
252Value *SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
253 const SimplifyQuery &Q);
254
255/// Given operands for a ShuffleVectorInst, fold the result or return null.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200256/// See class ShuffleVectorInst for a description of the mask representation.
257Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef<int> Mask,
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100258 Type *RetTy, const SimplifyQuery &Q);
259
260//=== Helper functions for higher up the class hierarchy.
261
262/// Given operands for a CmpInst, fold the result or return null.
263Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
264 const SimplifyQuery &Q);
265
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100266/// Given operand for a UnaryOperator, fold the result or return null.
267Value *SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q);
268
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200269/// Given operand for a UnaryOperator, fold the result or return null.
270/// Try to use FastMathFlags when folding the result.
271Value *SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
272 const SimplifyQuery &Q);
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100273
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100274/// Given operands for a BinaryOperator, fold the result or return null.
275Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
276 const SimplifyQuery &Q);
277
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200278/// Given operands for a BinaryOperator, fold the result or return null.
279/// Try to use FastMathFlags when folding the result.
280Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
281 FastMathFlags FMF, const SimplifyQuery &Q);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100282
283/// Given a callsite, fold the result or return null.
Andrew Walbran16937d02019-10-22 13:54:20 +0100284Value *SimplifyCall(CallBase *Call, const SimplifyQuery &Q);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100285
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200286/// Given an operand for a Freeze, see if we can fold the result.
287/// If not, this returns null.
288Value *SimplifyFreezeInst(Value *Op, const SimplifyQuery &Q);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100289
290/// See if we can compute a simplified version of this instruction. If not,
291/// return null.
292Value *SimplifyInstruction(Instruction *I, const SimplifyQuery &Q,
293 OptimizationRemarkEmitter *ORE = nullptr);
294
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200295/// See if V simplifies when its operand Op is replaced with RepOp. If not,
296/// return null.
297/// AllowRefinement specifies whether the simplification can be a refinement,
298/// or whether it needs to be strictly identical.
299Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
300 const SimplifyQuery &Q, bool AllowRefinement);
301
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100302/// Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
303///
304/// This first performs a normal RAUW of I with SimpleV. It then recursively
305/// attempts to simplify those users updated by the operation. The 'I'
306/// instruction must not be equal to the simplified value 'SimpleV'.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200307/// If UnsimplifiedUsers is provided, instructions that could not be simplified
308/// are added to it.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100309///
310/// The function returns true if any simplifications were performed.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200311bool replaceAndRecursivelySimplify(
312 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI = nullptr,
313 const DominatorTree *DT = nullptr, AssumptionCache *AC = nullptr,
314 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr);
Andrew Scull5e1ddfa2018-08-14 10:06:54 +0100315
316// These helper functions return a SimplifyQuery structure that contains as
317// many of the optional analysis we use as are currently valid. This is the
318// strongly preferred way of constructing SimplifyQuery in passes.
319const SimplifyQuery getBestSimplifyQuery(Pass &, Function &);
320template <class T, class... TArgs>
321const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &,
322 Function &);
323const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &,
324 const DataLayout &);
325} // end namespace llvm
326
327#endif
328