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