176aa662cSKarthik Bhat //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
276aa662cSKarthik Bhat //
376aa662cSKarthik Bhat //                     The LLVM Compiler Infrastructure
476aa662cSKarthik Bhat //
576aa662cSKarthik Bhat // This file is distributed under the University of Illinois Open Source
676aa662cSKarthik Bhat // License. See LICENSE.TXT for details.
776aa662cSKarthik Bhat //
876aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
976aa662cSKarthik Bhat //
1076aa662cSKarthik Bhat // This file defines common loop utility functions.
1176aa662cSKarthik Bhat //
1276aa662cSKarthik Bhat //===----------------------------------------------------------------------===//
1376aa662cSKarthik Bhat 
1431088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
1531088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
1676aa662cSKarthik Bhat #include "llvm/Analysis/LoopInfo.h"
1731088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
1845d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
19c434d091SElena Demikhovsky #include "llvm/Analysis/ScalarEvolutionExpander.h"
2045d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2131088a9dSChandler Carruth #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
2231088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
2376aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
2445d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
2576aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
2676aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
2731088a9dSChandler Carruth #include "llvm/Pass.h"
2876aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
2976aa662cSKarthik Bhat #include "llvm/Transforms/Utils/LoopUtils.h"
3076aa662cSKarthik Bhat 
3176aa662cSKarthik Bhat using namespace llvm;
3276aa662cSKarthik Bhat using namespace llvm::PatternMatch;
3376aa662cSKarthik Bhat 
3476aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
3576aa662cSKarthik Bhat 
360a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
3776aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
3876aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3976aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
4076aa662cSKarthik Bhat       return false;
4176aa662cSKarthik Bhat   return true;
4276aa662cSKarthik Bhat }
4376aa662cSKarthik Bhat 
44c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
45c94f8e29SChad Rosier   switch (Kind) {
46c94f8e29SChad Rosier   default:
47c94f8e29SChad Rosier     break;
48c94f8e29SChad Rosier   case RK_IntegerAdd:
49c94f8e29SChad Rosier   case RK_IntegerMult:
50c94f8e29SChad Rosier   case RK_IntegerOr:
51c94f8e29SChad Rosier   case RK_IntegerAnd:
52c94f8e29SChad Rosier   case RK_IntegerXor:
53c94f8e29SChad Rosier   case RK_IntegerMinMax:
54c94f8e29SChad Rosier     return true;
55c94f8e29SChad Rosier   }
56c94f8e29SChad Rosier   return false;
57c94f8e29SChad Rosier }
58c94f8e29SChad Rosier 
59c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
60c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
61c94f8e29SChad Rosier }
62c94f8e29SChad Rosier 
63c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
64c94f8e29SChad Rosier   switch (Kind) {
65c94f8e29SChad Rosier   default:
66c94f8e29SChad Rosier     break;
67c94f8e29SChad Rosier   case RK_IntegerAdd:
68c94f8e29SChad Rosier   case RK_IntegerMult:
69c94f8e29SChad Rosier   case RK_FloatAdd:
70c94f8e29SChad Rosier   case RK_FloatMult:
71c94f8e29SChad Rosier     return true;
72c94f8e29SChad Rosier   }
73c94f8e29SChad Rosier   return false;
74c94f8e29SChad Rosier }
75c94f8e29SChad Rosier 
76c94f8e29SChad Rosier Instruction *
77c94f8e29SChad Rosier RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
78c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &Visited,
79c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &CI) {
80c94f8e29SChad Rosier   if (!Phi->hasOneUse())
81c94f8e29SChad Rosier     return Phi;
82c94f8e29SChad Rosier 
83c94f8e29SChad Rosier   const APInt *M = nullptr;
84c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
85c94f8e29SChad Rosier 
86c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
87c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
88c94f8e29SChad Rosier   if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
89c94f8e29SChad Rosier                            m_And(m_APInt(M), m_Instruction(I))))) {
90c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
91c94f8e29SChad Rosier     if (Bits > 0) {
92c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
93c94f8e29SChad Rosier       Visited.insert(Phi);
94c94f8e29SChad Rosier       CI.insert(J);
95c94f8e29SChad Rosier       return J;
96c94f8e29SChad Rosier     }
97c94f8e29SChad Rosier   }
98c94f8e29SChad Rosier   return Phi;
99c94f8e29SChad Rosier }
100c94f8e29SChad Rosier 
101c94f8e29SChad Rosier bool RecurrenceDescriptor::getSourceExtensionKind(
102c94f8e29SChad Rosier     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
103c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &Visited,
104c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &CI) {
105c94f8e29SChad Rosier 
106c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
107c94f8e29SChad Rosier   bool FoundOneOperand = false;
10829dc0f70SMatthew Simpson   unsigned DstSize = RT->getPrimitiveSizeInBits();
109c94f8e29SChad Rosier   Worklist.push_back(Exit);
110c94f8e29SChad Rosier 
111c94f8e29SChad Rosier   // Traverse the instructions in the reduction expression, beginning with the
112c94f8e29SChad Rosier   // exit value.
113c94f8e29SChad Rosier   while (!Worklist.empty()) {
114c94f8e29SChad Rosier     Instruction *I = Worklist.pop_back_val();
115c94f8e29SChad Rosier     for (Use &U : I->operands()) {
116c94f8e29SChad Rosier 
117c94f8e29SChad Rosier       // Terminate the traversal if the operand is not an instruction, or we
118c94f8e29SChad Rosier       // reach the starting value.
119c94f8e29SChad Rosier       Instruction *J = dyn_cast<Instruction>(U.get());
120c94f8e29SChad Rosier       if (!J || J == Start)
121c94f8e29SChad Rosier         continue;
122c94f8e29SChad Rosier 
123c94f8e29SChad Rosier       // Otherwise, investigate the operation if it is also in the expression.
124c94f8e29SChad Rosier       if (Visited.count(J)) {
125c94f8e29SChad Rosier         Worklist.push_back(J);
126c94f8e29SChad Rosier         continue;
127c94f8e29SChad Rosier       }
128c94f8e29SChad Rosier 
129c94f8e29SChad Rosier       // If the operand is not in Visited, it is not a reduction operation, but
130c94f8e29SChad Rosier       // it does feed into one. Make sure it is either a single-use sign- or
13129dc0f70SMatthew Simpson       // zero-extend instruction.
132c94f8e29SChad Rosier       CastInst *Cast = dyn_cast<CastInst>(J);
133c94f8e29SChad Rosier       bool IsSExtInst = isa<SExtInst>(J);
13429dc0f70SMatthew Simpson       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
13529dc0f70SMatthew Simpson         return false;
13629dc0f70SMatthew Simpson 
13729dc0f70SMatthew Simpson       // Ensure the source type of the extend is no larger than the reduction
13829dc0f70SMatthew Simpson       // type. It is not necessary for the types to be identical.
13929dc0f70SMatthew Simpson       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
14029dc0f70SMatthew Simpson       if (SrcSize > DstSize)
141c94f8e29SChad Rosier         return false;
142c94f8e29SChad Rosier 
143c94f8e29SChad Rosier       // Furthermore, ensure that all such extends are of the same kind.
144c94f8e29SChad Rosier       if (FoundOneOperand) {
145c94f8e29SChad Rosier         if (IsSigned != IsSExtInst)
146c94f8e29SChad Rosier           return false;
147c94f8e29SChad Rosier       } else {
148c94f8e29SChad Rosier         FoundOneOperand = true;
149c94f8e29SChad Rosier         IsSigned = IsSExtInst;
150c94f8e29SChad Rosier       }
151c94f8e29SChad Rosier 
15229dc0f70SMatthew Simpson       // Lastly, if the source type of the extend matches the reduction type,
15329dc0f70SMatthew Simpson       // add the extend to CI so that we can avoid accounting for it in the
15429dc0f70SMatthew Simpson       // cost model.
15529dc0f70SMatthew Simpson       if (SrcSize == DstSize)
156c94f8e29SChad Rosier         CI.insert(Cast);
157c94f8e29SChad Rosier     }
158c94f8e29SChad Rosier   }
159c94f8e29SChad Rosier   return true;
160c94f8e29SChad Rosier }
161c94f8e29SChad Rosier 
1620a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
16376aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
1640a91310cSTyler Nowicki                                            RecurrenceDescriptor &RedDes) {
16576aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
16676aa662cSKarthik Bhat     return false;
16776aa662cSKarthik Bhat 
16876aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
16976aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
17076aa662cSKarthik Bhat     return false;
17176aa662cSKarthik Bhat 
17276aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
17376aa662cSKarthik Bhat   // preheader.
17476aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
17576aa662cSKarthik Bhat 
17676aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
17776aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
17876aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
17976aa662cSKarthik Bhat   // which ends in the phi node).
18076aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
18176aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
18276aa662cSKarthik Bhat   bool FoundReduxOp = false;
18376aa662cSKarthik Bhat 
18476aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
18576aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
18676aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
18776aa662cSKarthik Bhat   // must include the original PHI.
18876aa662cSKarthik Bhat   bool FoundStartPHI = false;
18976aa662cSKarthik Bhat 
19076aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
19176aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
19276aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
19376aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
19427b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
19576aa662cSKarthik Bhat 
196c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
197c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
198c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
199c94f8e29SChad Rosier   Instruction *Start = Phi;
200c94f8e29SChad Rosier   bool IsSigned = false;
201c94f8e29SChad Rosier 
20276aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
20376aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
204c94f8e29SChad Rosier 
205c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
206c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
207c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
208c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
209c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
210c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
211c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
212c94f8e29SChad Rosier       return false;
213c94f8e29SChad Rosier   } else {
214c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
215c94f8e29SChad Rosier       return false;
216c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
217c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
218c94f8e29SChad Rosier   }
219c94f8e29SChad Rosier 
220c94f8e29SChad Rosier   Worklist.push_back(Start);
221c94f8e29SChad Rosier   VisitedInsts.insert(Start);
22276aa662cSKarthik Bhat 
22376aa662cSKarthik Bhat   // A value in the reduction can be used:
22476aa662cSKarthik Bhat   //  - By the reduction:
22576aa662cSKarthik Bhat   //      - Reduction operation:
22676aa662cSKarthik Bhat   //        - One use of reduction value (safe).
22776aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
22876aa662cSKarthik Bhat   //      - PHI:
22976aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
23076aa662cSKarthik Bhat   //        - Otherwise, not safe.
23176aa662cSKarthik Bhat   //  - By one instruction outside of the loop (safe).
23276aa662cSKarthik Bhat   //  - By further instructions outside of the loop (not safe).
23376aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
23476aa662cSKarthik Bhat   //    This is either:
23576aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
23676aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
23776aa662cSKarthik Bhat   while (!Worklist.empty()) {
23876aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
23976aa662cSKarthik Bhat     Worklist.pop_back();
24076aa662cSKarthik Bhat 
24176aa662cSKarthik Bhat     // No Users.
24276aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
24376aa662cSKarthik Bhat     // a reduction variable.
24476aa662cSKarthik Bhat     if (Cur->use_empty())
24576aa662cSKarthik Bhat       return false;
24676aa662cSKarthik Bhat 
24776aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
24876aa662cSKarthik Bhat 
24976aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
25076aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
25176aa662cSKarthik Bhat       return false;
25276aa662cSKarthik Bhat 
25376aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
25476aa662cSKarthik Bhat     // LHS is the reduction variable.
25576aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
25676aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
25776aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
25876aa662cSKarthik Bhat       return false;
25976aa662cSKarthik Bhat 
260c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
261c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
262c94f8e29SChad Rosier     // type-promoted).
263c94f8e29SChad Rosier     if (Cur != Start) {
2640a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2650a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
26676aa662cSKarthik Bhat         return false;
267c94f8e29SChad Rosier     }
26876aa662cSKarthik Bhat 
26976aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
27076aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
27176aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
27276aa662cSKarthik Bhat       return false;
27376aa662cSKarthik Bhat 
27476aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
27576aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
27676aa662cSKarthik Bhat       return false;
27776aa662cSKarthik Bhat 
27876aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
27976aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
28076aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28176aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
28276aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28376aa662cSKarthik Bhat 
28476aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
285c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
28676aa662cSKarthik Bhat 
28776aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
28876aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
28976aa662cSKarthik Bhat     // nodes once we get to them.
29076aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
29176aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
29276aa662cSKarthik Bhat     for (User *U : Cur->users()) {
29376aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
29476aa662cSKarthik Bhat 
29576aa662cSKarthik Bhat       // Check if we found the exit user.
29676aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
29776aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
29876aa662cSKarthik Bhat         // Exit if you find multiple outside users or if the header phi node is
29976aa662cSKarthik Bhat         // being used. In this case the user uses the value of the previous
30076aa662cSKarthik Bhat         // iteration, in which case we would loose "VF-1" iterations of the
30176aa662cSKarthik Bhat         // reduction operation if we vectorize.
30276aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
30376aa662cSKarthik Bhat           return false;
30476aa662cSKarthik Bhat 
30576aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
30676aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
30776aa662cSKarthik Bhat         // operations on the value.
30876aa662cSKarthik Bhat         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
30976aa662cSKarthik Bhat           return false;
31076aa662cSKarthik Bhat 
31176aa662cSKarthik Bhat         ExitInstruction = Cur;
31276aa662cSKarthik Bhat         continue;
31376aa662cSKarthik Bhat       }
31476aa662cSKarthik Bhat 
31576aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
31676aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
31776aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
31827b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
31976aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
32076aa662cSKarthik Bhat         if (isa<PHINode>(UI))
32176aa662cSKarthik Bhat           PHIs.push_back(UI);
32276aa662cSKarthik Bhat         else
32376aa662cSKarthik Bhat           NonPHIs.push_back(UI);
32476aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
32576aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
32676aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3270a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
32876aa662cSKarthik Bhat         return false;
32976aa662cSKarthik Bhat 
33076aa662cSKarthik Bhat       // Remember that we completed the cycle.
33176aa662cSKarthik Bhat       if (UI == Phi)
33276aa662cSKarthik Bhat         FoundStartPHI = true;
33376aa662cSKarthik Bhat     }
33476aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
33576aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
33676aa662cSKarthik Bhat   }
33776aa662cSKarthik Bhat 
33876aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
33976aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
34076aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
34176aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
34276aa662cSKarthik Bhat     return false;
34376aa662cSKarthik Bhat 
34476aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
34576aa662cSKarthik Bhat     return false;
34676aa662cSKarthik Bhat 
347c94f8e29SChad Rosier   // If we think Phi may have been type-promoted, we also need to ensure that
348c94f8e29SChad Rosier   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
349c94f8e29SChad Rosier   // so, we will be able to evaluate the reduction in the narrower bit width.
350c94f8e29SChad Rosier   if (Start != Phi)
351c94f8e29SChad Rosier     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
352c94f8e29SChad Rosier                                 IsSigned, VisitedInsts, CastInsts))
353c94f8e29SChad Rosier       return false;
354c94f8e29SChad Rosier 
35576aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
35676aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
35776aa662cSKarthik Bhat 
35876aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
3590a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
36076aa662cSKarthik Bhat 
36176aa662cSKarthik Bhat   // Save the description of this reduction variable.
362c94f8e29SChad Rosier   RecurrenceDescriptor RD(
363c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
364c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
36576aa662cSKarthik Bhat   RedDes = RD;
36676aa662cSKarthik Bhat 
36776aa662cSKarthik Bhat   return true;
36876aa662cSKarthik Bhat }
36976aa662cSKarthik Bhat 
37076aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
37176aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
37227b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
37327b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
37476aa662cSKarthik Bhat 
37576aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
37676aa662cSKarthik Bhat          "Expect a select instruction");
37776aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
37876aa662cSKarthik Bhat   SelectInst *Select = nullptr;
37976aa662cSKarthik Bhat 
38076aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
38176aa662cSKarthik Bhat   // select.
38276aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
38376aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
38427b2c39eSTyler Nowicki       return InstDesc(false, I);
38527b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
38676aa662cSKarthik Bhat   }
38776aa662cSKarthik Bhat 
38876aa662cSKarthik Bhat   // Only handle single use cases for now.
38976aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
39027b2c39eSTyler Nowicki     return InstDesc(false, I);
39176aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
39276aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
39327b2c39eSTyler Nowicki     return InstDesc(false, I);
39476aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
39527b2c39eSTyler Nowicki     return InstDesc(false, I);
39676aa662cSKarthik Bhat 
39776aa662cSKarthik Bhat   Value *CmpLeft;
39876aa662cSKarthik Bhat   Value *CmpRight;
39976aa662cSKarthik Bhat 
40076aa662cSKarthik Bhat   // Look for a min/max pattern.
40176aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40227b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
40376aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40427b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
40576aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40627b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
40776aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40827b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
40976aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41027b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
41176aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41227b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
41376aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41427b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
41576aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41627b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
41776aa662cSKarthik Bhat 
41827b2c39eSTyler Nowicki   return InstDesc(false, I);
41976aa662cSKarthik Bhat }
42076aa662cSKarthik Bhat 
42127b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4220a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
42327b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
42476aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
425c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
426c1a86f58STyler Nowicki   if (!UAI && FP && !I->hasUnsafeAlgebra())
427c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
428c1a86f58STyler Nowicki 
42976aa662cSKarthik Bhat   switch (I->getOpcode()) {
43076aa662cSKarthik Bhat   default:
43127b2c39eSTyler Nowicki     return InstDesc(false, I);
43276aa662cSKarthik Bhat   case Instruction::PHI:
43310a1e8b1STim Northover     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
43476aa662cSKarthik Bhat   case Instruction::Sub:
43576aa662cSKarthik Bhat   case Instruction::Add:
43627b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
43776aa662cSKarthik Bhat   case Instruction::Mul:
43827b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
43976aa662cSKarthik Bhat   case Instruction::And:
44027b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
44176aa662cSKarthik Bhat   case Instruction::Or:
44227b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
44376aa662cSKarthik Bhat   case Instruction::Xor:
44427b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
44576aa662cSKarthik Bhat   case Instruction::FMul:
446c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
44776aa662cSKarthik Bhat   case Instruction::FSub:
44876aa662cSKarthik Bhat   case Instruction::FAdd:
449c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
45076aa662cSKarthik Bhat   case Instruction::FCmp:
45176aa662cSKarthik Bhat   case Instruction::ICmp:
45276aa662cSKarthik Bhat   case Instruction::Select:
45376aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
45476aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
45527b2c39eSTyler Nowicki       return InstDesc(false, I);
45676aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
45776aa662cSKarthik Bhat   }
45876aa662cSKarthik Bhat }
45976aa662cSKarthik Bhat 
4600a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
46176aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
46276aa662cSKarthik Bhat   unsigned NumUses = 0;
46376aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
46476aa662cSKarthik Bhat        ++Use) {
46576aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
46676aa662cSKarthik Bhat       ++NumUses;
46776aa662cSKarthik Bhat     if (NumUses > 1)
46876aa662cSKarthik Bhat       return true;
46976aa662cSKarthik Bhat   }
47076aa662cSKarthik Bhat 
47176aa662cSKarthik Bhat   return false;
47276aa662cSKarthik Bhat }
4730a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
4740a91310cSTyler Nowicki                                           RecurrenceDescriptor &RedDes) {
47576aa662cSKarthik Bhat 
47676aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
47776aa662cSKarthik Bhat   Function &F = *Header->getParent();
4788dd66e57SNirav Dave   bool HasFunNoNaNAttr =
47976aa662cSKarthik Bhat       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
48076aa662cSKarthik Bhat 
48176aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
48276aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
48376aa662cSKarthik Bhat     return true;
48476aa662cSKarthik Bhat   }
48576aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
48676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
48776aa662cSKarthik Bhat     return true;
48876aa662cSKarthik Bhat   }
48976aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
49076aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
49176aa662cSKarthik Bhat     return true;
49276aa662cSKarthik Bhat   }
49376aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
49476aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
49576aa662cSKarthik Bhat     return true;
49676aa662cSKarthik Bhat   }
49776aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
49876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
49976aa662cSKarthik Bhat     return true;
50076aa662cSKarthik Bhat   }
50176aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
50276aa662cSKarthik Bhat                       RedDes)) {
50376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
50476aa662cSKarthik Bhat     return true;
50576aa662cSKarthik Bhat   }
50676aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
50776aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
50876aa662cSKarthik Bhat     return true;
50976aa662cSKarthik Bhat   }
51076aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
51176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
51276aa662cSKarthik Bhat     return true;
51376aa662cSKarthik Bhat   }
51476aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
51576aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
51676aa662cSKarthik Bhat     return true;
51776aa662cSKarthik Bhat   }
51876aa662cSKarthik Bhat   // Not a reduction of known type.
51976aa662cSKarthik Bhat   return false;
52076aa662cSKarthik Bhat }
52176aa662cSKarthik Bhat 
52229c997c1SMatthew Simpson bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
52329c997c1SMatthew Simpson                                                   DominatorTree *DT) {
52429c997c1SMatthew Simpson 
52529c997c1SMatthew Simpson   // Ensure the phi node is in the loop header and has two incoming values.
52629c997c1SMatthew Simpson   if (Phi->getParent() != TheLoop->getHeader() ||
52729c997c1SMatthew Simpson       Phi->getNumIncomingValues() != 2)
52829c997c1SMatthew Simpson     return false;
52929c997c1SMatthew Simpson 
53029c997c1SMatthew Simpson   // Ensure the loop has a preheader and a single latch block. The loop
53129c997c1SMatthew Simpson   // vectorizer will need the latch to set up the next iteration of the loop.
53229c997c1SMatthew Simpson   auto *Preheader = TheLoop->getLoopPreheader();
53329c997c1SMatthew Simpson   auto *Latch = TheLoop->getLoopLatch();
53429c997c1SMatthew Simpson   if (!Preheader || !Latch)
53529c997c1SMatthew Simpson     return false;
53629c997c1SMatthew Simpson 
53729c997c1SMatthew Simpson   // Ensure the phi node's incoming blocks are the loop preheader and latch.
53829c997c1SMatthew Simpson   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
53929c997c1SMatthew Simpson       Phi->getBasicBlockIndex(Latch) < 0)
54029c997c1SMatthew Simpson     return false;
54129c997c1SMatthew Simpson 
54229c997c1SMatthew Simpson   // Get the previous value. The previous value comes from the latch edge while
54329c997c1SMatthew Simpson   // the initial value comes form the preheader edge.
54429c997c1SMatthew Simpson   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
54553207a99SMatthew Simpson   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
54629c997c1SMatthew Simpson     return false;
54729c997c1SMatthew Simpson 
54829c997c1SMatthew Simpson   // Ensure every user of the phi node is dominated by the previous value. The
54929c997c1SMatthew Simpson   // dominance requirement ensures the loop vectorizer will not need to
55029c997c1SMatthew Simpson   // vectorize the initial value prior to the first iteration of the loop.
55129c997c1SMatthew Simpson   for (User *U : Phi->users())
55229c997c1SMatthew Simpson     if (auto *I = dyn_cast<Instruction>(U))
55329c997c1SMatthew Simpson       if (!DT->dominates(Previous, I))
55429c997c1SMatthew Simpson         return false;
55529c997c1SMatthew Simpson 
55629c997c1SMatthew Simpson   return true;
55729c997c1SMatthew Simpson }
55829c997c1SMatthew Simpson 
55976aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
56076aa662cSKarthik Bhat /// the operation K.
5610a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
5620a91310cSTyler Nowicki                                                       Type *Tp) {
56376aa662cSKarthik Bhat   switch (K) {
56476aa662cSKarthik Bhat   case RK_IntegerXor:
56576aa662cSKarthik Bhat   case RK_IntegerAdd:
56676aa662cSKarthik Bhat   case RK_IntegerOr:
56776aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
56876aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
56976aa662cSKarthik Bhat   case RK_IntegerMult:
57076aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
57176aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
57276aa662cSKarthik Bhat   case RK_IntegerAnd:
57376aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
57476aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
57576aa662cSKarthik Bhat   case RK_FloatMult:
57676aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
57776aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
57876aa662cSKarthik Bhat   case RK_FloatAdd:
57976aa662cSKarthik Bhat     // Adding zero to a number does not change it.
58076aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
58176aa662cSKarthik Bhat   default:
5820a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
58376aa662cSKarthik Bhat   }
58476aa662cSKarthik Bhat }
58576aa662cSKarthik Bhat 
5860a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
5870a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
58876aa662cSKarthik Bhat   switch (Kind) {
58976aa662cSKarthik Bhat   case RK_IntegerAdd:
59076aa662cSKarthik Bhat     return Instruction::Add;
59176aa662cSKarthik Bhat   case RK_IntegerMult:
59276aa662cSKarthik Bhat     return Instruction::Mul;
59376aa662cSKarthik Bhat   case RK_IntegerOr:
59476aa662cSKarthik Bhat     return Instruction::Or;
59576aa662cSKarthik Bhat   case RK_IntegerAnd:
59676aa662cSKarthik Bhat     return Instruction::And;
59776aa662cSKarthik Bhat   case RK_IntegerXor:
59876aa662cSKarthik Bhat     return Instruction::Xor;
59976aa662cSKarthik Bhat   case RK_FloatMult:
60076aa662cSKarthik Bhat     return Instruction::FMul;
60176aa662cSKarthik Bhat   case RK_FloatAdd:
60276aa662cSKarthik Bhat     return Instruction::FAdd;
60376aa662cSKarthik Bhat   case RK_IntegerMinMax:
60476aa662cSKarthik Bhat     return Instruction::ICmp;
60576aa662cSKarthik Bhat   case RK_FloatMinMax:
60676aa662cSKarthik Bhat     return Instruction::FCmp;
60776aa662cSKarthik Bhat   default:
6080a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
60976aa662cSKarthik Bhat   }
61076aa662cSKarthik Bhat }
61176aa662cSKarthik Bhat 
61227b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
61327b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
61476aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
61576aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
61676aa662cSKarthik Bhat   switch (RK) {
61776aa662cSKarthik Bhat   default:
6180a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
61927b2c39eSTyler Nowicki   case MRK_UIntMin:
62076aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
62176aa662cSKarthik Bhat     break;
62227b2c39eSTyler Nowicki   case MRK_UIntMax:
62376aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
62476aa662cSKarthik Bhat     break;
62527b2c39eSTyler Nowicki   case MRK_SIntMin:
62676aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
62776aa662cSKarthik Bhat     break;
62827b2c39eSTyler Nowicki   case MRK_SIntMax:
62976aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
63076aa662cSKarthik Bhat     break;
63127b2c39eSTyler Nowicki   case MRK_FloatMin:
63276aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
63376aa662cSKarthik Bhat     break;
63427b2c39eSTyler Nowicki   case MRK_FloatMax:
63576aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
63676aa662cSKarthik Bhat     break;
63776aa662cSKarthik Bhat   }
63876aa662cSKarthik Bhat 
63950a4c27fSJames Molloy   // We only match FP sequences with unsafe algebra, so we can unconditionally
64050a4c27fSJames Molloy   // set it on any generated instructions.
64150a4c27fSJames Molloy   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
64250a4c27fSJames Molloy   FastMathFlags FMF;
64350a4c27fSJames Molloy   FMF.setUnsafeAlgebra();
644a252815bSSanjay Patel   Builder.setFastMathFlags(FMF);
64550a4c27fSJames Molloy 
64676aa662cSKarthik Bhat   Value *Cmp;
64727b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
64876aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
64976aa662cSKarthik Bhat   else
65076aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
65176aa662cSKarthik Bhat 
65276aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
65376aa662cSKarthik Bhat   return Select;
65476aa662cSKarthik Bhat }
65524e6cc2dSKarthik Bhat 
6561bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
657c434d091SElena Demikhovsky                                          const SCEV *Step)
658c434d091SElena Demikhovsky   : StartValue(Start), IK(K), Step(Step) {
6591bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
660c434d091SElena Demikhovsky 
661c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
662c434d091SElena Demikhovsky   // itself should not be null.
6631bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
6641bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
6651bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
6661bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
6671bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
668c434d091SElena Demikhovsky 
669c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
670c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
671c434d091SElena Demikhovsky          "Step value is zero");
672c434d091SElena Demikhovsky 
673c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
674c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
675c434d091SElena Demikhovsky   assert(Step->getType()->isIntegerTy() && "StepValue is not an integer");
6761bbf15c5SJames Molloy }
6771bbf15c5SJames Molloy 
6781bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
679c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
680c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
681c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
6821bbf15c5SJames Molloy   return 0;
6831bbf15c5SJames Molloy }
6841bbf15c5SJames Molloy 
685c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
686c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
687c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
688c434d091SElena Demikhovsky   return nullptr;
689c434d091SElena Demikhovsky }
690c434d091SElena Demikhovsky 
691c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
692c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
693c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
694c434d091SElena Demikhovsky 
695c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
6961bbf15c5SJames Molloy   switch (IK) {
697c434d091SElena Demikhovsky   case IK_IntInduction: {
6981bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
6991bbf15c5SJames Molloy            "Index type does not match StartValue type");
700c434d091SElena Demikhovsky 
701c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
702c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
703c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
704c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
705c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
706c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
707c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
708c434d091SElena Demikhovsky 
709c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
710c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
7111bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
712c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
713c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
7141bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
715c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
716c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
717c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
718c434d091SElena Demikhovsky   }
719c434d091SElena Demikhovsky   case IK_PtrInduction: {
720c434d091SElena Demikhovsky     assert(Index->getType() == Step->getType() &&
7211bbf15c5SJames Molloy            "Index type does not match StepValue type");
722c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
723c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
724c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
725c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
7261bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
727c434d091SElena Demikhovsky   }
7281bbf15c5SJames Molloy   case IK_NoInduction:
7291bbf15c5SJames Molloy     return nullptr;
7301bbf15c5SJames Molloy   }
7311bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
7321bbf15c5SJames Molloy }
7331bbf15c5SJames Molloy 
734c05bab8aSSilviu Baranga bool InductionDescriptor::isInductionPHI(PHINode *Phi,
735c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
736c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
737c05bab8aSSilviu Baranga                                          bool Assume) {
738c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
739c05bab8aSSilviu Baranga   // We only handle integer and pointer inductions variables.
740c05bab8aSSilviu Baranga   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
741c05bab8aSSilviu Baranga     return false;
742c05bab8aSSilviu Baranga 
743c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
744c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
745c05bab8aSSilviu Baranga 
746c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
747c05bab8aSSilviu Baranga   if (Assume && !AR)
748c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
749c05bab8aSSilviu Baranga 
750c05bab8aSSilviu Baranga   if (!AR) {
751c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
752c05bab8aSSilviu Baranga     return false;
753c05bab8aSSilviu Baranga   }
754c05bab8aSSilviu Baranga 
755c05bab8aSSilviu Baranga   return isInductionPHI(Phi, PSE.getSE(), D, AR);
756c05bab8aSSilviu Baranga }
757c05bab8aSSilviu Baranga 
758c05bab8aSSilviu Baranga bool InductionDescriptor::isInductionPHI(PHINode *Phi,
759c05bab8aSSilviu Baranga                                          ScalarEvolution *SE,
760c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
761c05bab8aSSilviu Baranga                                          const SCEV *Expr) {
76224e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
76324e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
76424e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
76524e6cc2dSKarthik Bhat     return false;
76624e6cc2dSKarthik Bhat 
76724e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
768c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
76924e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
770c05bab8aSSilviu Baranga 
77124e6cc2dSKarthik Bhat   if (!AR) {
77224e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
77324e6cc2dSKarthik Bhat     return false;
77424e6cc2dSKarthik Bhat   }
77524e6cc2dSKarthik Bhat 
7761bbf15c5SJames Molloy   assert(AR->getLoop()->getHeader() == Phi->getParent() &&
7771bbf15c5SJames Molloy          "PHI is an AddRec for a different loop?!");
7781bbf15c5SJames Molloy   Value *StartValue =
7791bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
78024e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
78124e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
782c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
783c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
784c434d091SElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, AR->getLoop()))
78524e6cc2dSKarthik Bhat     return false;
78624e6cc2dSKarthik Bhat 
78724e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
788c434d091SElena Demikhovsky     D = InductionDescriptor(StartValue, IK_IntInduction, Step);
78924e6cc2dSKarthik Bhat     return true;
79024e6cc2dSKarthik Bhat   }
79124e6cc2dSKarthik Bhat 
79224e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
793c434d091SElena Demikhovsky   // Pointer induction should be a constant.
794c434d091SElena Demikhovsky   if (!ConstStep)
795c434d091SElena Demikhovsky     return false;
796c434d091SElena Demikhovsky 
797c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
79824e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
79924e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
80024e6cc2dSKarthik Bhat   // sized.
80124e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
80224e6cc2dSKarthik Bhat     return false;
80324e6cc2dSKarthik Bhat 
80424e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
80524e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
806b58f32f7SDavid Majnemer   if (!Size)
807b58f32f7SDavid Majnemer     return false;
808b58f32f7SDavid Majnemer 
80924e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
81024e6cc2dSKarthik Bhat   if (CVSize % Size)
81124e6cc2dSKarthik Bhat     return false;
812c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
813c434d091SElena Demikhovsky                                     true /* signed */);
8141bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
81524e6cc2dSKarthik Bhat   return true;
81624e6cc2dSKarthik Bhat }
817c5b7b555SAshutosh Nema 
818c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
819c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
820c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
821c5b7b555SAshutosh Nema 
822c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
823c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
824c5b7b555SAshutosh Nema     // be adapted into a pointer.
825c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
826c5b7b555SAshutosh Nema       auto Users = Inst.users();
827c5b7b555SAshutosh Nema       if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
828c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
829c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
830c5b7b555SAshutosh Nema           }))
831c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
832c5b7b555SAshutosh Nema     }
833c5b7b555SAshutosh Nema 
834c5b7b555SAshutosh Nema   return UsedOutside;
835c5b7b555SAshutosh Nema }
83631088a9dSChandler Carruth 
83731088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
83831088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
83931088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
84031088a9dSChandler Carruth   // pass manager, they must also preserve these.
84131088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
84231088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
84331088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
84431088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
84531088a9dSChandler Carruth 
84631088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
84731088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
84831088a9dSChandler Carruth   extern char &LoopSimplifyID;
84931088a9dSChandler Carruth   extern char &LCSSAID;
85031088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
85131088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
85231088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
85331088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
85431088a9dSChandler Carruth 
85531088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
85631088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
85731088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
85831088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
85931088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
86031088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
86131088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
86231088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
86331088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
86431088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
86531088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
86631088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
86731088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
86831088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
86931088a9dSChandler Carruth }
87031088a9dSChandler Carruth 
87131088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
87231088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
87331088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
87431088a9dSChandler Carruth /// with:
87531088a9dSChandler Carruth ///
87631088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
87731088a9dSChandler Carruth ///
87831088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
87931088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
88031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
88131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
88231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
883e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
88431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
88531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
88631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
88731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
88831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
88931088a9dSChandler Carruth }
890963341c8SAdam Nemet 
891fe3def7cSAdam Nemet /// \brief Find string metadata for loop
892fe3def7cSAdam Nemet ///
893fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
894fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
895fe3def7cSAdam Nemet /// Optional's not-a-value.
896fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
897fe3def7cSAdam Nemet                                                             StringRef Name) {
898963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
899fe3def7cSAdam Nemet   // Return none if LoopID is false.
900963341c8SAdam Nemet   if (!LoopID)
901fe3def7cSAdam Nemet     return None;
902293be666SAdam Nemet 
903293be666SAdam Nemet   // First operand should refer to the loop id itself.
904293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
905293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
906293be666SAdam Nemet 
907963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
908963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
909963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
910963341c8SAdam Nemet     if (!MD)
911963341c8SAdam Nemet       continue;
912963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
913963341c8SAdam Nemet     if (!S)
914963341c8SAdam Nemet       continue;
915963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
916963341c8SAdam Nemet     if (Name.equals(S->getString()))
917fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
918fe3def7cSAdam Nemet       case 1:
919fe3def7cSAdam Nemet         return nullptr;
920fe3def7cSAdam Nemet       case 2:
921fe3def7cSAdam Nemet         return &MD->getOperand(1);
922fe3def7cSAdam Nemet       default:
923fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
924963341c8SAdam Nemet       }
925fe3def7cSAdam Nemet   }
926fe3def7cSAdam Nemet   return None;
927963341c8SAdam Nemet }
928122f984aSEvgeniy Stepanov 
929122f984aSEvgeniy Stepanov /// Returns true if the instruction in a loop is guaranteed to execute at least
930122f984aSEvgeniy Stepanov /// once.
931122f984aSEvgeniy Stepanov bool llvm::isGuaranteedToExecute(const Instruction &Inst,
932122f984aSEvgeniy Stepanov                                  const DominatorTree *DT, const Loop *CurLoop,
933122f984aSEvgeniy Stepanov                                  const LoopSafetyInfo *SafetyInfo) {
934122f984aSEvgeniy Stepanov   // We have to check to make sure that the instruction dominates all
935122f984aSEvgeniy Stepanov   // of the exit blocks.  If it doesn't, then there is a path out of the loop
936122f984aSEvgeniy Stepanov   // which does not execute this instruction, so we can't hoist it.
937122f984aSEvgeniy Stepanov 
938122f984aSEvgeniy Stepanov   // If the instruction is in the header block for the loop (which is very
939122f984aSEvgeniy Stepanov   // common), it is always guaranteed to dominate the exit blocks.  Since this
940122f984aSEvgeniy Stepanov   // is a common case, and can save some work, check it now.
941122f984aSEvgeniy Stepanov   if (Inst.getParent() == CurLoop->getHeader())
942122f984aSEvgeniy Stepanov     // If there's a throw in the header block, we can't guarantee we'll reach
943122f984aSEvgeniy Stepanov     // Inst.
944122f984aSEvgeniy Stepanov     return !SafetyInfo->HeaderMayThrow;
945122f984aSEvgeniy Stepanov 
946122f984aSEvgeniy Stepanov   // Somewhere in this loop there is an instruction which may throw and make us
947122f984aSEvgeniy Stepanov   // exit the loop.
948122f984aSEvgeniy Stepanov   if (SafetyInfo->MayThrow)
949122f984aSEvgeniy Stepanov     return false;
950122f984aSEvgeniy Stepanov 
951122f984aSEvgeniy Stepanov   // Get the exit blocks for the current loop.
952122f984aSEvgeniy Stepanov   SmallVector<BasicBlock *, 8> ExitBlocks;
953122f984aSEvgeniy Stepanov   CurLoop->getExitBlocks(ExitBlocks);
954122f984aSEvgeniy Stepanov 
955122f984aSEvgeniy Stepanov   // Verify that the block dominates each of the exit blocks of the loop.
956122f984aSEvgeniy Stepanov   for (BasicBlock *ExitBlock : ExitBlocks)
957122f984aSEvgeniy Stepanov     if (!DT->dominates(Inst.getParent(), ExitBlock))
958122f984aSEvgeniy Stepanov       return false;
959122f984aSEvgeniy Stepanov 
960122f984aSEvgeniy Stepanov   // As a degenerate case, if the loop is statically infinite then we haven't
961122f984aSEvgeniy Stepanov   // proven anything since there are no exit blocks.
962122f984aSEvgeniy Stepanov   if (ExitBlocks.empty())
963122f984aSEvgeniy Stepanov     return false;
964122f984aSEvgeniy Stepanov 
965*f1da33e4SEli Friedman   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
966*f1da33e4SEli Friedman   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
967*f1da33e4SEli Friedman   // just a special case of this.)
968122f984aSEvgeniy Stepanov   return true;
969122f984aSEvgeniy Stepanov }
970