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 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
650                                           RecurrenceDescriptor &RedDes,
651                                           DemandedBits *DB, AssumptionCache *AC,
652                                           DominatorTree *DT) {
653 
654   BasicBlock *Header = TheLoop->getHeader();
655   Function &F = *Header->getParent();
656   FastMathFlags FMF;
657   FMF.setNoNaNs(
658       F.getFnAttribute("no-nans-fp-math").getValueAsBool());
659   FMF.setNoSignedZeros(
660       F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool());
661 
662   if (AddReductionVar(Phi, RecurKind::Add, TheLoop, FMF, RedDes, DB, AC, DT)) {
663     LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
664     return true;
665   }
666   if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, FMF, RedDes, DB, AC, DT)) {
667     LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
668     return true;
669   }
670   if (AddReductionVar(Phi, RecurKind::Or, TheLoop, FMF, RedDes, DB, AC, DT)) {
671     LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
672     return true;
673   }
674   if (AddReductionVar(Phi, RecurKind::And, TheLoop, FMF, RedDes, DB, AC, DT)) {
675     LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
676     return true;
677   }
678   if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, FMF, RedDes, DB, AC, DT)) {
679     LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
680     return true;
681   }
682   if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, FMF, RedDes, DB, AC, DT)) {
683     LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n");
684     return true;
685   }
686   if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, FMF, RedDes, DB, AC, DT)) {
687     LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n");
688     return true;
689   }
690   if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, FMF, RedDes, DB, AC, DT)) {
691     LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n");
692     return true;
693   }
694   if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, FMF, RedDes, DB, AC, DT)) {
695     LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n");
696     return true;
697   }
698   if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, FMF, RedDes, DB, AC, DT)) {
699     LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
700     return true;
701   }
702   if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, FMF, RedDes, DB, AC, DT)) {
703     LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
704     return true;
705   }
706   if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, FMF, RedDes, DB, AC, DT)) {
707     LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n");
708     return true;
709   }
710   if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, FMF, RedDes, DB, AC, DT)) {
711     LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n");
712     return true;
713   }
714   // Not a reduction of known type.
715   return false;
716 }
717 
718 bool RecurrenceDescriptor::isFirstOrderRecurrence(
719     PHINode *Phi, Loop *TheLoop,
720     MapVector<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
721 
722   // Ensure the phi node is in the loop header and has two incoming values.
723   if (Phi->getParent() != TheLoop->getHeader() ||
724       Phi->getNumIncomingValues() != 2)
725     return false;
726 
727   // Ensure the loop has a preheader and a single latch block. The loop
728   // vectorizer will need the latch to set up the next iteration of the loop.
729   auto *Preheader = TheLoop->getLoopPreheader();
730   auto *Latch = TheLoop->getLoopLatch();
731   if (!Preheader || !Latch)
732     return false;
733 
734   // Ensure the phi node's incoming blocks are the loop preheader and latch.
735   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
736       Phi->getBasicBlockIndex(Latch) < 0)
737     return false;
738 
739   // Get the previous value. The previous value comes from the latch edge while
740   // the initial value comes form the preheader edge.
741   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
742   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
743       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
744     return false;
745 
746   // Ensure every user of the phi node (recursively) is dominated by the
747   // previous value. The dominance requirement ensures the loop vectorizer will
748   // not need to vectorize the initial value prior to the first iteration of the
749   // loop.
750   // TODO: Consider extending this sinking to handle memory instructions.
751 
752   // We optimistically assume we can sink all users after Previous. Keep a set
753   // of instructions to sink after Previous ordered by dominance in the common
754   // basic block. It will be applied to SinkAfter if all users can be sunk.
755   auto CompareByComesBefore = [](const Instruction *A, const Instruction *B) {
756     return A->comesBefore(B);
757   };
758   std::set<Instruction *, decltype(CompareByComesBefore)> InstrsToSink(
759       CompareByComesBefore);
760 
761   BasicBlock *PhiBB = Phi->getParent();
762   SmallVector<Instruction *, 8> WorkList;
763   auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
764     // Already sunk SinkCandidate.
765     if (SinkCandidate->getParent() == PhiBB &&
766         InstrsToSink.find(SinkCandidate) != InstrsToSink.end())
767       return true;
768 
769     // Cyclic dependence.
770     if (Previous == SinkCandidate)
771       return false;
772 
773     if (DT->dominates(Previous,
774                       SinkCandidate)) // We already are good w/o sinking.
775       return true;
776 
777     if (SinkCandidate->getParent() != PhiBB ||
778         SinkCandidate->mayHaveSideEffects() ||
779         SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
780       return false;
781 
782     // Do not try to sink an instruction multiple times (if multiple operands
783     // are first order recurrences).
784     // TODO: We can support this case, by sinking the instruction after the
785     // 'deepest' previous instruction.
786     if (SinkAfter.find(SinkCandidate) != SinkAfter.end())
787       return false;
788 
789     // If we reach a PHI node that is not dominated by Previous, we reached a
790     // header PHI. No need for sinking.
791     if (isa<PHINode>(SinkCandidate))
792       return true;
793 
794     // Sink User tentatively and check its users
795     InstrsToSink.insert(SinkCandidate);
796     WorkList.push_back(SinkCandidate);
797     return true;
798   };
799 
800   WorkList.push_back(Phi);
801   // Try to recursively sink instructions and their users after Previous.
802   while (!WorkList.empty()) {
803     Instruction *Current = WorkList.pop_back_val();
804     for (User *User : Current->users()) {
805       if (!TryToPushSinkCandidate(cast<Instruction>(User)))
806         return false;
807     }
808   }
809 
810   // We can sink all users of Phi. Update the mapping.
811   for (Instruction *I : InstrsToSink) {
812     SinkAfter[I] = Previous;
813     Previous = I;
814   }
815   return true;
816 }
817 
818 /// This function returns the identity element (or neutral element) for
819 /// the operation K.
820 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp,
821                                                       FastMathFlags FMF) {
822   switch (K) {
823   case RecurKind::Xor:
824   case RecurKind::Add:
825   case RecurKind::Or:
826     // Adding, Xoring, Oring zero to a number does not change it.
827     return ConstantInt::get(Tp, 0);
828   case RecurKind::Mul:
829     // Multiplying a number by 1 does not change it.
830     return ConstantInt::get(Tp, 1);
831   case RecurKind::And:
832     // AND-ing a number with an all-1 value does not change it.
833     return ConstantInt::get(Tp, -1, true);
834   case RecurKind::FMul:
835     // Multiplying a number by 1 does not change it.
836     return ConstantFP::get(Tp, 1.0L);
837   case RecurKind::FAdd:
838     // Adding zero to a number does not change it.
839     // FIXME: Ideally we should not need to check FMF for FAdd and should always
840     // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0.
841     // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI
842     // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would
843     // mean we can then remove the check for noSignedZeros() below (see D98963).
844     if (FMF.noSignedZeros())
845       return ConstantFP::get(Tp, 0.0L);
846     return ConstantFP::get(Tp, -0.0L);
847   case RecurKind::UMin:
848     return ConstantInt::get(Tp, -1);
849   case RecurKind::UMax:
850     return ConstantInt::get(Tp, 0);
851   case RecurKind::SMin:
852     return ConstantInt::get(Tp,
853                             APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
854   case RecurKind::SMax:
855     return ConstantInt::get(Tp,
856                             APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
857   case RecurKind::FMin:
858     return ConstantFP::getInfinity(Tp, true);
859   case RecurKind::FMax:
860     return ConstantFP::getInfinity(Tp, false);
861   default:
862     llvm_unreachable("Unknown recurrence kind");
863   }
864 }
865 
866 unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) {
867   switch (Kind) {
868   case RecurKind::Add:
869     return Instruction::Add;
870   case RecurKind::Mul:
871     return Instruction::Mul;
872   case RecurKind::Or:
873     return Instruction::Or;
874   case RecurKind::And:
875     return Instruction::And;
876   case RecurKind::Xor:
877     return Instruction::Xor;
878   case RecurKind::FMul:
879     return Instruction::FMul;
880   case RecurKind::FAdd:
881     return Instruction::FAdd;
882   case RecurKind::SMax:
883   case RecurKind::SMin:
884   case RecurKind::UMax:
885   case RecurKind::UMin:
886     return Instruction::ICmp;
887   case RecurKind::FMax:
888   case RecurKind::FMin:
889     return Instruction::FCmp;
890   default:
891     llvm_unreachable("Unknown recurrence operation");
892   }
893 }
894 
895 SmallVector<Instruction *, 4>
896 RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
897   SmallVector<Instruction *, 4> ReductionOperations;
898   unsigned RedOp = getOpcode(Kind);
899 
900   // Search down from the Phi to the LoopExitInstr, looking for instructions
901   // with a single user of the correct type for the reduction.
902 
903   // Note that we check that the type of the operand is correct for each item in
904   // the chain, including the last (the loop exit value). This can come up from
905   // sub, which would otherwise be treated as an add reduction. MinMax also need
906   // to check for a pair of icmp/select, for which we use getNextInstruction and
907   // isCorrectOpcode functions to step the right number of instruction, and
908   // check the icmp/select pair.
909   // FIXME: We also do not attempt to look through Phi/Select's yet, which might
910   // be part of the reduction chain, or attempt to looks through And's to find a
911   // smaller bitwidth. Subs are also currently not allowed (which are usually
912   // treated as part of a add reduction) as they are expected to generally be
913   // more expensive than out-of-loop reductions, and need to be costed more
914   // carefully.
915   unsigned ExpectedUses = 1;
916   if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
917     ExpectedUses = 2;
918 
919   auto getNextInstruction = [&](Instruction *Cur) {
920     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
921       // We are expecting a icmp/select pair, which we go to the next select
922       // instruction if we can. We already know that Cur has 2 uses.
923       if (isa<SelectInst>(*Cur->user_begin()))
924         return cast<Instruction>(*Cur->user_begin());
925       else
926         return cast<Instruction>(*std::next(Cur->user_begin()));
927     }
928     return cast<Instruction>(*Cur->user_begin());
929   };
930   auto isCorrectOpcode = [&](Instruction *Cur) {
931     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
932       Value *LHS, *RHS;
933       return SelectPatternResult::isMinOrMax(
934           matchSelectPattern(Cur, LHS, RHS).Flavor);
935     }
936     return Cur->getOpcode() == RedOp;
937   };
938 
939   // The loop exit instruction we check first (as a quick test) but add last. We
940   // check the opcode is correct (and dont allow them to be Subs) and that they
941   // have expected to have the expected number of uses. They will have one use
942   // from the phi and one from a LCSSA value, no matter the type.
943   if (!isCorrectOpcode(LoopExitInstr) || !LoopExitInstr->hasNUses(2))
944     return {};
945 
946   // Check that the Phi has one (or two for min/max) uses.
947   if (!Phi->hasNUses(ExpectedUses))
948     return {};
949   Instruction *Cur = getNextInstruction(Phi);
950 
951   // Each other instruction in the chain should have the expected number of uses
952   // and be the correct opcode.
953   while (Cur != LoopExitInstr) {
954     if (!isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
955       return {};
956 
957     ReductionOperations.push_back(Cur);
958     Cur = getNextInstruction(Cur);
959   }
960 
961   ReductionOperations.push_back(Cur);
962   return ReductionOperations;
963 }
964 
965 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
966                                          const SCEV *Step, BinaryOperator *BOp,
967                                          SmallVectorImpl<Instruction *> *Casts)
968     : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
969   assert(IK != IK_NoInduction && "Not an induction");
970 
971   // Start value type should match the induction kind and the value
972   // itself should not be null.
973   assert(StartValue && "StartValue is null");
974   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
975          "StartValue is not a pointer for pointer induction");
976   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
977          "StartValue is not an integer for integer induction");
978 
979   // Check the Step Value. It should be non-zero integer value.
980   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
981          "Step value is zero");
982 
983   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
984          "Step value should be constant for pointer induction");
985   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
986          "StepValue is not an integer");
987 
988   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
989          "StepValue is not FP for FpInduction");
990   assert((IK != IK_FpInduction ||
991           (InductionBinOp &&
992            (InductionBinOp->getOpcode() == Instruction::FAdd ||
993             InductionBinOp->getOpcode() == Instruction::FSub))) &&
994          "Binary opcode should be specified for FP induction");
995 
996   if (Casts) {
997     for (auto &Inst : *Casts) {
998       RedundantCasts.push_back(Inst);
999     }
1000   }
1001 }
1002 
1003 ConstantInt *InductionDescriptor::getConstIntStepValue() const {
1004   if (isa<SCEVConstant>(Step))
1005     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
1006   return nullptr;
1007 }
1008 
1009 bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
1010                                            ScalarEvolution *SE,
1011                                            InductionDescriptor &D) {
1012 
1013   // Here we only handle FP induction variables.
1014   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
1015 
1016   if (TheLoop->getHeader() != Phi->getParent())
1017     return false;
1018 
1019   // The loop may have multiple entrances or multiple exits; we can analyze
1020   // this phi if it has a unique entry value and a unique backedge value.
1021   if (Phi->getNumIncomingValues() != 2)
1022     return false;
1023   Value *BEValue = nullptr, *StartValue = nullptr;
1024   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
1025     BEValue = Phi->getIncomingValue(0);
1026     StartValue = Phi->getIncomingValue(1);
1027   } else {
1028     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
1029            "Unexpected Phi node in the loop");
1030     BEValue = Phi->getIncomingValue(1);
1031     StartValue = Phi->getIncomingValue(0);
1032   }
1033 
1034   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
1035   if (!BOp)
1036     return false;
1037 
1038   Value *Addend = nullptr;
1039   if (BOp->getOpcode() == Instruction::FAdd) {
1040     if (BOp->getOperand(0) == Phi)
1041       Addend = BOp->getOperand(1);
1042     else if (BOp->getOperand(1) == Phi)
1043       Addend = BOp->getOperand(0);
1044   } else if (BOp->getOpcode() == Instruction::FSub)
1045     if (BOp->getOperand(0) == Phi)
1046       Addend = BOp->getOperand(1);
1047 
1048   if (!Addend)
1049     return false;
1050 
1051   // The addend should be loop invariant
1052   if (auto *I = dyn_cast<Instruction>(Addend))
1053     if (TheLoop->contains(I))
1054       return false;
1055 
1056   // FP Step has unknown SCEV
1057   const SCEV *Step = SE->getUnknown(Addend);
1058   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
1059   return true;
1060 }
1061 
1062 /// This function is called when we suspect that the update-chain of a phi node
1063 /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
1064 /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
1065 /// predicate P under which the SCEV expression for the phi can be the
1066 /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
1067 /// cast instructions that are involved in the update-chain of this induction.
1068 /// A caller that adds the required runtime predicate can be free to drop these
1069 /// cast instructions, and compute the phi using \p AR (instead of some scev
1070 /// expression with casts).
1071 ///
1072 /// For example, without a predicate the scev expression can take the following
1073 /// form:
1074 ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
1075 ///
1076 /// It corresponds to the following IR sequence:
1077 /// %for.body:
1078 ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
1079 ///   %casted_phi = "ExtTrunc i64 %x"
1080 ///   %add = add i64 %casted_phi, %step
1081 ///
1082 /// where %x is given in \p PN,
1083 /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
1084 /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
1085 /// several forms, for example, such as:
1086 ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
1087 /// or:
1088 ///   ExtTrunc2:    %t = shl %x, m
1089 ///                 %casted_phi = ashr %t, m
1090 ///
1091 /// If we are able to find such sequence, we return the instructions
1092 /// we found, namely %casted_phi and the instructions on its use-def chain up
1093 /// to the phi (not including the phi).
1094 static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
1095                                     const SCEVUnknown *PhiScev,
1096                                     const SCEVAddRecExpr *AR,
1097                                     SmallVectorImpl<Instruction *> &CastInsts) {
1098 
1099   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
1100   auto *PN = cast<PHINode>(PhiScev->getValue());
1101   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
1102   const Loop *L = AR->getLoop();
1103 
1104   // Find any cast instructions that participate in the def-use chain of
1105   // PhiScev in the loop.
1106   // FORNOW/TODO: We currently expect the def-use chain to include only
1107   // two-operand instructions, where one of the operands is an invariant.
1108   // createAddRecFromPHIWithCasts() currently does not support anything more
1109   // involved than that, so we keep the search simple. This can be
1110   // extended/generalized as needed.
1111 
1112   auto getDef = [&](const Value *Val) -> Value * {
1113     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
1114     if (!BinOp)
1115       return nullptr;
1116     Value *Op0 = BinOp->getOperand(0);
1117     Value *Op1 = BinOp->getOperand(1);
1118     Value *Def = nullptr;
1119     if (L->isLoopInvariant(Op0))
1120       Def = Op1;
1121     else if (L->isLoopInvariant(Op1))
1122       Def = Op0;
1123     return Def;
1124   };
1125 
1126   // Look for the instruction that defines the induction via the
1127   // loop backedge.
1128   BasicBlock *Latch = L->getLoopLatch();
1129   if (!Latch)
1130     return false;
1131   Value *Val = PN->getIncomingValueForBlock(Latch);
1132   if (!Val)
1133     return false;
1134 
1135   // Follow the def-use chain until the induction phi is reached.
1136   // If on the way we encounter a Value that has the same SCEV Expr as the
1137   // phi node, we can consider the instructions we visit from that point
1138   // as part of the cast-sequence that can be ignored.
1139   bool InCastSequence = false;
1140   auto *Inst = dyn_cast<Instruction>(Val);
1141   while (Val != PN) {
1142     // If we encountered a phi node other than PN, or if we left the loop,
1143     // we bail out.
1144     if (!Inst || !L->contains(Inst)) {
1145       return false;
1146     }
1147     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
1148     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
1149       InCastSequence = true;
1150     if (InCastSequence) {
1151       // Only the last instruction in the cast sequence is expected to have
1152       // uses outside the induction def-use chain.
1153       if (!CastInsts.empty())
1154         if (!Inst->hasOneUse())
1155           return false;
1156       CastInsts.push_back(Inst);
1157     }
1158     Val = getDef(Val);
1159     if (!Val)
1160       return false;
1161     Inst = dyn_cast<Instruction>(Val);
1162   }
1163 
1164   return InCastSequence;
1165 }
1166 
1167 bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1168                                          PredicatedScalarEvolution &PSE,
1169                                          InductionDescriptor &D, bool Assume) {
1170   Type *PhiTy = Phi->getType();
1171 
1172   // Handle integer and pointer inductions variables.
1173   // Now we handle also FP induction but not trying to make a
1174   // recurrent expression from the PHI node in-place.
1175 
1176   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
1177       !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1178     return false;
1179 
1180   if (PhiTy->isFloatingPointTy())
1181     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1182 
1183   const SCEV *PhiScev = PSE.getSCEV(Phi);
1184   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1185 
1186   // We need this expression to be an AddRecExpr.
1187   if (Assume && !AR)
1188     AR = PSE.getAsAddRec(Phi);
1189 
1190   if (!AR) {
1191     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1192     return false;
1193   }
1194 
1195   // Record any Cast instructions that participate in the induction update
1196   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
1197   // If we started from an UnknownSCEV, and managed to build an addRecurrence
1198   // only after enabling Assume with PSCEV, this means we may have encountered
1199   // cast instructions that required adding a runtime check in order to
1200   // guarantee the correctness of the AddRecurrence respresentation of the
1201   // induction.
1202   if (PhiScev != AR && SymbolicPhi) {
1203     SmallVector<Instruction *, 2> Casts;
1204     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
1205       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
1206   }
1207 
1208   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1209 }
1210 
1211 bool InductionDescriptor::isInductionPHI(
1212     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
1213     InductionDescriptor &D, const SCEV *Expr,
1214     SmallVectorImpl<Instruction *> *CastsToIgnore) {
1215   Type *PhiTy = Phi->getType();
1216   // We only handle integer and pointer inductions variables.
1217   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
1218     return false;
1219 
1220   // Check that the PHI is consecutive.
1221   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
1222   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1223 
1224   if (!AR) {
1225     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1226     return false;
1227   }
1228 
1229   if (AR->getLoop() != TheLoop) {
1230     // FIXME: We should treat this as a uniform. Unfortunately, we
1231     // don't currently know how to handled uniform PHIs.
1232     LLVM_DEBUG(
1233         dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1234     return false;
1235   }
1236 
1237   Value *StartValue =
1238       Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
1239 
1240   BasicBlock *Latch = AR->getLoop()->getLoopLatch();
1241   if (!Latch)
1242     return false;
1243   BinaryOperator *BOp =
1244       dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
1245 
1246   const SCEV *Step = AR->getStepRecurrence(*SE);
1247   // Calculate the pointer stride and check if it is consecutive.
1248   // The stride may be a constant or a loop invariant integer value.
1249   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1250   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
1251     return false;
1252 
1253   if (PhiTy->isIntegerTy()) {
1254     D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
1255                             CastsToIgnore);
1256     return true;
1257   }
1258 
1259   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1260   // Pointer induction should be a constant.
1261   if (!ConstStep)
1262     return false;
1263 
1264   ConstantInt *CV = ConstStep->getValue();
1265   Type *PointerElementType = PhiTy->getPointerElementType();
1266   // The pointer stride cannot be determined if the pointer element type is not
1267   // sized.
1268   if (!PointerElementType->isSized())
1269     return false;
1270 
1271   const DataLayout &DL = Phi->getModule()->getDataLayout();
1272   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1273   if (!Size)
1274     return false;
1275 
1276   int64_t CVSize = CV->getSExtValue();
1277   if (CVSize % Size)
1278     return false;
1279   auto *StepValue =
1280       SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
1281   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue, BOp);
1282   return true;
1283 }
1284