1 //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines common loop utility functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/AliasAnalysis.h"
15 #include "llvm/Analysis/BasicAliasAnalysis.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/GlobalsModRef.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
20 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/IR/ValueHandle.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Transforms/Utils/LoopUtils.h"
29 
30 using namespace llvm;
31 using namespace llvm::PatternMatch;
32 
33 #define DEBUG_TYPE "loop-utils"
34 
35 bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
36                                         SmallPtrSetImpl<Instruction *> &Set) {
37   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
38     if (!Set.count(dyn_cast<Instruction>(*Use)))
39       return false;
40   return true;
41 }
42 
43 bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
44   switch (Kind) {
45   default:
46     break;
47   case RK_IntegerAdd:
48   case RK_IntegerMult:
49   case RK_IntegerOr:
50   case RK_IntegerAnd:
51   case RK_IntegerXor:
52   case RK_IntegerMinMax:
53     return true;
54   }
55   return false;
56 }
57 
58 bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
59   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
60 }
61 
62 bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
63   switch (Kind) {
64   default:
65     break;
66   case RK_IntegerAdd:
67   case RK_IntegerMult:
68   case RK_FloatAdd:
69   case RK_FloatMult:
70     return true;
71   }
72   return false;
73 }
74 
75 Instruction *
76 RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
77                                      SmallPtrSetImpl<Instruction *> &Visited,
78                                      SmallPtrSetImpl<Instruction *> &CI) {
79   if (!Phi->hasOneUse())
80     return Phi;
81 
82   const APInt *M = nullptr;
83   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
84 
85   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
86   // with a new integer type of the corresponding bit width.
87   if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
88                            m_And(m_APInt(M), m_Instruction(I))))) {
89     int32_t Bits = (*M + 1).exactLogBase2();
90     if (Bits > 0) {
91       RT = IntegerType::get(Phi->getContext(), Bits);
92       Visited.insert(Phi);
93       CI.insert(J);
94       return J;
95     }
96   }
97   return Phi;
98 }
99 
100 bool RecurrenceDescriptor::getSourceExtensionKind(
101     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
102     SmallPtrSetImpl<Instruction *> &Visited,
103     SmallPtrSetImpl<Instruction *> &CI) {
104 
105   SmallVector<Instruction *, 8> Worklist;
106   bool FoundOneOperand = false;
107   unsigned DstSize = RT->getPrimitiveSizeInBits();
108   Worklist.push_back(Exit);
109 
110   // Traverse the instructions in the reduction expression, beginning with the
111   // exit value.
112   while (!Worklist.empty()) {
113     Instruction *I = Worklist.pop_back_val();
114     for (Use &U : I->operands()) {
115 
116       // Terminate the traversal if the operand is not an instruction, or we
117       // reach the starting value.
118       Instruction *J = dyn_cast<Instruction>(U.get());
119       if (!J || J == Start)
120         continue;
121 
122       // Otherwise, investigate the operation if it is also in the expression.
123       if (Visited.count(J)) {
124         Worklist.push_back(J);
125         continue;
126       }
127 
128       // If the operand is not in Visited, it is not a reduction operation, but
129       // it does feed into one. Make sure it is either a single-use sign- or
130       // zero-extend instruction.
131       CastInst *Cast = dyn_cast<CastInst>(J);
132       bool IsSExtInst = isa<SExtInst>(J);
133       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
134         return false;
135 
136       // Ensure the source type of the extend is no larger than the reduction
137       // type. It is not necessary for the types to be identical.
138       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
139       if (SrcSize > DstSize)
140         return false;
141 
142       // Furthermore, ensure that all such extends are of the same kind.
143       if (FoundOneOperand) {
144         if (IsSigned != IsSExtInst)
145           return false;
146       } else {
147         FoundOneOperand = true;
148         IsSigned = IsSExtInst;
149       }
150 
151       // Lastly, if the source type of the extend matches the reduction type,
152       // add the extend to CI so that we can avoid accounting for it in the
153       // cost model.
154       if (SrcSize == DstSize)
155         CI.insert(Cast);
156     }
157   }
158   return true;
159 }
160 
161 bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
162                                            Loop *TheLoop, bool HasFunNoNaNAttr,
163                                            RecurrenceDescriptor &RedDes) {
164   if (Phi->getNumIncomingValues() != 2)
165     return false;
166 
167   // Reduction variables are only found in the loop header block.
168   if (Phi->getParent() != TheLoop->getHeader())
169     return false;
170 
171   // Obtain the reduction start value from the value that comes from the loop
172   // preheader.
173   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
174 
175   // ExitInstruction is the single value which is used outside the loop.
176   // We only allow for a single reduction value to be used outside the loop.
177   // This includes users of the reduction, variables (which form a cycle
178   // which ends in the phi node).
179   Instruction *ExitInstruction = nullptr;
180   // Indicates that we found a reduction operation in our scan.
181   bool FoundReduxOp = false;
182 
183   // We start with the PHI node and scan for all of the users of this
184   // instruction. All users must be instructions that can be used as reduction
185   // variables (such as ADD). We must have a single out-of-block user. The cycle
186   // must include the original PHI.
187   bool FoundStartPHI = false;
188 
189   // To recognize min/max patterns formed by a icmp select sequence, we store
190   // the number of instruction we saw from the recognized min/max pattern,
191   //  to make sure we only see exactly the two instructions.
192   unsigned NumCmpSelectPatternInst = 0;
193   InstDesc ReduxDesc(false, nullptr);
194 
195   // Data used for determining if the recurrence has been type-promoted.
196   Type *RecurrenceType = Phi->getType();
197   SmallPtrSet<Instruction *, 4> CastInsts;
198   Instruction *Start = Phi;
199   bool IsSigned = false;
200 
201   SmallPtrSet<Instruction *, 8> VisitedInsts;
202   SmallVector<Instruction *, 8> Worklist;
203 
204   // Return early if the recurrence kind does not match the type of Phi. If the
205   // recurrence kind is arithmetic, we attempt to look through AND operations
206   // resulting from the type promotion performed by InstCombine.  Vector
207   // operations are not limited to the legal integer widths, so we may be able
208   // to evaluate the reduction in the narrower width.
209   if (RecurrenceType->isFloatingPointTy()) {
210     if (!isFloatingPointRecurrenceKind(Kind))
211       return false;
212   } else {
213     if (!isIntegerRecurrenceKind(Kind))
214       return false;
215     if (isArithmeticRecurrenceKind(Kind))
216       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
217   }
218 
219   Worklist.push_back(Start);
220   VisitedInsts.insert(Start);
221 
222   // A value in the reduction can be used:
223   //  - By the reduction:
224   //      - Reduction operation:
225   //        - One use of reduction value (safe).
226   //        - Multiple use of reduction value (not safe).
227   //      - PHI:
228   //        - All uses of the PHI must be the reduction (safe).
229   //        - Otherwise, not safe.
230   //  - By one instruction outside of the loop (safe).
231   //  - By further instructions outside of the loop (not safe).
232   //  - By an instruction that is not part of the reduction (not safe).
233   //    This is either:
234   //      * An instruction type other than PHI or the reduction operation.
235   //      * A PHI in the header other than the initial PHI.
236   while (!Worklist.empty()) {
237     Instruction *Cur = Worklist.back();
238     Worklist.pop_back();
239 
240     // No Users.
241     // If the instruction has no users then this is a broken chain and can't be
242     // a reduction variable.
243     if (Cur->use_empty())
244       return false;
245 
246     bool IsAPhi = isa<PHINode>(Cur);
247 
248     // A header PHI use other than the original PHI.
249     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
250       return false;
251 
252     // Reductions of instructions such as Div, and Sub is only possible if the
253     // LHS is the reduction variable.
254     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
255         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
256         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
257       return false;
258 
259     // Any reduction instruction must be of one of the allowed kinds. We ignore
260     // the starting value (the Phi or an AND instruction if the Phi has been
261     // type-promoted).
262     if (Cur != Start) {
263       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
264       if (!ReduxDesc.isRecurrence())
265         return false;
266     }
267 
268     // A reduction operation must only have one use of the reduction value.
269     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
270         hasMultipleUsesOf(Cur, VisitedInsts))
271       return false;
272 
273     // All inputs to a PHI node must be a reduction value.
274     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
275       return false;
276 
277     if (Kind == RK_IntegerMinMax &&
278         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
279       ++NumCmpSelectPatternInst;
280     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
281       ++NumCmpSelectPatternInst;
282 
283     // Check  whether we found a reduction operator.
284     FoundReduxOp |= !IsAPhi && Cur != Start;
285 
286     // Process users of current instruction. Push non-PHI nodes after PHI nodes
287     // onto the stack. This way we are going to have seen all inputs to PHI
288     // nodes once we get to them.
289     SmallVector<Instruction *, 8> NonPHIs;
290     SmallVector<Instruction *, 8> PHIs;
291     for (User *U : Cur->users()) {
292       Instruction *UI = cast<Instruction>(U);
293 
294       // Check if we found the exit user.
295       BasicBlock *Parent = UI->getParent();
296       if (!TheLoop->contains(Parent)) {
297         // Exit if you find multiple outside users or if the header phi node is
298         // being used. In this case the user uses the value of the previous
299         // iteration, in which case we would loose "VF-1" iterations of the
300         // reduction operation if we vectorize.
301         if (ExitInstruction != nullptr || Cur == Phi)
302           return false;
303 
304         // The instruction used by an outside user must be the last instruction
305         // before we feed back to the reduction phi. Otherwise, we loose VF-1
306         // operations on the value.
307         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
308           return false;
309 
310         ExitInstruction = Cur;
311         continue;
312       }
313 
314       // Process instructions only once (termination). Each reduction cycle
315       // value must only be used once, except by phi nodes and min/max
316       // reductions which are represented as a cmp followed by a select.
317       InstDesc IgnoredVal(false, nullptr);
318       if (VisitedInsts.insert(UI).second) {
319         if (isa<PHINode>(UI))
320           PHIs.push_back(UI);
321         else
322           NonPHIs.push_back(UI);
323       } else if (!isa<PHINode>(UI) &&
324                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
325                    !isa<SelectInst>(UI)) ||
326                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
327         return false;
328 
329       // Remember that we completed the cycle.
330       if (UI == Phi)
331         FoundStartPHI = true;
332     }
333     Worklist.append(PHIs.begin(), PHIs.end());
334     Worklist.append(NonPHIs.begin(), NonPHIs.end());
335   }
336 
337   // This means we have seen one but not the other instruction of the
338   // pattern or more than just a select and cmp.
339   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
340       NumCmpSelectPatternInst != 2)
341     return false;
342 
343   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
344     return false;
345 
346   // If we think Phi may have been type-promoted, we also need to ensure that
347   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
348   // so, we will be able to evaluate the reduction in the narrower bit width.
349   if (Start != Phi)
350     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
351                                 IsSigned, VisitedInsts, CastInsts))
352       return false;
353 
354   // We found a reduction var if we have reached the original phi node and we
355   // only have a single instruction with out-of-loop users.
356 
357   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
358   // is saved as part of the RecurrenceDescriptor.
359 
360   // Save the description of this reduction variable.
361   RecurrenceDescriptor RD(
362       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
363       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
364   RedDes = RD;
365 
366   return true;
367 }
368 
369 /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
370 /// pattern corresponding to a min(X, Y) or max(X, Y).
371 RecurrenceDescriptor::InstDesc
372 RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
373 
374   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
375          "Expect a select instruction");
376   Instruction *Cmp = nullptr;
377   SelectInst *Select = nullptr;
378 
379   // We must handle the select(cmp()) as a single instruction. Advance to the
380   // select.
381   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
382     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
383       return InstDesc(false, I);
384     return InstDesc(Select, Prev.getMinMaxKind());
385   }
386 
387   // Only handle single use cases for now.
388   if (!(Select = dyn_cast<SelectInst>(I)))
389     return InstDesc(false, I);
390   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
391       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
392     return InstDesc(false, I);
393   if (!Cmp->hasOneUse())
394     return InstDesc(false, I);
395 
396   Value *CmpLeft;
397   Value *CmpRight;
398 
399   // Look for a min/max pattern.
400   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
401     return InstDesc(Select, MRK_UIntMin);
402   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
403     return InstDesc(Select, MRK_UIntMax);
404   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
405     return InstDesc(Select, MRK_SIntMax);
406   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
407     return InstDesc(Select, MRK_SIntMin);
408   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
409     return InstDesc(Select, MRK_FloatMin);
410   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
411     return InstDesc(Select, MRK_FloatMax);
412   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
413     return InstDesc(Select, MRK_FloatMin);
414   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
415     return InstDesc(Select, MRK_FloatMax);
416 
417   return InstDesc(false, I);
418 }
419 
420 RecurrenceDescriptor::InstDesc
421 RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
422                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
423   bool FP = I->getType()->isFloatingPointTy();
424   Instruction *UAI = Prev.getUnsafeAlgebraInst();
425   if (!UAI && FP && !I->hasUnsafeAlgebra())
426     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
427 
428   switch (I->getOpcode()) {
429   default:
430     return InstDesc(false, I);
431   case Instruction::PHI:
432     return InstDesc(I, Prev.getMinMaxKind());
433   case Instruction::Sub:
434   case Instruction::Add:
435     return InstDesc(Kind == RK_IntegerAdd, I);
436   case Instruction::Mul:
437     return InstDesc(Kind == RK_IntegerMult, I);
438   case Instruction::And:
439     return InstDesc(Kind == RK_IntegerAnd, I);
440   case Instruction::Or:
441     return InstDesc(Kind == RK_IntegerOr, I);
442   case Instruction::Xor:
443     return InstDesc(Kind == RK_IntegerXor, I);
444   case Instruction::FMul:
445     return InstDesc(Kind == RK_FloatMult, I, UAI);
446   case Instruction::FSub:
447   case Instruction::FAdd:
448     return InstDesc(Kind == RK_FloatAdd, I, UAI);
449   case Instruction::FCmp:
450   case Instruction::ICmp:
451   case Instruction::Select:
452     if (Kind != RK_IntegerMinMax &&
453         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
454       return InstDesc(false, I);
455     return isMinMaxSelectCmpPattern(I, Prev);
456   }
457 }
458 
459 bool RecurrenceDescriptor::hasMultipleUsesOf(
460     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
461   unsigned NumUses = 0;
462   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
463        ++Use) {
464     if (Insts.count(dyn_cast<Instruction>(*Use)))
465       ++NumUses;
466     if (NumUses > 1)
467       return true;
468   }
469 
470   return false;
471 }
472 bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
473                                           RecurrenceDescriptor &RedDes) {
474 
475   BasicBlock *Header = TheLoop->getHeader();
476   Function &F = *Header->getParent();
477   bool HasFunNoNaNAttr =
478       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
479 
480   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
481     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
482     return true;
483   }
484   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
485     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
486     return true;
487   }
488   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
489     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
490     return true;
491   }
492   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
493     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
494     return true;
495   }
496   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
497     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
498     return true;
499   }
500   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
501                       RedDes)) {
502     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
503     return true;
504   }
505   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
506     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
507     return true;
508   }
509   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
510     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
511     return true;
512   }
513   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
514     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
515     return true;
516   }
517   // Not a reduction of known type.
518   return false;
519 }
520 
521 bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
522                                                   DominatorTree *DT) {
523 
524   // Ensure the phi node is in the loop header and has two incoming values.
525   if (Phi->getParent() != TheLoop->getHeader() ||
526       Phi->getNumIncomingValues() != 2)
527     return false;
528 
529   // Ensure the loop has a preheader and a single latch block. The loop
530   // vectorizer will need the latch to set up the next iteration of the loop.
531   auto *Preheader = TheLoop->getLoopPreheader();
532   auto *Latch = TheLoop->getLoopLatch();
533   if (!Preheader || !Latch)
534     return false;
535 
536   // Ensure the phi node's incoming blocks are the loop preheader and latch.
537   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
538       Phi->getBasicBlockIndex(Latch) < 0)
539     return false;
540 
541   // Get the previous value. The previous value comes from the latch edge while
542   // the initial value comes form the preheader edge.
543   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
544   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
545     return false;
546 
547   // Ensure every user of the phi node is dominated by the previous value. The
548   // dominance requirement ensures the loop vectorizer will not need to
549   // vectorize the initial value prior to the first iteration of the loop.
550   for (User *U : Phi->users())
551     if (auto *I = dyn_cast<Instruction>(U))
552       if (!DT->dominates(Previous, I))
553         return false;
554 
555   return true;
556 }
557 
558 /// This function returns the identity element (or neutral element) for
559 /// the operation K.
560 Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
561                                                       Type *Tp) {
562   switch (K) {
563   case RK_IntegerXor:
564   case RK_IntegerAdd:
565   case RK_IntegerOr:
566     // Adding, Xoring, Oring zero to a number does not change it.
567     return ConstantInt::get(Tp, 0);
568   case RK_IntegerMult:
569     // Multiplying a number by 1 does not change it.
570     return ConstantInt::get(Tp, 1);
571   case RK_IntegerAnd:
572     // AND-ing a number with an all-1 value does not change it.
573     return ConstantInt::get(Tp, -1, true);
574   case RK_FloatMult:
575     // Multiplying a number by 1 does not change it.
576     return ConstantFP::get(Tp, 1.0L);
577   case RK_FloatAdd:
578     // Adding zero to a number does not change it.
579     return ConstantFP::get(Tp, 0.0L);
580   default:
581     llvm_unreachable("Unknown recurrence kind");
582   }
583 }
584 
585 /// This function translates the recurrence kind to an LLVM binary operator.
586 unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
587   switch (Kind) {
588   case RK_IntegerAdd:
589     return Instruction::Add;
590   case RK_IntegerMult:
591     return Instruction::Mul;
592   case RK_IntegerOr:
593     return Instruction::Or;
594   case RK_IntegerAnd:
595     return Instruction::And;
596   case RK_IntegerXor:
597     return Instruction::Xor;
598   case RK_FloatMult:
599     return Instruction::FMul;
600   case RK_FloatAdd:
601     return Instruction::FAdd;
602   case RK_IntegerMinMax:
603     return Instruction::ICmp;
604   case RK_FloatMinMax:
605     return Instruction::FCmp;
606   default:
607     llvm_unreachable("Unknown recurrence operation");
608   }
609 }
610 
611 Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
612                                             MinMaxRecurrenceKind RK,
613                                             Value *Left, Value *Right) {
614   CmpInst::Predicate P = CmpInst::ICMP_NE;
615   switch (RK) {
616   default:
617     llvm_unreachable("Unknown min/max recurrence kind");
618   case MRK_UIntMin:
619     P = CmpInst::ICMP_ULT;
620     break;
621   case MRK_UIntMax:
622     P = CmpInst::ICMP_UGT;
623     break;
624   case MRK_SIntMin:
625     P = CmpInst::ICMP_SLT;
626     break;
627   case MRK_SIntMax:
628     P = CmpInst::ICMP_SGT;
629     break;
630   case MRK_FloatMin:
631     P = CmpInst::FCMP_OLT;
632     break;
633   case MRK_FloatMax:
634     P = CmpInst::FCMP_OGT;
635     break;
636   }
637 
638   // We only match FP sequences with unsafe algebra, so we can unconditionally
639   // set it on any generated instructions.
640   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
641   FastMathFlags FMF;
642   FMF.setUnsafeAlgebra();
643   Builder.setFastMathFlags(FMF);
644 
645   Value *Cmp;
646   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
647     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
648   else
649     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
650 
651   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
652   return Select;
653 }
654 
655 InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
656                                          ConstantInt *Step)
657   : StartValue(Start), IK(K), StepValue(Step) {
658   assert(IK != IK_NoInduction && "Not an induction");
659   assert(StartValue && "StartValue is null");
660   assert(StepValue && !StepValue->isZero() && "StepValue is zero");
661   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
662          "StartValue is not a pointer for pointer induction");
663   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
664          "StartValue is not an integer for integer induction");
665   assert(StepValue->getType()->isIntegerTy() &&
666          "StepValue is not an integer");
667 }
668 
669 int InductionDescriptor::getConsecutiveDirection() const {
670   if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
671     return StepValue->getSExtValue();
672   return 0;
673 }
674 
675 Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
676   switch (IK) {
677   case IK_IntInduction:
678     assert(Index->getType() == StartValue->getType() &&
679            "Index type does not match StartValue type");
680     if (StepValue->isMinusOne())
681       return B.CreateSub(StartValue, Index);
682     if (!StepValue->isOne())
683       Index = B.CreateMul(Index, StepValue);
684     return B.CreateAdd(StartValue, Index);
685 
686   case IK_PtrInduction:
687     assert(Index->getType() == StepValue->getType() &&
688            "Index type does not match StepValue type");
689     if (StepValue->isMinusOne())
690       Index = B.CreateNeg(Index);
691     else if (!StepValue->isOne())
692       Index = B.CreateMul(Index, StepValue);
693     return B.CreateGEP(nullptr, StartValue, Index);
694 
695   case IK_NoInduction:
696     return nullptr;
697   }
698   llvm_unreachable("invalid enum");
699 }
700 
701 bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
702                                          InductionDescriptor &D) {
703   Type *PhiTy = Phi->getType();
704   // We only handle integer and pointer inductions variables.
705   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
706     return false;
707 
708   // Check that the PHI is consecutive.
709   const SCEV *PhiScev = SE->getSCEV(Phi);
710   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
711   if (!AR) {
712     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
713     return false;
714   }
715 
716   assert(AR->getLoop()->getHeader() == Phi->getParent() &&
717          "PHI is an AddRec for a different loop?!");
718   Value *StartValue =
719     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
720   const SCEV *Step = AR->getStepRecurrence(*SE);
721   // Calculate the pointer stride and check if it is consecutive.
722   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
723   if (!C)
724     return false;
725 
726   ConstantInt *CV = C->getValue();
727   if (PhiTy->isIntegerTy()) {
728     D = InductionDescriptor(StartValue, IK_IntInduction, CV);
729     return true;
730   }
731 
732   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
733   Type *PointerElementType = PhiTy->getPointerElementType();
734   // The pointer stride cannot be determined if the pointer element type is not
735   // sized.
736   if (!PointerElementType->isSized())
737     return false;
738 
739   const DataLayout &DL = Phi->getModule()->getDataLayout();
740   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
741   if (!Size)
742     return false;
743 
744   int64_t CVSize = CV->getSExtValue();
745   if (CVSize % Size)
746     return false;
747   auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
748 
749   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
750   return true;
751 }
752 
753 /// \brief Returns the instructions that use values defined in the loop.
754 SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
755   SmallVector<Instruction *, 8> UsedOutside;
756 
757   for (auto *Block : L->getBlocks())
758     // FIXME: I believe that this could use copy_if if the Inst reference could
759     // be adapted into a pointer.
760     for (auto &Inst : *Block) {
761       auto Users = Inst.users();
762       if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
763             auto *Use = cast<Instruction>(U);
764             return !L->contains(Use->getParent());
765           }))
766         UsedOutside.push_back(&Inst);
767     }
768 
769   return UsedOutside;
770 }
771 
772 void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
773   // By definition, all loop passes need the LoopInfo analysis and the
774   // Dominator tree it depends on. Because they all participate in the loop
775   // pass manager, they must also preserve these.
776   AU.addRequired<DominatorTreeWrapperPass>();
777   AU.addPreserved<DominatorTreeWrapperPass>();
778   AU.addRequired<LoopInfoWrapperPass>();
779   AU.addPreserved<LoopInfoWrapperPass>();
780 
781   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
782   // here because users shouldn't directly get them from this header.
783   extern char &LoopSimplifyID;
784   extern char &LCSSAID;
785   AU.addRequiredID(LoopSimplifyID);
786   AU.addPreservedID(LoopSimplifyID);
787   AU.addRequiredID(LCSSAID);
788   AU.addPreservedID(LCSSAID);
789 
790   // Loop passes are designed to run inside of a loop pass manager which means
791   // that any function analyses they require must be required by the first loop
792   // pass in the manager (so that it is computed before the loop pass manager
793   // runs) and preserved by all loop pasess in the manager. To make this
794   // reasonably robust, the set needed for most loop passes is maintained here.
795   // If your loop pass requires an analysis not listed here, you will need to
796   // carefully audit the loop pass manager nesting structure that results.
797   AU.addRequired<AAResultsWrapperPass>();
798   AU.addPreserved<AAResultsWrapperPass>();
799   AU.addPreserved<BasicAAWrapperPass>();
800   AU.addPreserved<GlobalsAAWrapperPass>();
801   AU.addPreserved<SCEVAAWrapperPass>();
802   AU.addRequired<ScalarEvolutionWrapperPass>();
803   AU.addPreserved<ScalarEvolutionWrapperPass>();
804 }
805 
806 /// Manually defined generic "LoopPass" dependency initialization. This is used
807 /// to initialize the exact set of passes from above in \c
808 /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
809 /// with:
810 ///
811 ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
812 ///
813 /// As-if "LoopPass" were a pass.
814 void llvm::initializeLoopPassPass(PassRegistry &Registry) {
815   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
816   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
817   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
818   INITIALIZE_PASS_DEPENDENCY(LCSSA)
819   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
820   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
821   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
822   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
823   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
824 }
825