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 
1476aa662cSKarthik Bhat #include "llvm/Analysis/LoopInfo.h"
1576aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
1676aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
1776aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
1876aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
1924e6cc2dSKarthik Bhat #include "llvm/Analysis/ScalarEvolution.h"
2024e6cc2dSKarthik Bhat #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2124e6cc2dSKarthik Bhat #include "llvm/IR/Module.h"
2276aa662cSKarthik Bhat #include "llvm/Transforms/Utils/LoopUtils.h"
2376aa662cSKarthik Bhat 
2476aa662cSKarthik Bhat using namespace llvm;
2576aa662cSKarthik Bhat using namespace llvm::PatternMatch;
2676aa662cSKarthik Bhat 
2776aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
2876aa662cSKarthik Bhat 
290a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
3076aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
3176aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
3276aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
3376aa662cSKarthik Bhat       return false;
3476aa662cSKarthik Bhat   return true;
3576aa662cSKarthik Bhat }
3676aa662cSKarthik Bhat 
37c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
38c94f8e29SChad Rosier   switch (Kind) {
39c94f8e29SChad Rosier   default:
40c94f8e29SChad Rosier     break;
41c94f8e29SChad Rosier   case RK_IntegerAdd:
42c94f8e29SChad Rosier   case RK_IntegerMult:
43c94f8e29SChad Rosier   case RK_IntegerOr:
44c94f8e29SChad Rosier   case RK_IntegerAnd:
45c94f8e29SChad Rosier   case RK_IntegerXor:
46c94f8e29SChad Rosier   case RK_IntegerMinMax:
47c94f8e29SChad Rosier     return true;
48c94f8e29SChad Rosier   }
49c94f8e29SChad Rosier   return false;
50c94f8e29SChad Rosier }
51c94f8e29SChad Rosier 
52c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
53c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
54c94f8e29SChad Rosier }
55c94f8e29SChad Rosier 
56c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
57c94f8e29SChad Rosier   switch (Kind) {
58c94f8e29SChad Rosier   default:
59c94f8e29SChad Rosier     break;
60c94f8e29SChad Rosier   case RK_IntegerAdd:
61c94f8e29SChad Rosier   case RK_IntegerMult:
62c94f8e29SChad Rosier   case RK_FloatAdd:
63c94f8e29SChad Rosier   case RK_FloatMult:
64c94f8e29SChad Rosier     return true;
65c94f8e29SChad Rosier   }
66c94f8e29SChad Rosier   return false;
67c94f8e29SChad Rosier }
68c94f8e29SChad Rosier 
69c94f8e29SChad Rosier Instruction *
70c94f8e29SChad Rosier RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
71c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &Visited,
72c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &CI) {
73c94f8e29SChad Rosier   if (!Phi->hasOneUse())
74c94f8e29SChad Rosier     return Phi;
75c94f8e29SChad Rosier 
76c94f8e29SChad Rosier   const APInt *M = nullptr;
77c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
78c94f8e29SChad Rosier 
79c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
80c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
81c94f8e29SChad Rosier   if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
82c94f8e29SChad Rosier                            m_And(m_APInt(M), m_Instruction(I))))) {
83c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
84c94f8e29SChad Rosier     if (Bits > 0) {
85c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
86c94f8e29SChad Rosier       Visited.insert(Phi);
87c94f8e29SChad Rosier       CI.insert(J);
88c94f8e29SChad Rosier       return J;
89c94f8e29SChad Rosier     }
90c94f8e29SChad Rosier   }
91c94f8e29SChad Rosier   return Phi;
92c94f8e29SChad Rosier }
93c94f8e29SChad Rosier 
94c94f8e29SChad Rosier bool RecurrenceDescriptor::getSourceExtensionKind(
95c94f8e29SChad Rosier     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
96c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &Visited,
97c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &CI) {
98c94f8e29SChad Rosier 
99c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
100c94f8e29SChad Rosier   bool FoundOneOperand = false;
101*29dc0f70SMatthew Simpson   unsigned DstSize = RT->getPrimitiveSizeInBits();
102c94f8e29SChad Rosier   Worklist.push_back(Exit);
103c94f8e29SChad Rosier 
104c94f8e29SChad Rosier   // Traverse the instructions in the reduction expression, beginning with the
105c94f8e29SChad Rosier   // exit value.
106c94f8e29SChad Rosier   while (!Worklist.empty()) {
107c94f8e29SChad Rosier     Instruction *I = Worklist.pop_back_val();
108c94f8e29SChad Rosier     for (Use &U : I->operands()) {
109c94f8e29SChad Rosier 
110c94f8e29SChad Rosier       // Terminate the traversal if the operand is not an instruction, or we
111c94f8e29SChad Rosier       // reach the starting value.
112c94f8e29SChad Rosier       Instruction *J = dyn_cast<Instruction>(U.get());
113c94f8e29SChad Rosier       if (!J || J == Start)
114c94f8e29SChad Rosier         continue;
115c94f8e29SChad Rosier 
116c94f8e29SChad Rosier       // Otherwise, investigate the operation if it is also in the expression.
117c94f8e29SChad Rosier       if (Visited.count(J)) {
118c94f8e29SChad Rosier         Worklist.push_back(J);
119c94f8e29SChad Rosier         continue;
120c94f8e29SChad Rosier       }
121c94f8e29SChad Rosier 
122c94f8e29SChad Rosier       // If the operand is not in Visited, it is not a reduction operation, but
123c94f8e29SChad Rosier       // it does feed into one. Make sure it is either a single-use sign- or
124*29dc0f70SMatthew Simpson       // zero-extend instruction.
125c94f8e29SChad Rosier       CastInst *Cast = dyn_cast<CastInst>(J);
126c94f8e29SChad Rosier       bool IsSExtInst = isa<SExtInst>(J);
127*29dc0f70SMatthew Simpson       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
128*29dc0f70SMatthew Simpson         return false;
129*29dc0f70SMatthew Simpson 
130*29dc0f70SMatthew Simpson       // Ensure the source type of the extend is no larger than the reduction
131*29dc0f70SMatthew Simpson       // type. It is not necessary for the types to be identical.
132*29dc0f70SMatthew Simpson       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
133*29dc0f70SMatthew Simpson       if (SrcSize > DstSize)
134c94f8e29SChad Rosier         return false;
135c94f8e29SChad Rosier 
136c94f8e29SChad Rosier       // Furthermore, ensure that all such extends are of the same kind.
137c94f8e29SChad Rosier       if (FoundOneOperand) {
138c94f8e29SChad Rosier         if (IsSigned != IsSExtInst)
139c94f8e29SChad Rosier           return false;
140c94f8e29SChad Rosier       } else {
141c94f8e29SChad Rosier         FoundOneOperand = true;
142c94f8e29SChad Rosier         IsSigned = IsSExtInst;
143c94f8e29SChad Rosier       }
144c94f8e29SChad Rosier 
145*29dc0f70SMatthew Simpson       // Lastly, if the source type of the extend matches the reduction type,
146*29dc0f70SMatthew Simpson       // add the extend to CI so that we can avoid accounting for it in the
147*29dc0f70SMatthew Simpson       // cost model.
148*29dc0f70SMatthew Simpson       if (SrcSize == DstSize)
149c94f8e29SChad Rosier         CI.insert(Cast);
150c94f8e29SChad Rosier     }
151c94f8e29SChad Rosier   }
152c94f8e29SChad Rosier   return true;
153c94f8e29SChad Rosier }
154c94f8e29SChad Rosier 
1550a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
15676aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
1570a91310cSTyler Nowicki                                            RecurrenceDescriptor &RedDes) {
15876aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
15976aa662cSKarthik Bhat     return false;
16076aa662cSKarthik Bhat 
16176aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
16276aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
16376aa662cSKarthik Bhat     return false;
16476aa662cSKarthik Bhat 
16576aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
16676aa662cSKarthik Bhat   // preheader.
16776aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
16876aa662cSKarthik Bhat 
16976aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
17076aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
17176aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
17276aa662cSKarthik Bhat   // which ends in the phi node).
17376aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
17476aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
17576aa662cSKarthik Bhat   bool FoundReduxOp = false;
17676aa662cSKarthik Bhat 
17776aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
17876aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
17976aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
18076aa662cSKarthik Bhat   // must include the original PHI.
18176aa662cSKarthik Bhat   bool FoundStartPHI = false;
18276aa662cSKarthik Bhat 
18376aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
18476aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
18576aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
18676aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
18727b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
18876aa662cSKarthik Bhat 
189c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
190c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
191c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
192c94f8e29SChad Rosier   Instruction *Start = Phi;
193c94f8e29SChad Rosier   bool IsSigned = false;
194c94f8e29SChad Rosier 
19576aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
19676aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
197c94f8e29SChad Rosier 
198c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
199c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
200c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
201c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
202c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
203c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
204c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
205c94f8e29SChad Rosier       return false;
206c94f8e29SChad Rosier   } else {
207c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
208c94f8e29SChad Rosier       return false;
209c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
210c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
211c94f8e29SChad Rosier   }
212c94f8e29SChad Rosier 
213c94f8e29SChad Rosier   Worklist.push_back(Start);
214c94f8e29SChad Rosier   VisitedInsts.insert(Start);
21576aa662cSKarthik Bhat 
21676aa662cSKarthik Bhat   // A value in the reduction can be used:
21776aa662cSKarthik Bhat   //  - By the reduction:
21876aa662cSKarthik Bhat   //      - Reduction operation:
21976aa662cSKarthik Bhat   //        - One use of reduction value (safe).
22076aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
22176aa662cSKarthik Bhat   //      - PHI:
22276aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
22376aa662cSKarthik Bhat   //        - Otherwise, not safe.
22476aa662cSKarthik Bhat   //  - By one instruction outside of the loop (safe).
22576aa662cSKarthik Bhat   //  - By further instructions outside of the loop (not safe).
22676aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
22776aa662cSKarthik Bhat   //    This is either:
22876aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
22976aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
23076aa662cSKarthik Bhat   while (!Worklist.empty()) {
23176aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
23276aa662cSKarthik Bhat     Worklist.pop_back();
23376aa662cSKarthik Bhat 
23476aa662cSKarthik Bhat     // No Users.
23576aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
23676aa662cSKarthik Bhat     // a reduction variable.
23776aa662cSKarthik Bhat     if (Cur->use_empty())
23876aa662cSKarthik Bhat       return false;
23976aa662cSKarthik Bhat 
24076aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
24176aa662cSKarthik Bhat 
24276aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
24376aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
24476aa662cSKarthik Bhat       return false;
24576aa662cSKarthik Bhat 
24676aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
24776aa662cSKarthik Bhat     // LHS is the reduction variable.
24876aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
24976aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
25076aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
25176aa662cSKarthik Bhat       return false;
25276aa662cSKarthik Bhat 
253c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
254c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
255c94f8e29SChad Rosier     // type-promoted).
256c94f8e29SChad Rosier     if (Cur != Start) {
2570a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2580a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
25976aa662cSKarthik Bhat         return false;
260c94f8e29SChad Rosier     }
26176aa662cSKarthik Bhat 
26276aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
26376aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
26476aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
26576aa662cSKarthik Bhat       return false;
26676aa662cSKarthik Bhat 
26776aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
26876aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
26976aa662cSKarthik Bhat       return false;
27076aa662cSKarthik Bhat 
27176aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
27276aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
27376aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
27476aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
27576aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
27676aa662cSKarthik Bhat 
27776aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
278c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
27976aa662cSKarthik Bhat 
28076aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
28176aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
28276aa662cSKarthik Bhat     // nodes once we get to them.
28376aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
28476aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
28576aa662cSKarthik Bhat     for (User *U : Cur->users()) {
28676aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
28776aa662cSKarthik Bhat 
28876aa662cSKarthik Bhat       // Check if we found the exit user.
28976aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
29076aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
29176aa662cSKarthik Bhat         // Exit if you find multiple outside users or if the header phi node is
29276aa662cSKarthik Bhat         // being used. In this case the user uses the value of the previous
29376aa662cSKarthik Bhat         // iteration, in which case we would loose "VF-1" iterations of the
29476aa662cSKarthik Bhat         // reduction operation if we vectorize.
29576aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
29676aa662cSKarthik Bhat           return false;
29776aa662cSKarthik Bhat 
29876aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
29976aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
30076aa662cSKarthik Bhat         // operations on the value.
30176aa662cSKarthik Bhat         if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
30276aa662cSKarthik Bhat           return false;
30376aa662cSKarthik Bhat 
30476aa662cSKarthik Bhat         ExitInstruction = Cur;
30576aa662cSKarthik Bhat         continue;
30676aa662cSKarthik Bhat       }
30776aa662cSKarthik Bhat 
30876aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
30976aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
31076aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
31127b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
31276aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
31376aa662cSKarthik Bhat         if (isa<PHINode>(UI))
31476aa662cSKarthik Bhat           PHIs.push_back(UI);
31576aa662cSKarthik Bhat         else
31676aa662cSKarthik Bhat           NonPHIs.push_back(UI);
31776aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
31876aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
31976aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3200a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
32176aa662cSKarthik Bhat         return false;
32276aa662cSKarthik Bhat 
32376aa662cSKarthik Bhat       // Remember that we completed the cycle.
32476aa662cSKarthik Bhat       if (UI == Phi)
32576aa662cSKarthik Bhat         FoundStartPHI = true;
32676aa662cSKarthik Bhat     }
32776aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
32876aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
32976aa662cSKarthik Bhat   }
33076aa662cSKarthik Bhat 
33176aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
33276aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
33376aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
33476aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
33576aa662cSKarthik Bhat     return false;
33676aa662cSKarthik Bhat 
33776aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
33876aa662cSKarthik Bhat     return false;
33976aa662cSKarthik Bhat 
340c94f8e29SChad Rosier   // If we think Phi may have been type-promoted, we also need to ensure that
341c94f8e29SChad Rosier   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
342c94f8e29SChad Rosier   // so, we will be able to evaluate the reduction in the narrower bit width.
343c94f8e29SChad Rosier   if (Start != Phi)
344c94f8e29SChad Rosier     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
345c94f8e29SChad Rosier                                 IsSigned, VisitedInsts, CastInsts))
346c94f8e29SChad Rosier       return false;
347c94f8e29SChad Rosier 
34876aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
34976aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
35076aa662cSKarthik Bhat 
35176aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
3520a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
35376aa662cSKarthik Bhat 
35476aa662cSKarthik Bhat   // Save the description of this reduction variable.
355c94f8e29SChad Rosier   RecurrenceDescriptor RD(
356c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
357c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
35876aa662cSKarthik Bhat   RedDes = RD;
35976aa662cSKarthik Bhat 
36076aa662cSKarthik Bhat   return true;
36176aa662cSKarthik Bhat }
36276aa662cSKarthik Bhat 
36376aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
36476aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
36527b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
36627b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
36776aa662cSKarthik Bhat 
36876aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
36976aa662cSKarthik Bhat          "Expect a select instruction");
37076aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
37176aa662cSKarthik Bhat   SelectInst *Select = nullptr;
37276aa662cSKarthik Bhat 
37376aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
37476aa662cSKarthik Bhat   // select.
37576aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
37676aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
37727b2c39eSTyler Nowicki       return InstDesc(false, I);
37827b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
37976aa662cSKarthik Bhat   }
38076aa662cSKarthik Bhat 
38176aa662cSKarthik Bhat   // Only handle single use cases for now.
38276aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
38327b2c39eSTyler Nowicki     return InstDesc(false, I);
38476aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
38576aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
38627b2c39eSTyler Nowicki     return InstDesc(false, I);
38776aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
38827b2c39eSTyler Nowicki     return InstDesc(false, I);
38976aa662cSKarthik Bhat 
39076aa662cSKarthik Bhat   Value *CmpLeft;
39176aa662cSKarthik Bhat   Value *CmpRight;
39276aa662cSKarthik Bhat 
39376aa662cSKarthik Bhat   // Look for a min/max pattern.
39476aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
39527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
39676aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
39727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
39876aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
39927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
40076aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40127b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
40276aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
40476aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
40676aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
40876aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
40927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
41076aa662cSKarthik Bhat 
41127b2c39eSTyler Nowicki   return InstDesc(false, I);
41276aa662cSKarthik Bhat }
41376aa662cSKarthik Bhat 
41427b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4150a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
41627b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
41776aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
418c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
419c1a86f58STyler Nowicki   if (!UAI && FP && !I->hasUnsafeAlgebra())
420c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
421c1a86f58STyler Nowicki 
42276aa662cSKarthik Bhat   switch (I->getOpcode()) {
42376aa662cSKarthik Bhat   default:
42427b2c39eSTyler Nowicki     return InstDesc(false, I);
42576aa662cSKarthik Bhat   case Instruction::PHI:
42627b2c39eSTyler Nowicki     return InstDesc(I, Prev.getMinMaxKind());
42776aa662cSKarthik Bhat   case Instruction::Sub:
42876aa662cSKarthik Bhat   case Instruction::Add:
42927b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
43076aa662cSKarthik Bhat   case Instruction::Mul:
43127b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
43276aa662cSKarthik Bhat   case Instruction::And:
43327b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
43476aa662cSKarthik Bhat   case Instruction::Or:
43527b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
43676aa662cSKarthik Bhat   case Instruction::Xor:
43727b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
43876aa662cSKarthik Bhat   case Instruction::FMul:
439c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
44076aa662cSKarthik Bhat   case Instruction::FSub:
44176aa662cSKarthik Bhat   case Instruction::FAdd:
442c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
44376aa662cSKarthik Bhat   case Instruction::FCmp:
44476aa662cSKarthik Bhat   case Instruction::ICmp:
44576aa662cSKarthik Bhat   case Instruction::Select:
44676aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
44776aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
44827b2c39eSTyler Nowicki       return InstDesc(false, I);
44976aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
45076aa662cSKarthik Bhat   }
45176aa662cSKarthik Bhat }
45276aa662cSKarthik Bhat 
4530a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
45476aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
45576aa662cSKarthik Bhat   unsigned NumUses = 0;
45676aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
45776aa662cSKarthik Bhat        ++Use) {
45876aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
45976aa662cSKarthik Bhat       ++NumUses;
46076aa662cSKarthik Bhat     if (NumUses > 1)
46176aa662cSKarthik Bhat       return true;
46276aa662cSKarthik Bhat   }
46376aa662cSKarthik Bhat 
46476aa662cSKarthik Bhat   return false;
46576aa662cSKarthik Bhat }
4660a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
4670a91310cSTyler Nowicki                                           RecurrenceDescriptor &RedDes) {
46876aa662cSKarthik Bhat 
46976aa662cSKarthik Bhat   bool HasFunNoNaNAttr = false;
47076aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
47176aa662cSKarthik Bhat   Function &F = *Header->getParent();
47276aa662cSKarthik Bhat   if (F.hasFnAttribute("no-nans-fp-math"))
47376aa662cSKarthik Bhat     HasFunNoNaNAttr =
47476aa662cSKarthik Bhat         F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
47576aa662cSKarthik Bhat 
47676aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
47776aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
47876aa662cSKarthik Bhat     return true;
47976aa662cSKarthik Bhat   }
48076aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
48176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
48276aa662cSKarthik Bhat     return true;
48376aa662cSKarthik Bhat   }
48476aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
48576aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
48676aa662cSKarthik Bhat     return true;
48776aa662cSKarthik Bhat   }
48876aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
48976aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
49076aa662cSKarthik Bhat     return true;
49176aa662cSKarthik Bhat   }
49276aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
49376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
49476aa662cSKarthik Bhat     return true;
49576aa662cSKarthik Bhat   }
49676aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
49776aa662cSKarthik Bhat                       RedDes)) {
49876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
49976aa662cSKarthik Bhat     return true;
50076aa662cSKarthik Bhat   }
50176aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
50276aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
50376aa662cSKarthik Bhat     return true;
50476aa662cSKarthik Bhat   }
50576aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
50676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
50776aa662cSKarthik Bhat     return true;
50876aa662cSKarthik Bhat   }
50976aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
51076aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
51176aa662cSKarthik Bhat     return true;
51276aa662cSKarthik Bhat   }
51376aa662cSKarthik Bhat   // Not a reduction of known type.
51476aa662cSKarthik Bhat   return false;
51576aa662cSKarthik Bhat }
51676aa662cSKarthik Bhat 
51776aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
51876aa662cSKarthik Bhat /// the operation K.
5190a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
5200a91310cSTyler Nowicki                                                       Type *Tp) {
52176aa662cSKarthik Bhat   switch (K) {
52276aa662cSKarthik Bhat   case RK_IntegerXor:
52376aa662cSKarthik Bhat   case RK_IntegerAdd:
52476aa662cSKarthik Bhat   case RK_IntegerOr:
52576aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
52676aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
52776aa662cSKarthik Bhat   case RK_IntegerMult:
52876aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
52976aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
53076aa662cSKarthik Bhat   case RK_IntegerAnd:
53176aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
53276aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
53376aa662cSKarthik Bhat   case RK_FloatMult:
53476aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
53576aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
53676aa662cSKarthik Bhat   case RK_FloatAdd:
53776aa662cSKarthik Bhat     // Adding zero to a number does not change it.
53876aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
53976aa662cSKarthik Bhat   default:
5400a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
54176aa662cSKarthik Bhat   }
54276aa662cSKarthik Bhat }
54376aa662cSKarthik Bhat 
5440a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
5450a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
54676aa662cSKarthik Bhat   switch (Kind) {
54776aa662cSKarthik Bhat   case RK_IntegerAdd:
54876aa662cSKarthik Bhat     return Instruction::Add;
54976aa662cSKarthik Bhat   case RK_IntegerMult:
55076aa662cSKarthik Bhat     return Instruction::Mul;
55176aa662cSKarthik Bhat   case RK_IntegerOr:
55276aa662cSKarthik Bhat     return Instruction::Or;
55376aa662cSKarthik Bhat   case RK_IntegerAnd:
55476aa662cSKarthik Bhat     return Instruction::And;
55576aa662cSKarthik Bhat   case RK_IntegerXor:
55676aa662cSKarthik Bhat     return Instruction::Xor;
55776aa662cSKarthik Bhat   case RK_FloatMult:
55876aa662cSKarthik Bhat     return Instruction::FMul;
55976aa662cSKarthik Bhat   case RK_FloatAdd:
56076aa662cSKarthik Bhat     return Instruction::FAdd;
56176aa662cSKarthik Bhat   case RK_IntegerMinMax:
56276aa662cSKarthik Bhat     return Instruction::ICmp;
56376aa662cSKarthik Bhat   case RK_FloatMinMax:
56476aa662cSKarthik Bhat     return Instruction::FCmp;
56576aa662cSKarthik Bhat   default:
5660a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
56776aa662cSKarthik Bhat   }
56876aa662cSKarthik Bhat }
56976aa662cSKarthik Bhat 
57027b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
57127b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
57276aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
57376aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
57476aa662cSKarthik Bhat   switch (RK) {
57576aa662cSKarthik Bhat   default:
5760a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
57727b2c39eSTyler Nowicki   case MRK_UIntMin:
57876aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
57976aa662cSKarthik Bhat     break;
58027b2c39eSTyler Nowicki   case MRK_UIntMax:
58176aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
58276aa662cSKarthik Bhat     break;
58327b2c39eSTyler Nowicki   case MRK_SIntMin:
58476aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
58576aa662cSKarthik Bhat     break;
58627b2c39eSTyler Nowicki   case MRK_SIntMax:
58776aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
58876aa662cSKarthik Bhat     break;
58927b2c39eSTyler Nowicki   case MRK_FloatMin:
59076aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
59176aa662cSKarthik Bhat     break;
59227b2c39eSTyler Nowicki   case MRK_FloatMax:
59376aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
59476aa662cSKarthik Bhat     break;
59576aa662cSKarthik Bhat   }
59676aa662cSKarthik Bhat 
59776aa662cSKarthik Bhat   Value *Cmp;
59827b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
59976aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
60076aa662cSKarthik Bhat   else
60176aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
60276aa662cSKarthik Bhat 
60376aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
60476aa662cSKarthik Bhat   return Select;
60576aa662cSKarthik Bhat }
60624e6cc2dSKarthik Bhat 
6071bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
6081bbf15c5SJames Molloy                                          ConstantInt *Step)
6091bbf15c5SJames Molloy   : StartValue(Start), IK(K), StepValue(Step) {
6101bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
6111bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
6121bbf15c5SJames Molloy   assert(StepValue && !StepValue->isZero() && "StepValue is zero");
6131bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
6141bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
6151bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
6161bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
6171bbf15c5SJames Molloy   assert(StepValue->getType()->isIntegerTy() &&
6181bbf15c5SJames Molloy          "StepValue is not an integer");
6191bbf15c5SJames Molloy }
6201bbf15c5SJames Molloy 
6211bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
6221bbf15c5SJames Molloy   if (StepValue && (StepValue->isOne() || StepValue->isMinusOne()))
6231bbf15c5SJames Molloy     return StepValue->getSExtValue();
6241bbf15c5SJames Molloy   return 0;
6251bbf15c5SJames Molloy }
6261bbf15c5SJames Molloy 
6271bbf15c5SJames Molloy Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index) const {
6281bbf15c5SJames Molloy   switch (IK) {
6291bbf15c5SJames Molloy   case IK_IntInduction:
6301bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
6311bbf15c5SJames Molloy            "Index type does not match StartValue type");
6321bbf15c5SJames Molloy     if (StepValue->isMinusOne())
6331bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
6341bbf15c5SJames Molloy     if (!StepValue->isOne())
6351bbf15c5SJames Molloy       Index = B.CreateMul(Index, StepValue);
6361bbf15c5SJames Molloy     return B.CreateAdd(StartValue, Index);
6371bbf15c5SJames Molloy 
6381bbf15c5SJames Molloy   case IK_PtrInduction:
6391bbf15c5SJames Molloy     assert(Index->getType() == StepValue->getType() &&
6401bbf15c5SJames Molloy            "Index type does not match StepValue type");
6411bbf15c5SJames Molloy     if (StepValue->isMinusOne())
6421bbf15c5SJames Molloy       Index = B.CreateNeg(Index);
6431bbf15c5SJames Molloy     else if (!StepValue->isOne())
6441bbf15c5SJames Molloy       Index = B.CreateMul(Index, StepValue);
6451bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
6461bbf15c5SJames Molloy 
6471bbf15c5SJames Molloy   case IK_NoInduction:
6481bbf15c5SJames Molloy     return nullptr;
6491bbf15c5SJames Molloy   }
6501bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
6511bbf15c5SJames Molloy }
6521bbf15c5SJames Molloy 
6531bbf15c5SJames Molloy bool InductionDescriptor::isInductionPHI(PHINode *Phi, ScalarEvolution *SE,
6541bbf15c5SJames Molloy                                          InductionDescriptor &D) {
65524e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
65624e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
65724e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
65824e6cc2dSKarthik Bhat     return false;
65924e6cc2dSKarthik Bhat 
66024e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
66124e6cc2dSKarthik Bhat   const SCEV *PhiScev = SE->getSCEV(Phi);
66224e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
66324e6cc2dSKarthik Bhat   if (!AR) {
66424e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
66524e6cc2dSKarthik Bhat     return false;
66624e6cc2dSKarthik Bhat   }
66724e6cc2dSKarthik Bhat 
6681bbf15c5SJames Molloy   assert(AR->getLoop()->getHeader() == Phi->getParent() &&
6691bbf15c5SJames Molloy          "PHI is an AddRec for a different loop?!");
6701bbf15c5SJames Molloy   Value *StartValue =
6711bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
67224e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
67324e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
67424e6cc2dSKarthik Bhat   const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
67524e6cc2dSKarthik Bhat   if (!C)
67624e6cc2dSKarthik Bhat     return false;
67724e6cc2dSKarthik Bhat 
67824e6cc2dSKarthik Bhat   ConstantInt *CV = C->getValue();
67924e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
6801bbf15c5SJames Molloy     D = InductionDescriptor(StartValue, IK_IntInduction, CV);
68124e6cc2dSKarthik Bhat     return true;
68224e6cc2dSKarthik Bhat   }
68324e6cc2dSKarthik Bhat 
68424e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
68524e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
68624e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
68724e6cc2dSKarthik Bhat   // sized.
68824e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
68924e6cc2dSKarthik Bhat     return false;
69024e6cc2dSKarthik Bhat 
69124e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
69224e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
693b58f32f7SDavid Majnemer   if (!Size)
694b58f32f7SDavid Majnemer     return false;
695b58f32f7SDavid Majnemer 
69624e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
69724e6cc2dSKarthik Bhat   if (CVSize % Size)
69824e6cc2dSKarthik Bhat     return false;
6991bbf15c5SJames Molloy   auto *StepValue = ConstantInt::getSigned(CV->getType(), CVSize / Size);
7001bbf15c5SJames Molloy 
7011bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
70224e6cc2dSKarthik Bhat   return true;
70324e6cc2dSKarthik Bhat }
704c5b7b555SAshutosh Nema 
705c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
706c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
707c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
708c5b7b555SAshutosh Nema 
709c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
710c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
711c5b7b555SAshutosh Nema     // be adapted into a pointer.
712c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
713c5b7b555SAshutosh Nema       auto Users = Inst.users();
714c5b7b555SAshutosh Nema       if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
715c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
716c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
717c5b7b555SAshutosh Nema           }))
718c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
719c5b7b555SAshutosh Nema     }
720c5b7b555SAshutosh Nema 
721c5b7b555SAshutosh Nema   return UsedOutside;
722c5b7b555SAshutosh Nema }
723