1 //===- llvm/Analysis/IVDescriptors.h - IndVar Descriptors -------*- C++ -*-===//
3 // 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
7 //===----------------------------------------------------------------------===//
9 // This file "describes" induction and recurrence variables.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_ANALYSIS_IVDESCRIPTORS_H
14 #define LLVM_ANALYSIS_IVDESCRIPTORS_H
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/DemandedBits.h"
24 #include "llvm/Analysis/EHPersonalities.h"
25 #include "llvm/Analysis/MustExecute.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InstrTypes.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Support/Casting.h"
37 class AliasSetTracker
;
42 class OptimizationRemarkEmitter
;
43 class PredicatedScalarEvolution
;
44 class PredIteratorCache
;
45 class ScalarEvolution
;
47 class TargetLibraryInfo
;
48 class TargetTransformInfo
;
50 /// The RecurrenceDescriptor is used to identify recurrences variables in a
51 /// loop. Reduction is a special case of recurrence that has uses of the
52 /// recurrence variable outside the loop. The method isReductionPHI identifies
53 /// reductions that are basic recurrences.
55 /// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
56 /// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
57 /// array[i]; } is a summation of array elements. Basic recurrences are a
58 /// special case of chains of recurrences (CR). See ScalarEvolution for CR
61 /// This struct holds information about recurrence variables.
62 class RecurrenceDescriptor
{
64 /// This enum represents the kinds of recurrences that we support.
66 RK_NoRecurrence
, ///< Not a recurrence.
67 RK_IntegerAdd
, ///< Sum of integers.
68 RK_IntegerMult
, ///< Product of integers.
69 RK_IntegerOr
, ///< Bitwise or logical OR of numbers.
70 RK_IntegerAnd
, ///< Bitwise or logical AND of numbers.
71 RK_IntegerXor
, ///< Bitwise or logical XOR of numbers.
72 RK_IntegerMinMax
, ///< Min/max implemented in terms of select(cmp()).
73 RK_FloatAdd
, ///< Sum of floats.
74 RK_FloatMult
, ///< Product of floats.
75 RK_FloatMinMax
///< Min/max implemented in terms of select(cmp()).
78 // This enum represents the kind of minmax recurrence.
79 enum MinMaxRecurrenceKind
{
89 RecurrenceDescriptor() = default;
91 RecurrenceDescriptor(Value
*Start
, Instruction
*Exit
, RecurrenceKind K
,
92 MinMaxRecurrenceKind MK
, Instruction
*UAI
, Type
*RT
,
93 bool Signed
, SmallPtrSetImpl
<Instruction
*> &CI
)
94 : StartValue(Start
), LoopExitInstr(Exit
), Kind(K
), MinMaxKind(MK
),
95 UnsafeAlgebraInst(UAI
), RecurrenceType(RT
), IsSigned(Signed
) {
96 CastInsts
.insert(CI
.begin(), CI
.end());
99 /// This POD struct holds information about a potential recurrence operation.
102 InstDesc(bool IsRecur
, Instruction
*I
, Instruction
*UAI
= nullptr)
103 : IsRecurrence(IsRecur
), PatternLastInst(I
), MinMaxKind(MRK_Invalid
),
104 UnsafeAlgebraInst(UAI
) {}
106 InstDesc(Instruction
*I
, MinMaxRecurrenceKind K
, Instruction
*UAI
= nullptr)
107 : IsRecurrence(true), PatternLastInst(I
), MinMaxKind(K
),
108 UnsafeAlgebraInst(UAI
) {}
110 bool isRecurrence() { return IsRecurrence
; }
112 bool hasUnsafeAlgebra() { return UnsafeAlgebraInst
!= nullptr; }
114 Instruction
*getUnsafeAlgebraInst() { return UnsafeAlgebraInst
; }
116 MinMaxRecurrenceKind
getMinMaxKind() { return MinMaxKind
; }
118 Instruction
*getPatternInst() { return PatternLastInst
; }
121 // Is this instruction a recurrence candidate.
123 // The last instruction in a min/max pattern (select of the select(icmp())
124 // pattern), or the current recurrence instruction otherwise.
125 Instruction
*PatternLastInst
;
126 // If this is a min/max pattern the comparison predicate.
127 MinMaxRecurrenceKind MinMaxKind
;
128 // Recurrence has unsafe algebra.
129 Instruction
*UnsafeAlgebraInst
;
132 /// Returns a struct describing if the instruction 'I' can be a recurrence
133 /// variable of type 'Kind'. If the recurrence is a min/max pattern of
134 /// select(icmp()) this function advances the instruction pointer 'I' from the
135 /// compare instruction to the select instruction and stores this pointer in
136 /// 'PatternLastInst' member of the returned struct.
137 static InstDesc
isRecurrenceInstr(Instruction
*I
, RecurrenceKind Kind
,
138 InstDesc
&Prev
, bool HasFunNoNaNAttr
);
140 /// Returns true if instruction I has multiple uses in Insts
141 static bool hasMultipleUsesOf(Instruction
*I
,
142 SmallPtrSetImpl
<Instruction
*> &Insts
,
143 unsigned MaxNumUses
);
145 /// Returns true if all uses of the instruction I is within the Set.
146 static bool areAllUsesIn(Instruction
*I
, SmallPtrSetImpl
<Instruction
*> &Set
);
148 /// Returns a struct describing if the instruction if the instruction is a
149 /// Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y)
151 static InstDesc
isMinMaxSelectCmpPattern(Instruction
*I
, InstDesc
&Prev
);
153 /// Returns a struct describing if the instruction is a
154 /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
155 static InstDesc
isConditionalRdxPattern(RecurrenceKind Kind
, Instruction
*I
);
157 /// Returns identity corresponding to the RecurrenceKind.
158 static Constant
*getRecurrenceIdentity(RecurrenceKind K
, Type
*Tp
);
160 /// Returns the opcode of binary operation corresponding to the
162 static unsigned getRecurrenceBinOp(RecurrenceKind Kind
);
164 /// Returns true if Phi is a reduction of type Kind and adds it to the
165 /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are
166 /// non-null, the minimal bit width needed to compute the reduction will be
168 static bool AddReductionVar(PHINode
*Phi
, RecurrenceKind Kind
, Loop
*TheLoop
,
169 bool HasFunNoNaNAttr
,
170 RecurrenceDescriptor
&RedDes
,
171 DemandedBits
*DB
= nullptr,
172 AssumptionCache
*AC
= nullptr,
173 DominatorTree
*DT
= nullptr);
175 /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor
176 /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are
177 /// non-null, the minimal bit width needed to compute the reduction will be
179 static bool isReductionPHI(PHINode
*Phi
, Loop
*TheLoop
,
180 RecurrenceDescriptor
&RedDes
,
181 DemandedBits
*DB
= nullptr,
182 AssumptionCache
*AC
= nullptr,
183 DominatorTree
*DT
= nullptr);
185 /// Returns true if Phi is a first-order recurrence. A first-order recurrence
186 /// is a non-reduction recurrence relation in which the value of the
187 /// recurrence in the current loop iteration equals a value defined in the
188 /// previous iteration. \p SinkAfter includes pairs of instructions where the
189 /// first will be rescheduled to appear after the second if/when the loop is
190 /// vectorized. It may be augmented with additional pairs if needed in order
191 /// to handle Phi as a first-order recurrence.
193 isFirstOrderRecurrence(PHINode
*Phi
, Loop
*TheLoop
,
194 DenseMap
<Instruction
*, Instruction
*> &SinkAfter
,
197 RecurrenceKind
getRecurrenceKind() { return Kind
; }
199 MinMaxRecurrenceKind
getMinMaxRecurrenceKind() { return MinMaxKind
; }
201 TrackingVH
<Value
> getRecurrenceStartValue() { return StartValue
; }
203 Instruction
*getLoopExitInstr() { return LoopExitInstr
; }
205 /// Returns true if the recurrence has unsafe algebra which requires a relaxed
206 /// floating-point model.
207 bool hasUnsafeAlgebra() { return UnsafeAlgebraInst
!= nullptr; }
209 /// Returns first unsafe algebra instruction in the PHI node's use-chain.
210 Instruction
*getUnsafeAlgebraInst() { return UnsafeAlgebraInst
; }
212 /// Returns true if the recurrence kind is an integer kind.
213 static bool isIntegerRecurrenceKind(RecurrenceKind Kind
);
215 /// Returns true if the recurrence kind is a floating point kind.
216 static bool isFloatingPointRecurrenceKind(RecurrenceKind Kind
);
218 /// Returns true if the recurrence kind is an arithmetic kind.
219 static bool isArithmeticRecurrenceKind(RecurrenceKind Kind
);
221 /// Returns the type of the recurrence. This type can be narrower than the
222 /// actual type of the Phi if the recurrence has been type-promoted.
223 Type
*getRecurrenceType() { return RecurrenceType
; }
225 /// Returns a reference to the instructions used for type-promoting the
227 SmallPtrSet
<Instruction
*, 8> &getCastInsts() { return CastInsts
; }
229 /// Returns true if all source operands of the recurrence are SExtInsts.
230 bool isSigned() { return IsSigned
; }
233 // The starting value of the recurrence.
234 // It does not have to be zero!
235 TrackingVH
<Value
> StartValue
;
236 // The instruction who's value is used outside the loop.
237 Instruction
*LoopExitInstr
= nullptr;
238 // The kind of the recurrence.
239 RecurrenceKind Kind
= RK_NoRecurrence
;
240 // If this a min/max recurrence the kind of recurrence.
241 MinMaxRecurrenceKind MinMaxKind
= MRK_Invalid
;
242 // First occurrence of unasfe algebra in the PHI's use-chain.
243 Instruction
*UnsafeAlgebraInst
= nullptr;
244 // The type of the recurrence.
245 Type
*RecurrenceType
= nullptr;
246 // True if all source operands of the recurrence are SExtInsts.
247 bool IsSigned
= false;
248 // Instructions used for type-promoting the recurrence.
249 SmallPtrSet
<Instruction
*, 8> CastInsts
;
252 /// A struct for saving information about induction variables.
253 class InductionDescriptor
{
255 /// This enum represents the kinds of inductions that we support.
257 IK_NoInduction
, ///< Not an induction variable.
258 IK_IntInduction
, ///< Integer induction variable. Step = C.
259 IK_PtrInduction
, ///< Pointer induction var. Step = C / sizeof(elem).
260 IK_FpInduction
///< Floating point induction variable.
264 /// Default constructor - creates an invalid induction.
265 InductionDescriptor() = default;
267 /// Get the consecutive direction. Returns:
268 /// 0 - unknown or non-consecutive.
269 /// 1 - consecutive and increasing.
270 /// -1 - consecutive and decreasing.
271 int getConsecutiveDirection() const;
273 Value
*getStartValue() const { return StartValue
; }
274 InductionKind
getKind() const { return IK
; }
275 const SCEV
*getStep() const { return Step
; }
276 BinaryOperator
*getInductionBinOp() const { return InductionBinOp
; }
277 ConstantInt
*getConstIntStepValue() const;
279 /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
280 /// induction, the induction descriptor \p D will contain the data describing
281 /// this induction. If by some other means the caller has a better SCEV
282 /// expression for \p Phi than the one returned by the ScalarEvolution
283 /// analysis, it can be passed through \p Expr. If the def-use chain
284 /// associated with the phi includes casts (that we know we can ignore
285 /// under proper runtime checks), they are passed through \p CastsToIgnore.
287 isInductionPHI(PHINode
*Phi
, const Loop
*L
, ScalarEvolution
*SE
,
288 InductionDescriptor
&D
, const SCEV
*Expr
= nullptr,
289 SmallVectorImpl
<Instruction
*> *CastsToIgnore
= nullptr);
291 /// Returns true if \p Phi is a floating point induction in the loop \p L.
292 /// If \p Phi is an induction, the induction descriptor \p D will contain
293 /// the data describing this induction.
294 static bool isFPInductionPHI(PHINode
*Phi
, const Loop
*L
, ScalarEvolution
*SE
,
295 InductionDescriptor
&D
);
297 /// Returns true if \p Phi is a loop \p L induction, in the context associated
298 /// with the run-time predicate of PSE. If \p Assume is true, this can add
299 /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
301 /// If \p Phi is an induction, \p D will contain the data describing this
303 static bool isInductionPHI(PHINode
*Phi
, const Loop
*L
,
304 PredicatedScalarEvolution
&PSE
,
305 InductionDescriptor
&D
, bool Assume
= false);
307 /// Returns true if the induction type is FP and the binary operator does
308 /// not have the "fast-math" property. Such operation requires a relaxed FP
310 bool hasUnsafeAlgebra() {
311 return InductionBinOp
&& !cast
<FPMathOperator
>(InductionBinOp
)->isFast();
314 /// Returns induction operator that does not have "fast-math" property
315 /// and requires FP unsafe mode.
316 Instruction
*getUnsafeAlgebraInst() {
317 if (!InductionBinOp
|| cast
<FPMathOperator
>(InductionBinOp
)->isFast())
319 return InductionBinOp
;
322 /// Returns binary opcode of the induction operator.
323 Instruction::BinaryOps
getInductionOpcode() const {
324 return InductionBinOp
? InductionBinOp
->getOpcode()
325 : Instruction::BinaryOpsEnd
;
328 /// Returns a reference to the type cast instructions in the induction
329 /// update chain, that are redundant when guarded with a runtime
330 /// SCEV overflow check.
331 const SmallVectorImpl
<Instruction
*> &getCastInsts() const {
332 return RedundantCasts
;
336 /// Private constructor - used by \c isInductionPHI.
337 InductionDescriptor(Value
*Start
, InductionKind K
, const SCEV
*Step
,
338 BinaryOperator
*InductionBinOp
= nullptr,
339 SmallVectorImpl
<Instruction
*> *Casts
= nullptr);
342 TrackingVH
<Value
> StartValue
;
344 InductionKind IK
= IK_NoInduction
;
346 const SCEV
*Step
= nullptr;
347 // Instruction that advances induction variable.
348 BinaryOperator
*InductionBinOp
= nullptr;
349 // Instructions used for type-casts of the induction variable,
350 // that are redundant when guarded with a runtime SCEV overflow check.
351 SmallVector
<Instruction
*, 2> RedundantCasts
;
354 } // end namespace llvm
356 #endif // LLVM_ANALYSIS_IVDESCRIPTORS_H