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