1 //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file "describes" induction and recurrence variables.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/IVDescriptors.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/Analysis/AliasAnalysis.h"
16 #include "llvm/Analysis/BasicAliasAnalysis.h"
17 #include "llvm/Analysis/DemandedBits.h"
18 #include "llvm/Analysis/DomTreeUpdater.h"
19 #include "llvm/Analysis/GlobalsModRef.h"
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/MustExecute.h"
24 #include "llvm/Analysis/ScalarEvolution.h"
25 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
26 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
27 #include "llvm/Analysis/TargetTransformInfo.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/KnownBits.h"
37 
38 using namespace llvm;
39 using namespace llvm::PatternMatch;
40 
41 #define DEBUG_TYPE "iv-descriptors"
42 
43 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
44                                         SmallPtrSetImpl<Instruction *> &Set) {
45   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
46     if (!Set.count(dyn_cast<Instruction>(*Use)))
47       return false;
48   return true;
49 }
50 
51 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
52   switch (Kind) {
53   default:
54     break;
55   case RK_IntegerAdd:
56   case RK_IntegerMult:
57   case RK_IntegerOr:
58   case RK_IntegerAnd:
59   case RK_IntegerXor:
60   case RK_IntegerMinMax:
61     return true;
62   }
63   return false;
64 }
65 
66 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
67   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
68 }
69 
70 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
71   switch (Kind) {
72   default:
73     break;
74   case RK_IntegerAdd:
75   case RK_IntegerMult:
76   case RK_FloatAdd:
77   case RK_FloatMult:
78     return true;
79   }
80   return false;
81 }
82 
83 /// Determines if Phi may have been type-promoted. If Phi has a single user
84 /// that ANDs the Phi with a type mask, return the user. RT is updated to
85 /// account for the narrower bit width represented by the mask, and the AND
86 /// instruction is added to CI.
87 static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
88                                    SmallPtrSetImpl<Instruction *> &Visited,
89                                    SmallPtrSetImpl<Instruction *> &CI) {
90   if (!Phi->hasOneUse())
91     return Phi;
92 
93   const APInt *M = nullptr;
94   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
95 
96   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
97   // with a new integer type of the corresponding bit width.
98   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
99     int32_t Bits = (*M + 1).exactLogBase2();
100     if (Bits > 0) {
101       RT = IntegerType::get(Phi->getContext(), Bits);
102       Visited.insert(Phi);
103       CI.insert(J);
104       return J;
105     }
106   }
107   return Phi;
108 }
109 
110 /// Compute the minimal bit width needed to represent a reduction whose exit
111 /// instruction is given by Exit.
112 static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
113                                                      DemandedBits *DB,
114                                                      AssumptionCache *AC,
115                                                      DominatorTree *DT) {
116   bool IsSigned = false;
117   const DataLayout &DL = Exit->getModule()->getDataLayout();
118   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
119 
120   if (DB) {
121     // Use the demanded bits analysis to determine the bits that are live out
122     // of the exit instruction, rounding up to the nearest power of two. If the
123     // use of demanded bits results in a smaller bit width, we know the value
124     // must be positive (i.e., IsSigned = false), because if this were not the
125     // case, the sign bit would have been demanded.
126     auto Mask = DB->getDemandedBits(Exit);
127     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
128   }
129 
130   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
131     // If demanded bits wasn't able to limit the bit width, we can try to use
132     // value tracking instead. This can be the case, for example, if the value
133     // may be negative.
134     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
135     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
136     MaxBitWidth = NumTypeBits - NumSignBits;
137     KnownBits Bits = computeKnownBits(Exit, DL);
138     if (!Bits.isNonNegative()) {
139       // If the value is not known to be non-negative, we set IsSigned to true,
140       // meaning that we will use sext instructions instead of zext
141       // instructions to restore the original type.
142       IsSigned = true;
143       if (!Bits.isNegative())
144         // If the value is not known to be negative, we don't known what the
145         // upper bit is, and therefore, we don't know what kind of extend we
146         // will need. In this case, just increase the bit width by one bit and
147         // use sext.
148         ++MaxBitWidth;
149     }
150   }
151   if (!isPowerOf2_64(MaxBitWidth))
152     MaxBitWidth = NextPowerOf2(MaxBitWidth);
153 
154   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
155                         IsSigned);
156 }
157 
158 /// Collect cast instructions that can be ignored in the vectorizer's cost
159 /// model, given a reduction exit value and the minimal type in which the
160 /// reduction can be represented.
161 static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
162                                  Type *RecurrenceType,
163                                  SmallPtrSetImpl<Instruction *> &Casts) {
164 
165   SmallVector<Instruction *, 8> Worklist;
166   SmallPtrSet<Instruction *, 8> Visited;
167   Worklist.push_back(Exit);
168 
169   while (!Worklist.empty()) {
170     Instruction *Val = Worklist.pop_back_val();
171     Visited.insert(Val);
172     if (auto *Cast = dyn_cast<CastInst>(Val))
173       if (Cast->getSrcTy() == RecurrenceType) {
174         // If the source type of a cast instruction is equal to the recurrence
175         // type, it will be eliminated, and should be ignored in the vectorizer
176         // cost model.
177         Casts.insert(Cast);
178         continue;
179       }
180 
181     // Add all operands to the work list if they are loop-varying values that
182     // we haven't yet visited.
183     for (Value *O : cast<User>(Val)->operands())
184       if (auto *I = dyn_cast<Instruction>(O))
185         if (TheLoop->contains(I) && !Visited.count(I))
186           Worklist.push_back(I);
187   }
188 }
189 
190 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
191                                            Loop *TheLoop, bool HasFunNoNaNAttr,
192                                            RecurrenceDescriptor &RedDes,
193                                            DemandedBits *DB,
194                                            AssumptionCache *AC,
195                                            DominatorTree *DT) {
196   if (Phi->getNumIncomingValues() != 2)
197     return false;
198 
199   // Reduction variables are only found in the loop header block.
200   if (Phi->getParent() != TheLoop->getHeader())
201     return false;
202 
203   // Obtain the reduction start value from the value that comes from the loop
204   // preheader.
205   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
206 
207   // ExitInstruction is the single value which is used outside the loop.
208   // We only allow for a single reduction value to be used outside the loop.
209   // This includes users of the reduction, variables (which form a cycle
210   // which ends in the phi node).
211   Instruction *ExitInstruction = nullptr;
212   // Indicates that we found a reduction operation in our scan.
213   bool FoundReduxOp = false;
214 
215   // We start with the PHI node and scan for all of the users of this
216   // instruction. All users must be instructions that can be used as reduction
217   // variables (such as ADD). We must have a single out-of-block user. The cycle
218   // must include the original PHI.
219   bool FoundStartPHI = false;
220 
221   // To recognize min/max patterns formed by a icmp select sequence, we store
222   // the number of instruction we saw from the recognized min/max pattern,
223   //  to make sure we only see exactly the two instructions.
224   unsigned NumCmpSelectPatternInst = 0;
225   InstDesc ReduxDesc(false, nullptr);
226 
227   // Data used for determining if the recurrence has been type-promoted.
228   Type *RecurrenceType = Phi->getType();
229   SmallPtrSet<Instruction *, 4> CastInsts;
230   Instruction *Start = Phi;
231   bool IsSigned = false;
232 
233   SmallPtrSet<Instruction *, 8> VisitedInsts;
234   SmallVector<Instruction *, 8> Worklist;
235 
236   // Return early if the recurrence kind does not match the type of Phi. If the
237   // recurrence kind is arithmetic, we attempt to look through AND operations
238   // resulting from the type promotion performed by InstCombine.  Vector
239   // operations are not limited to the legal integer widths, so we may be able
240   // to evaluate the reduction in the narrower width.
241   if (RecurrenceType->isFloatingPointTy()) {
242     if (!isFloatingPointRecurrenceKind(Kind))
243       return false;
244   } else {
245     if (!isIntegerRecurrenceKind(Kind))
246       return false;
247     if (isArithmeticRecurrenceKind(Kind))
248       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
249   }
250 
251   Worklist.push_back(Start);
252   VisitedInsts.insert(Start);
253 
254   // Start with all flags set because we will intersect this with the reduction
255   // flags from all the reduction operations.
256   FastMathFlags FMF = FastMathFlags::getFast();
257 
258   // A value in the reduction can be used:
259   //  - By the reduction:
260   //      - Reduction operation:
261   //        - One use of reduction value (safe).
262   //        - Multiple use of reduction value (not safe).
263   //      - PHI:
264   //        - All uses of the PHI must be the reduction (safe).
265   //        - Otherwise, not safe.
266   //  - By instructions outside of the loop (safe).
267   //      * One value may have several outside users, but all outside
268   //        uses must be of the same value.
269   //  - By an instruction that is not part of the reduction (not safe).
270   //    This is either:
271   //      * An instruction type other than PHI or the reduction operation.
272   //      * A PHI in the header other than the initial PHI.
273   while (!Worklist.empty()) {
274     Instruction *Cur = Worklist.back();
275     Worklist.pop_back();
276 
277     // No Users.
278     // If the instruction has no users then this is a broken chain and can't be
279     // a reduction variable.
280     if (Cur->use_empty())
281       return false;
282 
283     bool IsAPhi = isa<PHINode>(Cur);
284 
285     // A header PHI use other than the original PHI.
286     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
287       return false;
288 
289     // Reductions of instructions such as Div, and Sub is only possible if the
290     // LHS is the reduction variable.
291     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
292         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
293         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
294       return false;
295 
296     // Any reduction instruction must be of one of the allowed kinds. We ignore
297     // the starting value (the Phi or an AND instruction if the Phi has been
298     // type-promoted).
299     if (Cur != Start) {
300       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
301       if (!ReduxDesc.isRecurrence())
302         return false;
303       // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
304       if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi)
305         FMF &= ReduxDesc.getPatternInst()->getFastMathFlags();
306     }
307 
308     bool IsASelect = isa<SelectInst>(Cur);
309 
310     // A conditional reduction operation must only have 2 or less uses in
311     // VisitedInsts.
312     if (IsASelect && (Kind == RK_FloatAdd || Kind == RK_FloatMult) &&
313         hasMultipleUsesOf(Cur, VisitedInsts, 2))
314       return false;
315 
316     // A reduction operation must only have one use of the reduction value.
317     if (!IsAPhi && !IsASelect && Kind != RK_IntegerMinMax &&
318         Kind != RK_FloatMinMax && hasMultipleUsesOf(Cur, VisitedInsts, 1))
319       return false;
320 
321     // All inputs to a PHI node must be a reduction value.
322     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
323       return false;
324 
325     if (Kind == RK_IntegerMinMax &&
326         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
327       ++NumCmpSelectPatternInst;
328     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
329       ++NumCmpSelectPatternInst;
330 
331     // Check  whether we found a reduction operator.
332     FoundReduxOp |= !IsAPhi && Cur != Start;
333 
334     // Process users of current instruction. Push non-PHI nodes after PHI nodes
335     // onto the stack. This way we are going to have seen all inputs to PHI
336     // nodes once we get to them.
337     SmallVector<Instruction *, 8> NonPHIs;
338     SmallVector<Instruction *, 8> PHIs;
339     for (User *U : Cur->users()) {
340       Instruction *UI = cast<Instruction>(U);
341 
342       // Check if we found the exit user.
343       BasicBlock *Parent = UI->getParent();
344       if (!TheLoop->contains(Parent)) {
345         // If we already know this instruction is used externally, move on to
346         // the next user.
347         if (ExitInstruction == Cur)
348           continue;
349 
350         // Exit if you find multiple values used outside or if the header phi
351         // node is being used. In this case the user uses the value of the
352         // previous iteration, in which case we would loose "VF-1" iterations of
353         // the reduction operation if we vectorize.
354         if (ExitInstruction != nullptr || Cur == Phi)
355           return false;
356 
357         // The instruction used by an outside user must be the last instruction
358         // before we feed back to the reduction phi. Otherwise, we loose VF-1
359         // operations on the value.
360         if (!is_contained(Phi->operands(), Cur))
361           return false;
362 
363         ExitInstruction = Cur;
364         continue;
365       }
366 
367       // Process instructions only once (termination). Each reduction cycle
368       // value must only be used once, except by phi nodes and min/max
369       // reductions which are represented as a cmp followed by a select.
370       InstDesc IgnoredVal(false, nullptr);
371       if (VisitedInsts.insert(UI).second) {
372         if (isa<PHINode>(UI))
373           PHIs.push_back(UI);
374         else
375           NonPHIs.push_back(UI);
376       } else if (!isa<PHINode>(UI) &&
377                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
378                    !isa<SelectInst>(UI)) ||
379                   (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
380                    !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence())))
381         return false;
382 
383       // Remember that we completed the cycle.
384       if (UI == Phi)
385         FoundStartPHI = true;
386     }
387     Worklist.append(PHIs.begin(), PHIs.end());
388     Worklist.append(NonPHIs.begin(), NonPHIs.end());
389   }
390 
391   // This means we have seen one but not the other instruction of the
392   // pattern or more than just a select and cmp.
393   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
394       NumCmpSelectPatternInst != 2)
395     return false;
396 
397   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
398     return false;
399 
400   if (Start != Phi) {
401     // If the starting value is not the same as the phi node, we speculatively
402     // looked through an 'and' instruction when evaluating a potential
403     // arithmetic reduction to determine if it may have been type-promoted.
404     //
405     // We now compute the minimal bit width that is required to represent the
406     // reduction. If this is the same width that was indicated by the 'and', we
407     // can represent the reduction in the smaller type. The 'and' instruction
408     // will be eliminated since it will essentially be a cast instruction that
409     // can be ignore in the cost model. If we compute a different type than we
410     // did when evaluating the 'and', the 'and' will not be eliminated, and we
411     // will end up with different kinds of operations in the recurrence
412     // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
413     // the case.
414     //
415     // The vectorizer relies on InstCombine to perform the actual
416     // type-shrinking. It does this by inserting instructions to truncate the
417     // exit value of the reduction to the width indicated by RecurrenceType and
418     // then extend this value back to the original width. If IsSigned is false,
419     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
420     // used.
421     //
422     // TODO: We should not rely on InstCombine to rewrite the reduction in the
423     //       smaller type. We should just generate a correctly typed expression
424     //       to begin with.
425     Type *ComputedType;
426     std::tie(ComputedType, IsSigned) =
427         computeRecurrenceType(ExitInstruction, DB, AC, DT);
428     if (ComputedType != RecurrenceType)
429       return false;
430 
431     // The recurrence expression will be represented in a narrower type. If
432     // there are any cast instructions that will be unnecessary, collect them
433     // in CastInsts. Note that the 'and' instruction was already included in
434     // this list.
435     //
436     // TODO: A better way to represent this may be to tag in some way all the
437     //       instructions that are a part of the reduction. The vectorizer cost
438     //       model could then apply the recurrence type to these instructions,
439     //       without needing a white list of instructions to ignore.
440     //       This may also be useful for the inloop reductions, if it can be
441     //       kept simple enough.
442     collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
443   }
444 
445   // We found a reduction var if we have reached the original phi node and we
446   // only have a single instruction with out-of-loop users.
447 
448   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
449   // is saved as part of the RecurrenceDescriptor.
450 
451   // Save the description of this reduction variable.
452   RecurrenceDescriptor RD(
453       RdxStart, ExitInstruction, Kind, FMF, ReduxDesc.getMinMaxKind(),
454       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
455   RedDes = RD;
456 
457   return true;
458 }
459 
460 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
461 /// pattern corresponding to a min(X, Y) or max(X, Y).
462 RecurrenceDescriptor::InstDesc
463 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
464 
465   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
466          "Expect a select instruction");
467   Instruction *Cmp = nullptr;
468   SelectInst *Select = nullptr;
469 
470   // We must handle the select(cmp()) as a single instruction. Advance to the
471   // select.
472   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
473     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
474       return InstDesc(false, I);
475     return InstDesc(Select, Prev.getMinMaxKind());
476   }
477 
478   // Only handle single use cases for now.
479   if (!(Select = dyn_cast<SelectInst>(I)))
480     return InstDesc(false, I);
481   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
482       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
483     return InstDesc(false, I);
484   if (!Cmp->hasOneUse())
485     return InstDesc(false, I);
486 
487   Value *CmpLeft;
488   Value *CmpRight;
489 
490   // Look for a min/max pattern.
491   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
492     return InstDesc(Select, MRK_UIntMin);
493   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
494     return InstDesc(Select, MRK_UIntMax);
495   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
496     return InstDesc(Select, MRK_SIntMax);
497   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
498     return InstDesc(Select, MRK_SIntMin);
499   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
500     return InstDesc(Select, MRK_FloatMin);
501   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
502     return InstDesc(Select, MRK_FloatMax);
503   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
504     return InstDesc(Select, MRK_FloatMin);
505   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
506     return InstDesc(Select, MRK_FloatMax);
507 
508   return InstDesc(false, I);
509 }
510 
511 /// Returns true if the select instruction has users in the compare-and-add
512 /// reduction pattern below. The select instruction argument is the last one
513 /// in the sequence.
514 ///
515 /// %sum.1 = phi ...
516 /// ...
517 /// %cmp = fcmp pred %0, %CFP
518 /// %add = fadd %0, %sum.1
519 /// %sum.2 = select %cmp, %add, %sum.1
520 RecurrenceDescriptor::InstDesc
521 RecurrenceDescriptor::isConditionalRdxPattern(
522     RecurrenceKind Kind, Instruction *I) {
523   SelectInst *SI = dyn_cast<SelectInst>(I);
524   if (!SI)
525     return InstDesc(false, I);
526 
527   CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
528   // Only handle single use cases for now.
529   if (!CI || !CI->hasOneUse())
530     return InstDesc(false, I);
531 
532   Value *TrueVal = SI->getTrueValue();
533   Value *FalseVal = SI->getFalseValue();
534   // Handle only when either of operands of select instruction is a PHI
535   // node for now.
536   if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
537       (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
538     return InstDesc(false, I);
539 
540   Instruction *I1 =
541       isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
542                              : dyn_cast<Instruction>(TrueVal);
543   if (!I1 || !I1->isBinaryOp())
544     return InstDesc(false, I);
545 
546   Value *Op1, *Op2;
547   if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1)  ||
548        m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
549       I1->isFast())
550     return InstDesc(Kind == RK_FloatAdd, SI);
551 
552   if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
553     return InstDesc(Kind == RK_FloatMult, SI);
554 
555   return InstDesc(false, I);
556 }
557 
558 RecurrenceDescriptor::InstDesc
559 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
560                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
561   Instruction *UAI = Prev.getUnsafeAlgebraInst();
562   if (!UAI && isa<FPMathOperator>(I) && !I->hasAllowReassoc())
563     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
564 
565   switch (I->getOpcode()) {
566   default:
567     return InstDesc(false, I);
568   case Instruction::PHI:
569     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
570   case Instruction::Sub:
571   case Instruction::Add:
572     return InstDesc(Kind == RK_IntegerAdd, I);
573   case Instruction::Mul:
574     return InstDesc(Kind == RK_IntegerMult, I);
575   case Instruction::And:
576     return InstDesc(Kind == RK_IntegerAnd, I);
577   case Instruction::Or:
578     return InstDesc(Kind == RK_IntegerOr, I);
579   case Instruction::Xor:
580     return InstDesc(Kind == RK_IntegerXor, I);
581   case Instruction::FDiv:
582   case Instruction::FMul:
583     return InstDesc(Kind == RK_FloatMult, I, UAI);
584   case Instruction::FSub:
585   case Instruction::FAdd:
586     return InstDesc(Kind == RK_FloatAdd, I, UAI);
587   case Instruction::Select:
588     if (Kind == RK_FloatAdd || Kind == RK_FloatMult)
589       return isConditionalRdxPattern(Kind, I);
590     LLVM_FALLTHROUGH;
591   case Instruction::FCmp:
592   case Instruction::ICmp:
593     if (Kind != RK_IntegerMinMax &&
594         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
595       return InstDesc(false, I);
596     return isMinMaxSelectCmpPattern(I, Prev);
597   }
598 }
599 
600 bool RecurrenceDescriptor::hasMultipleUsesOf(
601     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
602     unsigned MaxNumUses) {
603   unsigned NumUses = 0;
604   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
605        ++Use) {
606     if (Insts.count(dyn_cast<Instruction>(*Use)))
607       ++NumUses;
608     if (NumUses > MaxNumUses)
609       return true;
610   }
611 
612   return false;
613 }
614 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
615                                           RecurrenceDescriptor &RedDes,
616                                           DemandedBits *DB, AssumptionCache *AC,
617                                           DominatorTree *DT) {
618 
619   BasicBlock *Header = TheLoop->getHeader();
620   Function &F = *Header->getParent();
621   bool HasFunNoNaNAttr =
622       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
623 
624   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
625                       AC, DT)) {
626     LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
627     return true;
628   }
629   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
630                       AC, DT)) {
631     LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
632     return true;
633   }
634   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
635                       AC, DT)) {
636     LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
637     return true;
638   }
639   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
640                       AC, DT)) {
641     LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
642     return true;
643   }
644   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
645                       AC, DT)) {
646     LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
647     return true;
648   }
649   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
650                       DB, AC, DT)) {
651     LLVM_DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
652     return true;
653   }
654   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
655                       AC, DT)) {
656     LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
657     return true;
658   }
659   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
660                       AC, DT)) {
661     LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
662     return true;
663   }
664   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
665                       AC, DT)) {
666     LLVM_DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi
667                       << "\n");
668     return true;
669   }
670   // Not a reduction of known type.
671   return false;
672 }
673 
674 bool RecurrenceDescriptor::isFirstOrderRecurrence(
675     PHINode *Phi, Loop *TheLoop,
676     DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
677 
678   // Ensure the phi node is in the loop header and has two incoming values.
679   if (Phi->getParent() != TheLoop->getHeader() ||
680       Phi->getNumIncomingValues() != 2)
681     return false;
682 
683   // Ensure the loop has a preheader and a single latch block. The loop
684   // vectorizer will need the latch to set up the next iteration of the loop.
685   auto *Preheader = TheLoop->getLoopPreheader();
686   auto *Latch = TheLoop->getLoopLatch();
687   if (!Preheader || !Latch)
688     return false;
689 
690   // Ensure the phi node's incoming blocks are the loop preheader and latch.
691   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
692       Phi->getBasicBlockIndex(Latch) < 0)
693     return false;
694 
695   // Get the previous value. The previous value comes from the latch edge while
696   // the initial value comes form the preheader edge.
697   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
698   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
699       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
700     return false;
701 
702   // Ensure every user of the phi node is dominated by the previous value.
703   // The dominance requirement ensures the loop vectorizer will not need to
704   // vectorize the initial value prior to the first iteration of the loop.
705   // TODO: Consider extending this sinking to handle memory instructions and
706   // phis with multiple users.
707 
708   // Returns true, if all users of I are dominated by DominatedBy.
709   auto allUsesDominatedBy = [DT](Instruction *I, Instruction *DominatedBy) {
710     return all_of(I->uses(), [DT, DominatedBy](Use &U) {
711       return DT->dominates(DominatedBy, U);
712     });
713   };
714 
715   if (Phi->hasOneUse()) {
716     Instruction *I = Phi->user_back();
717 
718     // If the user of the PHI is also the incoming value, we potentially have a
719     // reduction and which cannot be handled by sinking.
720     if (Previous == I)
721       return false;
722 
723     // We cannot sink terminator instructions.
724     if (I->getParent()->getTerminator() == I)
725       return false;
726 
727     // Do not try to sink an instruction multiple times (if multiple operands
728     // are first order recurrences).
729     // TODO: We can support this case, by sinking the instruction after the
730     // 'deepest' previous instruction.
731     if (SinkAfter.find(I) != SinkAfter.end())
732       return false;
733 
734     if (DT->dominates(Previous, I)) // We already are good w/o sinking.
735       return true;
736 
737     // We can sink any instruction without side effects, as long as all users
738     // are dominated by the instruction we are sinking after.
739     if (I->getParent() == Phi->getParent() && !I->mayHaveSideEffects() &&
740         allUsesDominatedBy(I, Previous)) {
741       SinkAfter[I] = Previous;
742       return true;
743     }
744   }
745 
746   return allUsesDominatedBy(Phi, Previous);
747 }
748 
749 /// This function returns the identity element (or neutral element) for
750 /// the operation K.
751 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
752                                                       MinMaxRecurrenceKind MK,
753                                                       Type *Tp) {
754   switch (K) {
755   case RK_IntegerXor:
756   case RK_IntegerAdd:
757   case RK_IntegerOr:
758     // Adding, Xoring, Oring zero to a number does not change it.
759     return ConstantInt::get(Tp, 0);
760   case RK_IntegerMult:
761     // Multiplying a number by 1 does not change it.
762     return ConstantInt::get(Tp, 1);
763   case RK_IntegerAnd:
764     // AND-ing a number with an all-1 value does not change it.
765     return ConstantInt::get(Tp, -1, true);
766   case RK_FloatMult:
767     // Multiplying a number by 1 does not change it.
768     return ConstantFP::get(Tp, 1.0L);
769   case RK_FloatAdd:
770     // Adding zero to a number does not change it.
771     return ConstantFP::get(Tp, 0.0L);
772   case RK_IntegerMinMax:
773   case RK_FloatMinMax:
774     switch (MK) {
775     case MRK_UIntMin:
776       return ConstantInt::get(Tp, -1);
777     case MRK_UIntMax:
778       return ConstantInt::get(Tp, 0);
779     case MRK_SIntMin:
780       return ConstantInt::get(
781           Tp, APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
782     case MRK_SIntMax:
783       return ConstantInt::get(
784           Tp, APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
785     case MRK_FloatMin:
786       return ConstantFP::getInfinity(Tp, true);
787     case MRK_FloatMax:
788       return ConstantFP::getInfinity(Tp, false);
789     default:
790       llvm_unreachable("Unknown recurrence kind");
791     }
792   default:
793     llvm_unreachable("Unknown recurrence kind");
794   }
795 }
796 
797 /// This function translates the recurrence kind to an LLVM binary operator.
798 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
799   switch (Kind) {
800   case RK_IntegerAdd:
801     return Instruction::Add;
802   case RK_IntegerMult:
803     return Instruction::Mul;
804   case RK_IntegerOr:
805     return Instruction::Or;
806   case RK_IntegerAnd:
807     return Instruction::And;
808   case RK_IntegerXor:
809     return Instruction::Xor;
810   case RK_FloatMult:
811     return Instruction::FMul;
812   case RK_FloatAdd:
813     return Instruction::FAdd;
814   case RK_IntegerMinMax:
815     return Instruction::ICmp;
816   case RK_FloatMinMax:
817     return Instruction::FCmp;
818   default:
819     llvm_unreachable("Unknown recurrence operation");
820   }
821 }
822 
823 SmallVector<Instruction *, 4>
824 RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
825   SmallVector<Instruction *, 4> ReductionOperations;
826   unsigned RedOp = getRecurrenceBinOp(Kind);
827 
828   // Search down from the Phi to the LoopExitInstr, looking for instructions
829   // with a single user of the correct type for the reduction.
830 
831   // Note that we check that the type of the operand is correct for each item in
832   // the chain, including the last (the loop exit value). This can come up from
833   // sub, which would otherwise be treated as an add reduction. MinMax also need
834   // to check for a pair of icmp/select, for which we use getNextInstruction and
835   // isCorrectOpcode functions to step the right number of instruction, and
836   // check the icmp/select pair.
837   // FIXME: We also do not attempt to look through Phi/Select's yet, which might
838   // be part of the reduction chain, or attempt to looks through And's to find a
839   // smaller bitwidth. Subs are also currently not allowed (which are usually
840   // treated as part of a add reduction) as they are expected to generally be
841   // more expensive than out-of-loop reductions, and need to be costed more
842   // carefully.
843   unsigned ExpectedUses = 1;
844   if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
845     ExpectedUses = 2;
846 
847   auto getNextInstruction = [&](Instruction *Cur) {
848     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
849       // We are expecting a icmp/select pair, which we go to the next select
850       // instruction if we can. We already know that Cur has 2 uses.
851       if (isa<SelectInst>(*Cur->user_begin()))
852         return cast<Instruction>(*Cur->user_begin());
853       else
854         return cast<Instruction>(*std::next(Cur->user_begin()));
855     }
856     return cast<Instruction>(*Cur->user_begin());
857   };
858   auto isCorrectOpcode = [&](Instruction *Cur) {
859     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
860       Value *LHS, *RHS;
861       return SelectPatternResult::isMinOrMax(
862           matchSelectPattern(Cur, LHS, RHS).Flavor);
863     }
864     return Cur->getOpcode() == RedOp;
865   };
866 
867   // The loop exit instruction we check first (as a quick test) but add last. We
868   // check the opcode is correct (and dont allow them to be Subs) and that they
869   // have expected to have the expected number of uses. They will have one use
870   // from the phi and one from a LCSSA value, no matter the type.
871   if (!isCorrectOpcode(LoopExitInstr) || !LoopExitInstr->hasNUses(2))
872     return {};
873 
874   // Check that the Phi has one (or two for min/max) uses.
875   if (!Phi->hasNUses(ExpectedUses))
876     return {};
877   Instruction *Cur = getNextInstruction(Phi);
878 
879   // Each other instruction in the chain should have the expected number of uses
880   // and be the correct opcode.
881   while (Cur != LoopExitInstr) {
882     if (!isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
883       return {};
884 
885     ReductionOperations.push_back(Cur);
886     Cur = getNextInstruction(Cur);
887   }
888 
889   ReductionOperations.push_back(Cur);
890   return ReductionOperations;
891 }
892 
893 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
894                                          const SCEV *Step, BinaryOperator *BOp,
895                                          SmallVectorImpl<Instruction *> *Casts)
896     : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
897   assert(IK != IK_NoInduction && "Not an induction");
898 
899   // Start value type should match the induction kind and the value
900   // itself should not be null.
901   assert(StartValue && "StartValue is null");
902   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
903          "StartValue is not a pointer for pointer induction");
904   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
905          "StartValue is not an integer for integer induction");
906 
907   // Check the Step Value. It should be non-zero integer value.
908   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
909          "Step value is zero");
910 
911   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
912          "Step value should be constant for pointer induction");
913   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
914          "StepValue is not an integer");
915 
916   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
917          "StepValue is not FP for FpInduction");
918   assert((IK != IK_FpInduction ||
919           (InductionBinOp &&
920            (InductionBinOp->getOpcode() == Instruction::FAdd ||
921             InductionBinOp->getOpcode() == Instruction::FSub))) &&
922          "Binary opcode should be specified for FP induction");
923 
924   if (Casts) {
925     for (auto &Inst : *Casts) {
926       RedundantCasts.push_back(Inst);
927     }
928   }
929 }
930 
931 int InductionDescriptor::getConsecutiveDirection() const {
932   ConstantInt *ConstStep = getConstIntStepValue();
933   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
934     return ConstStep->getSExtValue();
935   return 0;
936 }
937 
938 ConstantInt *InductionDescriptor::getConstIntStepValue() const {
939   if (isa<SCEVConstant>(Step))
940     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
941   return nullptr;
942 }
943 
944 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
945                                            ScalarEvolution *SE,
946                                            InductionDescriptor &D) {
947 
948   // Here we only handle FP induction variables.
949   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
950 
951   if (TheLoop->getHeader() != Phi->getParent())
952     return false;
953 
954   // The loop may have multiple entrances or multiple exits; we can analyze
955   // this phi if it has a unique entry value and a unique backedge value.
956   if (Phi->getNumIncomingValues() != 2)
957     return false;
958   Value *BEValue = nullptr, *StartValue = nullptr;
959   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
960     BEValue = Phi->getIncomingValue(0);
961     StartValue = Phi->getIncomingValue(1);
962   } else {
963     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
964            "Unexpected Phi node in the loop");
965     BEValue = Phi->getIncomingValue(1);
966     StartValue = Phi->getIncomingValue(0);
967   }
968 
969   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
970   if (!BOp)
971     return false;
972 
973   Value *Addend = nullptr;
974   if (BOp->getOpcode() == Instruction::FAdd) {
975     if (BOp->getOperand(0) == Phi)
976       Addend = BOp->getOperand(1);
977     else if (BOp->getOperand(1) == Phi)
978       Addend = BOp->getOperand(0);
979   } else if (BOp->getOpcode() == Instruction::FSub)
980     if (BOp->getOperand(0) == Phi)
981       Addend = BOp->getOperand(1);
982 
983   if (!Addend)
984     return false;
985 
986   // The addend should be loop invariant
987   if (auto *I = dyn_cast<Instruction>(Addend))
988     if (TheLoop->contains(I))
989       return false;
990 
991   // FP Step has unknown SCEV
992   const SCEV *Step = SE->getUnknown(Addend);
993   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
994   return true;
995 }
996 
997 /// This function is called when we suspect that the update-chain of a phi node
998 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
999 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1000 /// predicate P under which the SCEV expression for the phi can be the
1001 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1002 /// cast instructions that are involved in the update-chain of this induction.
1003 /// A caller that adds the required runtime predicate can be free to drop these
1004 /// cast instructions, and compute the phi using \p AR (instead of some scev
1005 /// expression with casts).
1006 ///
1007 /// For example, without a predicate the scev expression can take the following
1008 /// form:
1009 ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1010 ///
1011 /// It corresponds to the following IR sequence:
1012 /// %for.body:
1013 ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1014 ///   %casted_phi = "ExtTrunc i64 %x"
1015 ///   %add = add i64 %casted_phi, %step
1016 ///
1017 /// where %x is given in \p PN,
1018 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1019 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1020 /// several forms, for example, such as:
1021 ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
1022 /// or:
1023 ///   ExtTrunc2:    %t = shl %x, m
1024 ///                 %casted_phi = ashr %t, m
1025 ///
1026 /// If we are able to find such sequence, we return the instructions
1027 /// we found, namely %casted_phi and the instructions on its use-def chain up
1028 /// to the phi (not including the phi).
1029 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
1030                                     const SCEVUnknown *PhiScev,
1031                                     const SCEVAddRecExpr *AR,
1032                                     SmallVectorImpl<Instruction *> &CastInsts) {
1033 
1034   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1035   auto *PN = cast<PHINode>(PhiScev->getValue());
1036   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
1037   const Loop *L = AR->getLoop();
1038 
1039   // Find any cast instructions that participate in the def-use chain of
1040   // PhiScev in the loop.
1041   // FORNOW/TODO: We currently expect the def-use chain to include only
1042   // two-operand instructions, where one of the operands is an invariant.
1043   // createAddRecFromPHIWithCasts() currently does not support anything more
1044   // involved than that, so we keep the search simple. This can be
1045   // extended/generalized as needed.
1046 
1047   auto getDef = [&](const Value *Val) -> Value * {
1048     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1049     if (!BinOp)
1050       return nullptr;
1051     Value *Op0 = BinOp->getOperand(0);
1052     Value *Op1 = BinOp->getOperand(1);
1053     Value *Def = nullptr;
1054     if (L->isLoopInvariant(Op0))
1055       Def = Op1;
1056     else if (L->isLoopInvariant(Op1))
1057       Def = Op0;
1058     return Def;
1059   };
1060 
1061   // Look for the instruction that defines the induction via the
1062   // loop backedge.
1063   BasicBlock *Latch = L->getLoopLatch();
1064   if (!Latch)
1065     return false;
1066   Value *Val = PN->getIncomingValueForBlock(Latch);
1067   if (!Val)
1068     return false;
1069 
1070   // Follow the def-use chain until the induction phi is reached.
1071   // If on the way we encounter a Value that has the same SCEV Expr as the
1072   // phi node, we can consider the instructions we visit from that point
1073   // as part of the cast-sequence that can be ignored.
1074   bool InCastSequence = false;
1075   auto *Inst = dyn_cast<Instruction>(Val);
1076   while (Val != PN) {
1077     // If we encountered a phi node other than PN, or if we left the loop,
1078     // we bail out.
1079     if (!Inst || !L->contains(Inst)) {
1080       return false;
1081     }
1082     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1083     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1084       InCastSequence = true;
1085     if (InCastSequence) {
1086       // Only the last instruction in the cast sequence is expected to have
1087       // uses outside the induction def-use chain.
1088       if (!CastInsts.empty())
1089         if (!Inst->hasOneUse())
1090           return false;
1091       CastInsts.push_back(Inst);
1092     }
1093     Val = getDef(Val);
1094     if (!Val)
1095       return false;
1096     Inst = dyn_cast<Instruction>(Val);
1097   }
1098 
1099   return InCastSequence;
1100 }
1101 
1102 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1103                                          PredicatedScalarEvolution &PSE,
1104                                          InductionDescriptor &D, bool Assume) {
1105   Type *PhiTy = Phi->getType();
1106 
1107   // Handle integer and pointer inductions variables.
1108   // Now we handle also FP induction but not trying to make a
1109   // recurrent expression from the PHI node in-place.
1110 
1111   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1112       !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1113     return false;
1114 
1115   if (PhiTy->isFloatingPointTy())
1116     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1117 
1118   const SCEV *PhiScev = PSE.getSCEV(Phi);
1119   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1120 
1121   // We need this expression to be an AddRecExpr.
1122   if (Assume && !AR)
1123     AR = PSE.getAsAddRec(Phi);
1124 
1125   if (!AR) {
1126     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1127     return false;
1128   }
1129 
1130   // Record any Cast instructions that participate in the induction update
1131   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1132   // If we started from an UnknownSCEV, and managed to build an addRecurrence
1133   // only after enabling Assume with PSCEV, this means we may have encountered
1134   // cast instructions that required adding a runtime check in order to
1135   // guarantee the correctness of the AddRecurrence respresentation of the
1136   // induction.
1137   if (PhiScev != AR && SymbolicPhi) {
1138     SmallVector<Instruction *, 2> Casts;
1139     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1140       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1141   }
1142 
1143   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1144 }
1145 
1146 bool InductionDescriptor::isInductionPHI(
1147     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1148     InductionDescriptor &D, const SCEV *Expr,
1149     SmallVectorImpl<Instruction *> *CastsToIgnore) {
1150   Type *PhiTy = Phi->getType();
1151   // We only handle integer and pointer inductions variables.
1152   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1153     return false;
1154 
1155   // Check that the PHI is consecutive.
1156   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1157   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1158 
1159   if (!AR) {
1160     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1161     return false;
1162   }
1163 
1164   if (AR->getLoop() != TheLoop) {
1165     // FIXME: We should treat this as a uniform. Unfortunately, we
1166     // don't currently know how to handled uniform PHIs.
1167     LLVM_DEBUG(
1168         dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1169     return false;
1170   }
1171 
1172   Value *StartValue =
1173       Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
1174 
1175   BasicBlock *Latch = AR->getLoop()->getLoopLatch();
1176   if (!Latch)
1177     return false;
1178   BinaryOperator *BOp =
1179       dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1180 
1181   const SCEV *Step = AR->getStepRecurrence(*SE);
1182   // Calculate the pointer stride and check if it is consecutive.
1183   // The stride may be a constant or a loop invariant integer value.
1184   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1185   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
1186     return false;
1187 
1188   if (PhiTy->isIntegerTy()) {
1189     D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1190                             CastsToIgnore);
1191     return true;
1192   }
1193 
1194   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1195   // Pointer induction should be a constant.
1196   if (!ConstStep)
1197     return false;
1198 
1199   ConstantInt *CV = ConstStep->getValue();
1200   Type *PointerElementType = PhiTy->getPointerElementType();
1201   // The pointer stride cannot be determined if the pointer element type is not
1202   // sized.
1203   if (!PointerElementType->isSized())
1204     return false;
1205 
1206   const DataLayout &DL = Phi->getModule()->getDataLayout();
1207   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1208   if (!Size)
1209     return false;
1210 
1211   int64_t CVSize = CV->getSExtValue();
1212   if (CVSize % Size)
1213     return false;
1214   auto *StepValue =
1215       SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1216   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, BOp);
1217   return true;
1218 }
1219