blob: 6bb6c4cae0a2c62cbac5633b44004ec3973436c9 [file] [log] [blame]
Andrew Scull0372a572018-11-16 15:47:06 +00001//===- llvm/Analysis/IVDescriptors.h - IndVar Descriptors -------*- 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 Scull0372a572018-11-16 15:47:06 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file "describes" induction and recurrence variables.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ANALYSIS_IVDESCRIPTORS_H
14#define LLVM_ANALYSIS_IVDESCRIPTORS_H
15
16#include "llvm/ADT/DenseMap.h"
Andrew Scull0372a572018-11-16 15:47:06 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
Andrew Scull0372a572018-11-16 15:47:06 +000020#include "llvm/IR/InstrTypes.h"
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020021#include "llvm/IR/Instruction.h"
Andrew Scull0372a572018-11-16 15:47:06 +000022#include "llvm/IR/Operator.h"
23#include "llvm/IR/ValueHandle.h"
24#include "llvm/Support/Casting.h"
25
26namespace llvm {
27
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020028class DemandedBits;
29class AssumptionCache;
Andrew Scull0372a572018-11-16 15:47:06 +000030class Loop;
Andrew Scull0372a572018-11-16 15:47:06 +000031class PredicatedScalarEvolution;
Andrew Scull0372a572018-11-16 15:47:06 +000032class ScalarEvolution;
33class SCEV;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020034class DominatorTree;
35class ICFLoopSafetyInfo;
36
37/// These are the kinds of recurrences that we support.
38enum class RecurKind {
39 None, ///< Not a recurrence.
40 Add, ///< Sum of integers.
41 Mul, ///< Product of integers.
42 Or, ///< Bitwise or logical OR of integers.
43 And, ///< Bitwise or logical AND of integers.
44 Xor, ///< Bitwise or logical XOR of integers.
45 SMin, ///< Signed integer min implemented in terms of select(cmp()).
46 SMax, ///< Signed integer max implemented in terms of select(cmp()).
47 UMin, ///< Unisgned integer min implemented in terms of select(cmp()).
48 UMax, ///< Unsigned integer max implemented in terms of select(cmp()).
49 FAdd, ///< Sum of floats.
50 FMul, ///< Product of floats.
51 FMin, ///< FP min implemented in terms of select(cmp()).
52 FMax ///< FP max implemented in terms of select(cmp()).
53};
Andrew Scull0372a572018-11-16 15:47:06 +000054
55/// The RecurrenceDescriptor is used to identify recurrences variables in a
56/// loop. Reduction is a special case of recurrence that has uses of the
57/// recurrence variable outside the loop. The method isReductionPHI identifies
58/// reductions that are basic recurrences.
59///
60/// Basic recurrences are defined as the summation, product, OR, AND, XOR, min,
61/// or max of a set of terms. For example: for(i=0; i<n; i++) { total +=
62/// array[i]; } is a summation of array elements. Basic recurrences are a
63/// special case of chains of recurrences (CR). See ScalarEvolution for CR
64/// references.
65
66/// This struct holds information about recurrence variables.
67class RecurrenceDescriptor {
68public:
Andrew Scull0372a572018-11-16 15:47:06 +000069 RecurrenceDescriptor() = default;
70
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020071 RecurrenceDescriptor(Value *Start, Instruction *Exit, RecurKind K,
72 FastMathFlags FMF, Instruction *UAI, Type *RT,
73 bool Signed, SmallPtrSetImpl<Instruction *> &CI)
Andrew Walbran3d2c1972020-04-07 12:24:26 +010074 : StartValue(Start), LoopExitInstr(Exit), Kind(K), FMF(FMF),
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020075 UnsafeAlgebraInst(UAI), RecurrenceType(RT), IsSigned(Signed) {
Andrew Scull0372a572018-11-16 15:47:06 +000076 CastInsts.insert(CI.begin(), CI.end());
77 }
78
79 /// This POD struct holds information about a potential recurrence operation.
80 class InstDesc {
81 public:
82 InstDesc(bool IsRecur, Instruction *I, Instruction *UAI = nullptr)
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020083 : IsRecurrence(IsRecur), PatternLastInst(I),
84 RecKind(RecurKind::None), UnsafeAlgebraInst(UAI) {}
85
86 InstDesc(Instruction *I, RecurKind K, Instruction *UAI = nullptr)
87 : IsRecurrence(true), PatternLastInst(I), RecKind(K),
Andrew Scull0372a572018-11-16 15:47:06 +000088 UnsafeAlgebraInst(UAI) {}
89
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020090 bool isRecurrence() const { return IsRecurrence; }
Andrew Scull0372a572018-11-16 15:47:06 +000091
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020092 bool hasUnsafeAlgebra() const { return UnsafeAlgebraInst != nullptr; }
Andrew Scull0372a572018-11-16 15:47:06 +000093
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020094 Instruction *getUnsafeAlgebraInst() const { return UnsafeAlgebraInst; }
Andrew Scull0372a572018-11-16 15:47:06 +000095
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020096 RecurKind getRecKind() const { return RecKind; }
Andrew Scull0372a572018-11-16 15:47:06 +000097
Olivier Deprezf4ef2d02021-04-20 13:36:24 +020098 Instruction *getPatternInst() const { return PatternLastInst; }
Andrew Scull0372a572018-11-16 15:47:06 +000099
100 private:
101 // Is this instruction a recurrence candidate.
102 bool IsRecurrence;
103 // The last instruction in a min/max pattern (select of the select(icmp())
104 // pattern), or the current recurrence instruction otherwise.
105 Instruction *PatternLastInst;
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200106 // If this is a min/max pattern.
107 RecurKind RecKind;
Andrew Scull0372a572018-11-16 15:47:06 +0000108 // Recurrence has unsafe algebra.
109 Instruction *UnsafeAlgebraInst;
110 };
111
112 /// Returns a struct describing if the instruction 'I' can be a recurrence
113 /// variable of type 'Kind'. If the recurrence is a min/max pattern of
114 /// select(icmp()) this function advances the instruction pointer 'I' from the
115 /// compare instruction to the select instruction and stores this pointer in
116 /// 'PatternLastInst' member of the returned struct.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200117 static InstDesc isRecurrenceInstr(Instruction *I, RecurKind Kind,
Andrew Scull0372a572018-11-16 15:47:06 +0000118 InstDesc &Prev, bool HasFunNoNaNAttr);
119
120 /// Returns true if instruction I has multiple uses in Insts
121 static bool hasMultipleUsesOf(Instruction *I,
Andrew Walbran16937d02019-10-22 13:54:20 +0100122 SmallPtrSetImpl<Instruction *> &Insts,
123 unsigned MaxNumUses);
Andrew Scull0372a572018-11-16 15:47:06 +0000124
125 /// Returns true if all uses of the instruction I is within the Set.
126 static bool areAllUsesIn(Instruction *I, SmallPtrSetImpl<Instruction *> &Set);
127
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200128 /// Returns a struct describing if the instruction is a
Andrew Scull0372a572018-11-16 15:47:06 +0000129 /// Select(ICmp(X, Y), X, Y) instruction pattern corresponding to a min(X, Y)
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200130 /// or max(X, Y). \p Prev specifies the description of an already processed
131 /// select instruction, so its corresponding cmp can be matched to it.
132 static InstDesc isMinMaxSelectCmpPattern(Instruction *I,
133 const InstDesc &Prev);
Andrew Scull0372a572018-11-16 15:47:06 +0000134
Andrew Walbran16937d02019-10-22 13:54:20 +0100135 /// Returns a struct describing if the instruction is a
136 /// Select(FCmp(X, Y), (Z = X op PHINode), PHINode) instruction pattern.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200137 static InstDesc isConditionalRdxPattern(RecurKind Kind, Instruction *I);
Andrew Walbran16937d02019-10-22 13:54:20 +0100138
Andrew Scull0372a572018-11-16 15:47:06 +0000139 /// Returns identity corresponding to the RecurrenceKind.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200140 static Constant *getRecurrenceIdentity(RecurKind K, Type *Tp);
Andrew Scull0372a572018-11-16 15:47:06 +0000141
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200142 /// Returns the opcode corresponding to the RecurrenceKind.
143 static unsigned getOpcode(RecurKind Kind);
Andrew Scull0372a572018-11-16 15:47:06 +0000144
145 /// Returns true if Phi is a reduction of type Kind and adds it to the
146 /// RecurrenceDescriptor. If either \p DB is non-null or \p AC and \p DT are
147 /// non-null, the minimal bit width needed to compute the reduction will be
148 /// computed.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200149 static bool AddReductionVar(PHINode *Phi, RecurKind Kind, Loop *TheLoop,
Andrew Scull0372a572018-11-16 15:47:06 +0000150 bool HasFunNoNaNAttr,
151 RecurrenceDescriptor &RedDes,
152 DemandedBits *DB = nullptr,
153 AssumptionCache *AC = nullptr,
154 DominatorTree *DT = nullptr);
155
156 /// Returns true if Phi is a reduction in TheLoop. The RecurrenceDescriptor
157 /// is returned in RedDes. If either \p DB is non-null or \p AC and \p DT are
158 /// non-null, the minimal bit width needed to compute the reduction will be
159 /// computed.
160 static bool isReductionPHI(PHINode *Phi, Loop *TheLoop,
161 RecurrenceDescriptor &RedDes,
162 DemandedBits *DB = nullptr,
163 AssumptionCache *AC = nullptr,
164 DominatorTree *DT = nullptr);
165
166 /// Returns true if Phi is a first-order recurrence. A first-order recurrence
167 /// is a non-reduction recurrence relation in which the value of the
168 /// recurrence in the current loop iteration equals a value defined in the
169 /// previous iteration. \p SinkAfter includes pairs of instructions where the
170 /// first will be rescheduled to appear after the second if/when the loop is
171 /// vectorized. It may be augmented with additional pairs if needed in order
172 /// to handle Phi as a first-order recurrence.
173 static bool
174 isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
175 DenseMap<Instruction *, Instruction *> &SinkAfter,
176 DominatorTree *DT);
177
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200178 RecurKind getRecurrenceKind() const { return Kind; }
Andrew Scull0372a572018-11-16 15:47:06 +0000179
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200180 unsigned getOpcode() const { return getOpcode(getRecurrenceKind()); }
Andrew Scull0372a572018-11-16 15:47:06 +0000181
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200182 FastMathFlags getFastMathFlags() const { return FMF; }
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100183
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200184 TrackingVH<Value> getRecurrenceStartValue() const { return StartValue; }
Andrew Scull0372a572018-11-16 15:47:06 +0000185
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200186 Instruction *getLoopExitInstr() const { return LoopExitInstr; }
Andrew Scull0372a572018-11-16 15:47:06 +0000187
188 /// Returns true if the recurrence has unsafe algebra which requires a relaxed
189 /// floating-point model.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200190 bool hasUnsafeAlgebra() const { return UnsafeAlgebraInst != nullptr; }
Andrew Scull0372a572018-11-16 15:47:06 +0000191
192 /// Returns first unsafe algebra instruction in the PHI node's use-chain.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200193 Instruction *getUnsafeAlgebraInst() const { return UnsafeAlgebraInst; }
Andrew Scull0372a572018-11-16 15:47:06 +0000194
195 /// Returns true if the recurrence kind is an integer kind.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200196 static bool isIntegerRecurrenceKind(RecurKind Kind);
Andrew Scull0372a572018-11-16 15:47:06 +0000197
198 /// Returns true if the recurrence kind is a floating point kind.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200199 static bool isFloatingPointRecurrenceKind(RecurKind Kind);
Andrew Scull0372a572018-11-16 15:47:06 +0000200
201 /// Returns true if the recurrence kind is an arithmetic kind.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200202 static bool isArithmeticRecurrenceKind(RecurKind Kind);
203
204 /// Returns true if the recurrence kind is an integer min/max kind.
205 static bool isIntMinMaxRecurrenceKind(RecurKind Kind) {
206 return Kind == RecurKind::UMin || Kind == RecurKind::UMax ||
207 Kind == RecurKind::SMin || Kind == RecurKind::SMax;
208 }
209
210 /// Returns true if the recurrence kind is a floating-point min/max kind.
211 static bool isFPMinMaxRecurrenceKind(RecurKind Kind) {
212 return Kind == RecurKind::FMin || Kind == RecurKind::FMax;
213 }
214
215 /// Returns true if the recurrence kind is any min/max kind.
216 static bool isMinMaxRecurrenceKind(RecurKind Kind) {
217 return isIntMinMaxRecurrenceKind(Kind) || isFPMinMaxRecurrenceKind(Kind);
218 }
Andrew Scull0372a572018-11-16 15:47:06 +0000219
220 /// Returns the type of the recurrence. This type can be narrower than the
221 /// actual type of the Phi if the recurrence has been type-promoted.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200222 Type *getRecurrenceType() const { return RecurrenceType; }
Andrew Scull0372a572018-11-16 15:47:06 +0000223
224 /// Returns a reference to the instructions used for type-promoting the
225 /// recurrence.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200226 const SmallPtrSet<Instruction *, 8> &getCastInsts() const { return CastInsts; }
Andrew Scull0372a572018-11-16 15:47:06 +0000227
228 /// Returns true if all source operands of the recurrence are SExtInsts.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200229 bool isSigned() const { return IsSigned; }
230
231 /// Attempts to find a chain of operations from Phi to LoopExitInst that can
232 /// be treated as a set of reductions instructions for in-loop reductions.
233 SmallVector<Instruction *, 4> getReductionOpChain(PHINode *Phi,
234 Loop *L) const;
Andrew Scull0372a572018-11-16 15:47:06 +0000235
236private:
237 // The starting value of the recurrence.
238 // It does not have to be zero!
239 TrackingVH<Value> StartValue;
240 // The instruction who's value is used outside the loop.
241 Instruction *LoopExitInstr = nullptr;
242 // The kind of the recurrence.
Olivier Deprezf4ef2d02021-04-20 13:36:24 +0200243 RecurKind Kind = RecurKind::None;
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100244 // The fast-math flags on the recurrent instructions. We propagate these
245 // fast-math flags into the vectorized FP instructions we generate.
246 FastMathFlags FMF;
Andrew Scull0372a572018-11-16 15:47:06 +0000247 // First occurrence of unasfe algebra in the PHI's use-chain.
248 Instruction *UnsafeAlgebraInst = nullptr;
249 // The type of the recurrence.
250 Type *RecurrenceType = nullptr;
251 // True if all source operands of the recurrence are SExtInsts.
252 bool IsSigned = false;
253 // Instructions used for type-promoting the recurrence.
254 SmallPtrSet<Instruction *, 8> CastInsts;
255};
256
257/// A struct for saving information about induction variables.
258class InductionDescriptor {
259public:
260 /// This enum represents the kinds of inductions that we support.
261 enum InductionKind {
262 IK_NoInduction, ///< Not an induction variable.
263 IK_IntInduction, ///< Integer induction variable. Step = C.
264 IK_PtrInduction, ///< Pointer induction var. Step = C / sizeof(elem).
265 IK_FpInduction ///< Floating point induction variable.
266 };
267
268public:
269 /// Default constructor - creates an invalid induction.
270 InductionDescriptor() = default;
271
Andrew Scull0372a572018-11-16 15:47:06 +0000272 Value *getStartValue() const { return StartValue; }
273 InductionKind getKind() const { return IK; }
274 const SCEV *getStep() const { return Step; }
275 BinaryOperator *getInductionBinOp() const { return InductionBinOp; }
276 ConstantInt *getConstIntStepValue() const;
277
278 /// Returns true if \p Phi is an induction in the loop \p L. If \p Phi is an
279 /// induction, the induction descriptor \p D will contain the data describing
280 /// this induction. If by some other means the caller has a better SCEV
281 /// expression for \p Phi than the one returned by the ScalarEvolution
282 /// analysis, it can be passed through \p Expr. If the def-use chain
283 /// associated with the phi includes casts (that we know we can ignore
284 /// under proper runtime checks), they are passed through \p CastsToIgnore.
285 static bool
286 isInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
287 InductionDescriptor &D, const SCEV *Expr = nullptr,
288 SmallVectorImpl<Instruction *> *CastsToIgnore = nullptr);
289
290 /// Returns true if \p Phi is a floating point induction in the loop \p L.
291 /// If \p Phi is an induction, the induction descriptor \p D will contain
292 /// the data describing this induction.
293 static bool isFPInductionPHI(PHINode *Phi, const Loop *L, ScalarEvolution *SE,
294 InductionDescriptor &D);
295
296 /// Returns true if \p Phi is a loop \p L induction, in the context associated
297 /// with the run-time predicate of PSE. If \p Assume is true, this can add
298 /// further SCEV predicates to \p PSE in order to prove that \p Phi is an
299 /// induction.
300 /// If \p Phi is an induction, \p D will contain the data describing this
301 /// induction.
302 static bool isInductionPHI(PHINode *Phi, const Loop *L,
303 PredicatedScalarEvolution &PSE,
304 InductionDescriptor &D, bool Assume = false);
305
306 /// Returns true if the induction type is FP and the binary operator does
307 /// not have the "fast-math" property. Such operation requires a relaxed FP
308 /// mode.
309 bool hasUnsafeAlgebra() {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100310 return (IK == IK_FpInduction) && InductionBinOp &&
311 !cast<FPMathOperator>(InductionBinOp)->isFast();
Andrew Scull0372a572018-11-16 15:47:06 +0000312 }
313
314 /// Returns induction operator that does not have "fast-math" property
315 /// and requires FP unsafe mode.
316 Instruction *getUnsafeAlgebraInst() {
Andrew Walbran3d2c1972020-04-07 12:24:26 +0100317 if (IK != IK_FpInduction)
318 return nullptr;
319
Andrew Scull0372a572018-11-16 15:47:06 +0000320 if (!InductionBinOp || cast<FPMathOperator>(InductionBinOp)->isFast())
321 return nullptr;
322 return InductionBinOp;
323 }
324
325 /// Returns binary opcode of the induction operator.
326 Instruction::BinaryOps getInductionOpcode() const {
327 return InductionBinOp ? InductionBinOp->getOpcode()
328 : Instruction::BinaryOpsEnd;
329 }
330
331 /// Returns a reference to the type cast instructions in the induction
332 /// update chain, that are redundant when guarded with a runtime
333 /// SCEV overflow check.
334 const SmallVectorImpl<Instruction *> &getCastInsts() const {
335 return RedundantCasts;
336 }
337
338private:
339 /// Private constructor - used by \c isInductionPHI.
340 InductionDescriptor(Value *Start, InductionKind K, const SCEV *Step,
341 BinaryOperator *InductionBinOp = nullptr,
342 SmallVectorImpl<Instruction *> *Casts = nullptr);
343
344 /// Start value.
345 TrackingVH<Value> StartValue;
346 /// Induction kind.
347 InductionKind IK = IK_NoInduction;
348 /// Step value.
349 const SCEV *Step = nullptr;
350 // Instruction that advances induction variable.
351 BinaryOperator *InductionBinOp = nullptr;
352 // Instructions used for type-casts of the induction variable,
353 // that are redundant when guarded with a runtime SCEV overflow check.
354 SmallVector<Instruction *, 2> RedundantCasts;
355};
356
357} // end namespace llvm
358
359#endif // LLVM_ANALYSIS_IVDESCRIPTORS_H