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 
142f2bd8caSAdam Nemet #include "llvm/Transforms/Utils/LoopUtils.h"
1531088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
1631088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
1731088a9dSChandler Carruth #include "llvm/Analysis/GlobalsModRef.h"
182f2bd8caSAdam Nemet #include "llvm/Analysis/GlobalsModRef.h"
192f2bd8caSAdam Nemet #include "llvm/Analysis/LoopInfo.h"
20c3ccf5d7SIgor Laevsky #include "llvm/Analysis/LoopPass.h"
2145d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolution.h"
222f2bd8caSAdam Nemet #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
23c434d091SElena Demikhovsky #include "llvm/Analysis/ScalarEvolutionExpander.h"
2445d4cb9aSWeiming Zhao #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2531088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
2676aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
2745d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
2876aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
2976aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
3031088a9dSChandler Carruth #include "llvm/Pass.h"
3176aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
3276aa662cSKarthik Bhat 
3376aa662cSKarthik Bhat using namespace llvm;
3476aa662cSKarthik Bhat using namespace llvm::PatternMatch;
3576aa662cSKarthik Bhat 
3676aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
3776aa662cSKarthik Bhat 
380a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
3976aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
4076aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4176aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
4276aa662cSKarthik Bhat       return false;
4376aa662cSKarthik Bhat   return true;
4476aa662cSKarthik Bhat }
4576aa662cSKarthik Bhat 
46c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
47c94f8e29SChad Rosier   switch (Kind) {
48c94f8e29SChad Rosier   default:
49c94f8e29SChad Rosier     break;
50c94f8e29SChad Rosier   case RK_IntegerAdd:
51c94f8e29SChad Rosier   case RK_IntegerMult:
52c94f8e29SChad Rosier   case RK_IntegerOr:
53c94f8e29SChad Rosier   case RK_IntegerAnd:
54c94f8e29SChad Rosier   case RK_IntegerXor:
55c94f8e29SChad Rosier   case RK_IntegerMinMax:
56c94f8e29SChad Rosier     return true;
57c94f8e29SChad Rosier   }
58c94f8e29SChad Rosier   return false;
59c94f8e29SChad Rosier }
60c94f8e29SChad Rosier 
61c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
62c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
63c94f8e29SChad Rosier }
64c94f8e29SChad Rosier 
65c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
66c94f8e29SChad Rosier   switch (Kind) {
67c94f8e29SChad Rosier   default:
68c94f8e29SChad Rosier     break;
69c94f8e29SChad Rosier   case RK_IntegerAdd:
70c94f8e29SChad Rosier   case RK_IntegerMult:
71c94f8e29SChad Rosier   case RK_FloatAdd:
72c94f8e29SChad Rosier   case RK_FloatMult:
73c94f8e29SChad Rosier     return true;
74c94f8e29SChad Rosier   }
75c94f8e29SChad Rosier   return false;
76c94f8e29SChad Rosier }
77c94f8e29SChad Rosier 
78c94f8e29SChad Rosier Instruction *
79c94f8e29SChad Rosier RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
80c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &Visited,
81c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &CI) {
82c94f8e29SChad Rosier   if (!Phi->hasOneUse())
83c94f8e29SChad Rosier     return Phi;
84c94f8e29SChad Rosier 
85c94f8e29SChad Rosier   const APInt *M = nullptr;
86c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
87c94f8e29SChad Rosier 
88c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
89c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
90c94f8e29SChad Rosier   if (match(J, m_CombineOr(m_And(m_Instruction(I), m_APInt(M)),
91c94f8e29SChad Rosier                            m_And(m_APInt(M), m_Instruction(I))))) {
92c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
93c94f8e29SChad Rosier     if (Bits > 0) {
94c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
95c94f8e29SChad Rosier       Visited.insert(Phi);
96c94f8e29SChad Rosier       CI.insert(J);
97c94f8e29SChad Rosier       return J;
98c94f8e29SChad Rosier     }
99c94f8e29SChad Rosier   }
100c94f8e29SChad Rosier   return Phi;
101c94f8e29SChad Rosier }
102c94f8e29SChad Rosier 
103c94f8e29SChad Rosier bool RecurrenceDescriptor::getSourceExtensionKind(
104c94f8e29SChad Rosier     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
105c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &Visited,
106c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &CI) {
107c94f8e29SChad Rosier 
108c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
109c94f8e29SChad Rosier   bool FoundOneOperand = false;
11029dc0f70SMatthew Simpson   unsigned DstSize = RT->getPrimitiveSizeInBits();
111c94f8e29SChad Rosier   Worklist.push_back(Exit);
112c94f8e29SChad Rosier 
113c94f8e29SChad Rosier   // Traverse the instructions in the reduction expression, beginning with the
114c94f8e29SChad Rosier   // exit value.
115c94f8e29SChad Rosier   while (!Worklist.empty()) {
116c94f8e29SChad Rosier     Instruction *I = Worklist.pop_back_val();
117c94f8e29SChad Rosier     for (Use &U : I->operands()) {
118c94f8e29SChad Rosier 
119c94f8e29SChad Rosier       // Terminate the traversal if the operand is not an instruction, or we
120c94f8e29SChad Rosier       // reach the starting value.
121c94f8e29SChad Rosier       Instruction *J = dyn_cast<Instruction>(U.get());
122c94f8e29SChad Rosier       if (!J || J == Start)
123c94f8e29SChad Rosier         continue;
124c94f8e29SChad Rosier 
125c94f8e29SChad Rosier       // Otherwise, investigate the operation if it is also in the expression.
126c94f8e29SChad Rosier       if (Visited.count(J)) {
127c94f8e29SChad Rosier         Worklist.push_back(J);
128c94f8e29SChad Rosier         continue;
129c94f8e29SChad Rosier       }
130c94f8e29SChad Rosier 
131c94f8e29SChad Rosier       // If the operand is not in Visited, it is not a reduction operation, but
132c94f8e29SChad Rosier       // it does feed into one. Make sure it is either a single-use sign- or
13329dc0f70SMatthew Simpson       // zero-extend instruction.
134c94f8e29SChad Rosier       CastInst *Cast = dyn_cast<CastInst>(J);
135c94f8e29SChad Rosier       bool IsSExtInst = isa<SExtInst>(J);
13629dc0f70SMatthew Simpson       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
13729dc0f70SMatthew Simpson         return false;
13829dc0f70SMatthew Simpson 
13929dc0f70SMatthew Simpson       // Ensure the source type of the extend is no larger than the reduction
14029dc0f70SMatthew Simpson       // type. It is not necessary for the types to be identical.
14129dc0f70SMatthew Simpson       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
14229dc0f70SMatthew Simpson       if (SrcSize > DstSize)
143c94f8e29SChad Rosier         return false;
144c94f8e29SChad Rosier 
145c94f8e29SChad Rosier       // Furthermore, ensure that all such extends are of the same kind.
146c94f8e29SChad Rosier       if (FoundOneOperand) {
147c94f8e29SChad Rosier         if (IsSigned != IsSExtInst)
148c94f8e29SChad Rosier           return false;
149c94f8e29SChad Rosier       } else {
150c94f8e29SChad Rosier         FoundOneOperand = true;
151c94f8e29SChad Rosier         IsSigned = IsSExtInst;
152c94f8e29SChad Rosier       }
153c94f8e29SChad Rosier 
15429dc0f70SMatthew Simpson       // Lastly, if the source type of the extend matches the reduction type,
15529dc0f70SMatthew Simpson       // add the extend to CI so that we can avoid accounting for it in the
15629dc0f70SMatthew Simpson       // cost model.
15729dc0f70SMatthew Simpson       if (SrcSize == DstSize)
158c94f8e29SChad Rosier         CI.insert(Cast);
159c94f8e29SChad Rosier     }
160c94f8e29SChad Rosier   }
161c94f8e29SChad Rosier   return true;
162c94f8e29SChad Rosier }
163c94f8e29SChad Rosier 
1640a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
16576aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
1660a91310cSTyler Nowicki                                            RecurrenceDescriptor &RedDes) {
16776aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
16876aa662cSKarthik Bhat     return false;
16976aa662cSKarthik Bhat 
17076aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
17176aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
17276aa662cSKarthik Bhat     return false;
17376aa662cSKarthik Bhat 
17476aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
17576aa662cSKarthik Bhat   // preheader.
17676aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
17776aa662cSKarthik Bhat 
17876aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
17976aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
18076aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
18176aa662cSKarthik Bhat   // which ends in the phi node).
18276aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
18376aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
18476aa662cSKarthik Bhat   bool FoundReduxOp = false;
18576aa662cSKarthik Bhat 
18676aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
18776aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
18876aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
18976aa662cSKarthik Bhat   // must include the original PHI.
19076aa662cSKarthik Bhat   bool FoundStartPHI = false;
19176aa662cSKarthik Bhat 
19276aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
19376aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
19476aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
19576aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
19627b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
19776aa662cSKarthik Bhat 
198c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
199c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
200c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
201c94f8e29SChad Rosier   Instruction *Start = Phi;
202c94f8e29SChad Rosier   bool IsSigned = false;
203c94f8e29SChad Rosier 
20476aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
20576aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
206c94f8e29SChad Rosier 
207c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
208c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
209c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
210c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
211c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
212c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
213c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
214c94f8e29SChad Rosier       return false;
215c94f8e29SChad Rosier   } else {
216c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
217c94f8e29SChad Rosier       return false;
218c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
219c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
220c94f8e29SChad Rosier   }
221c94f8e29SChad Rosier 
222c94f8e29SChad Rosier   Worklist.push_back(Start);
223c94f8e29SChad Rosier   VisitedInsts.insert(Start);
22476aa662cSKarthik Bhat 
22576aa662cSKarthik Bhat   // A value in the reduction can be used:
22676aa662cSKarthik Bhat   //  - By the reduction:
22776aa662cSKarthik Bhat   //      - Reduction operation:
22876aa662cSKarthik Bhat   //        - One use of reduction value (safe).
22976aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
23076aa662cSKarthik Bhat   //      - PHI:
23176aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
23276aa662cSKarthik Bhat   //        - Otherwise, not safe.
2337cefb409SMichael Kuperstein   //  - By instructions outside of the loop (safe).
2347cefb409SMichael Kuperstein   //      * One value may have several outside users, but all outside
2357cefb409SMichael Kuperstein   //        uses must be of the same value.
23676aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
23776aa662cSKarthik Bhat   //    This is either:
23876aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
23976aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
24076aa662cSKarthik Bhat   while (!Worklist.empty()) {
24176aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
24276aa662cSKarthik Bhat     Worklist.pop_back();
24376aa662cSKarthik Bhat 
24476aa662cSKarthik Bhat     // No Users.
24576aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
24676aa662cSKarthik Bhat     // a reduction variable.
24776aa662cSKarthik Bhat     if (Cur->use_empty())
24876aa662cSKarthik Bhat       return false;
24976aa662cSKarthik Bhat 
25076aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
25176aa662cSKarthik Bhat 
25276aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
25376aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
25476aa662cSKarthik Bhat       return false;
25576aa662cSKarthik Bhat 
25676aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
25776aa662cSKarthik Bhat     // LHS is the reduction variable.
25876aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
25976aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
26076aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
26176aa662cSKarthik Bhat       return false;
26276aa662cSKarthik Bhat 
263c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
264c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
265c94f8e29SChad Rosier     // type-promoted).
266c94f8e29SChad Rosier     if (Cur != Start) {
2670a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2680a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
26976aa662cSKarthik Bhat         return false;
270c94f8e29SChad Rosier     }
27176aa662cSKarthik Bhat 
27276aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
27376aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
27476aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
27576aa662cSKarthik Bhat       return false;
27676aa662cSKarthik Bhat 
27776aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
27876aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
27976aa662cSKarthik Bhat       return false;
28076aa662cSKarthik Bhat 
28176aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
28276aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
28376aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28476aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
28576aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28676aa662cSKarthik Bhat 
28776aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
288c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
28976aa662cSKarthik Bhat 
29076aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
29176aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
29276aa662cSKarthik Bhat     // nodes once we get to them.
29376aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
29476aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
29576aa662cSKarthik Bhat     for (User *U : Cur->users()) {
29676aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
29776aa662cSKarthik Bhat 
29876aa662cSKarthik Bhat       // Check if we found the exit user.
29976aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
30076aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
3017cefb409SMichael Kuperstein         // If we already know this instruction is used externally, move on to
3027cefb409SMichael Kuperstein         // the next user.
3037cefb409SMichael Kuperstein         if (ExitInstruction == Cur)
3047cefb409SMichael Kuperstein           continue;
3057cefb409SMichael Kuperstein 
3067cefb409SMichael Kuperstein         // Exit if you find multiple values used outside or if the header phi
3077cefb409SMichael Kuperstein         // node is being used. In this case the user uses the value of the
3087cefb409SMichael Kuperstein         // previous iteration, in which case we would loose "VF-1" iterations of
3097cefb409SMichael Kuperstein         // the reduction operation if we vectorize.
31076aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
31176aa662cSKarthik Bhat           return false;
31276aa662cSKarthik Bhat 
31376aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
31476aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
31576aa662cSKarthik Bhat         // operations on the value.
31642531260SDavid Majnemer         if (!is_contained(Phi->operands(), Cur))
31776aa662cSKarthik Bhat           return false;
31876aa662cSKarthik Bhat 
31976aa662cSKarthik Bhat         ExitInstruction = Cur;
32076aa662cSKarthik Bhat         continue;
32176aa662cSKarthik Bhat       }
32276aa662cSKarthik Bhat 
32376aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
32476aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
32576aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
32627b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
32776aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
32876aa662cSKarthik Bhat         if (isa<PHINode>(UI))
32976aa662cSKarthik Bhat           PHIs.push_back(UI);
33076aa662cSKarthik Bhat         else
33176aa662cSKarthik Bhat           NonPHIs.push_back(UI);
33276aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
33376aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
33476aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3350a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
33676aa662cSKarthik Bhat         return false;
33776aa662cSKarthik Bhat 
33876aa662cSKarthik Bhat       // Remember that we completed the cycle.
33976aa662cSKarthik Bhat       if (UI == Phi)
34076aa662cSKarthik Bhat         FoundStartPHI = true;
34176aa662cSKarthik Bhat     }
34276aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
34376aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
34476aa662cSKarthik Bhat   }
34576aa662cSKarthik Bhat 
34676aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
34776aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
34876aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
34976aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
35076aa662cSKarthik Bhat     return false;
35176aa662cSKarthik Bhat 
35276aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
35376aa662cSKarthik Bhat     return false;
35476aa662cSKarthik Bhat 
355c94f8e29SChad Rosier   // If we think Phi may have been type-promoted, we also need to ensure that
356c94f8e29SChad Rosier   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
357c94f8e29SChad Rosier   // so, we will be able to evaluate the reduction in the narrower bit width.
358c94f8e29SChad Rosier   if (Start != Phi)
359c94f8e29SChad Rosier     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
360c94f8e29SChad Rosier                                 IsSigned, VisitedInsts, CastInsts))
361c94f8e29SChad Rosier       return false;
362c94f8e29SChad Rosier 
36376aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
36476aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
36576aa662cSKarthik Bhat 
36676aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
3670a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
36876aa662cSKarthik Bhat 
36976aa662cSKarthik Bhat   // Save the description of this reduction variable.
370c94f8e29SChad Rosier   RecurrenceDescriptor RD(
371c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
372c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
37376aa662cSKarthik Bhat   RedDes = RD;
37476aa662cSKarthik Bhat 
37576aa662cSKarthik Bhat   return true;
37676aa662cSKarthik Bhat }
37776aa662cSKarthik Bhat 
37876aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
37976aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
38027b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
38127b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
38276aa662cSKarthik Bhat 
38376aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
38476aa662cSKarthik Bhat          "Expect a select instruction");
38576aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
38676aa662cSKarthik Bhat   SelectInst *Select = nullptr;
38776aa662cSKarthik Bhat 
38876aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
38976aa662cSKarthik Bhat   // select.
39076aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
39176aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
39227b2c39eSTyler Nowicki       return InstDesc(false, I);
39327b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
39476aa662cSKarthik Bhat   }
39576aa662cSKarthik Bhat 
39676aa662cSKarthik Bhat   // Only handle single use cases for now.
39776aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
39827b2c39eSTyler Nowicki     return InstDesc(false, I);
39976aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
40076aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
40127b2c39eSTyler Nowicki     return InstDesc(false, I);
40276aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
40327b2c39eSTyler Nowicki     return InstDesc(false, I);
40476aa662cSKarthik Bhat 
40576aa662cSKarthik Bhat   Value *CmpLeft;
40676aa662cSKarthik Bhat   Value *CmpRight;
40776aa662cSKarthik Bhat 
40876aa662cSKarthik Bhat   // Look for a min/max pattern.
40976aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41027b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
41176aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41227b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
41376aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41427b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
41576aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41627b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
41776aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41827b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
41976aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42027b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
42176aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42227b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
42376aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42427b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
42576aa662cSKarthik Bhat 
42627b2c39eSTyler Nowicki   return InstDesc(false, I);
42776aa662cSKarthik Bhat }
42876aa662cSKarthik Bhat 
42927b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4300a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
43127b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
43276aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
433c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
434c1a86f58STyler Nowicki   if (!UAI && FP && !I->hasUnsafeAlgebra())
435c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
436c1a86f58STyler Nowicki 
43776aa662cSKarthik Bhat   switch (I->getOpcode()) {
43876aa662cSKarthik Bhat   default:
43927b2c39eSTyler Nowicki     return InstDesc(false, I);
44076aa662cSKarthik Bhat   case Instruction::PHI:
44110a1e8b1STim Northover     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
44276aa662cSKarthik Bhat   case Instruction::Sub:
44376aa662cSKarthik Bhat   case Instruction::Add:
44427b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
44576aa662cSKarthik Bhat   case Instruction::Mul:
44627b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
44776aa662cSKarthik Bhat   case Instruction::And:
44827b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
44976aa662cSKarthik Bhat   case Instruction::Or:
45027b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
45176aa662cSKarthik Bhat   case Instruction::Xor:
45227b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
45376aa662cSKarthik Bhat   case Instruction::FMul:
454c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
45576aa662cSKarthik Bhat   case Instruction::FSub:
45676aa662cSKarthik Bhat   case Instruction::FAdd:
457c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
45876aa662cSKarthik Bhat   case Instruction::FCmp:
45976aa662cSKarthik Bhat   case Instruction::ICmp:
46076aa662cSKarthik Bhat   case Instruction::Select:
46176aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
46276aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
46327b2c39eSTyler Nowicki       return InstDesc(false, I);
46476aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
46576aa662cSKarthik Bhat   }
46676aa662cSKarthik Bhat }
46776aa662cSKarthik Bhat 
4680a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
46976aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
47076aa662cSKarthik Bhat   unsigned NumUses = 0;
47176aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
47276aa662cSKarthik Bhat        ++Use) {
47376aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
47476aa662cSKarthik Bhat       ++NumUses;
47576aa662cSKarthik Bhat     if (NumUses > 1)
47676aa662cSKarthik Bhat       return true;
47776aa662cSKarthik Bhat   }
47876aa662cSKarthik Bhat 
47976aa662cSKarthik Bhat   return false;
48076aa662cSKarthik Bhat }
4810a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
4820a91310cSTyler Nowicki                                           RecurrenceDescriptor &RedDes) {
48376aa662cSKarthik Bhat 
48476aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
48576aa662cSKarthik Bhat   Function &F = *Header->getParent();
4868dd66e57SNirav Dave   bool HasFunNoNaNAttr =
48776aa662cSKarthik Bhat       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
48876aa662cSKarthik Bhat 
48976aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
49076aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
49176aa662cSKarthik Bhat     return true;
49276aa662cSKarthik Bhat   }
49376aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
49476aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
49576aa662cSKarthik Bhat     return true;
49676aa662cSKarthik Bhat   }
49776aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
49876aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
49976aa662cSKarthik Bhat     return true;
50076aa662cSKarthik Bhat   }
50176aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
50276aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
50376aa662cSKarthik Bhat     return true;
50476aa662cSKarthik Bhat   }
50576aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
50676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
50776aa662cSKarthik Bhat     return true;
50876aa662cSKarthik Bhat   }
50976aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
51076aa662cSKarthik Bhat                       RedDes)) {
51176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
51276aa662cSKarthik Bhat     return true;
51376aa662cSKarthik Bhat   }
51476aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
51576aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
51676aa662cSKarthik Bhat     return true;
51776aa662cSKarthik Bhat   }
51876aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
51976aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
52076aa662cSKarthik Bhat     return true;
52176aa662cSKarthik Bhat   }
52276aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
52376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
52476aa662cSKarthik Bhat     return true;
52576aa662cSKarthik Bhat   }
52676aa662cSKarthik Bhat   // Not a reduction of known type.
52776aa662cSKarthik Bhat   return false;
52876aa662cSKarthik Bhat }
52976aa662cSKarthik Bhat 
53029c997c1SMatthew Simpson bool RecurrenceDescriptor::isFirstOrderRecurrence(PHINode *Phi, Loop *TheLoop,
53129c997c1SMatthew Simpson                                                   DominatorTree *DT) {
53229c997c1SMatthew Simpson 
53329c997c1SMatthew Simpson   // Ensure the phi node is in the loop header and has two incoming values.
53429c997c1SMatthew Simpson   if (Phi->getParent() != TheLoop->getHeader() ||
53529c997c1SMatthew Simpson       Phi->getNumIncomingValues() != 2)
53629c997c1SMatthew Simpson     return false;
53729c997c1SMatthew Simpson 
53829c997c1SMatthew Simpson   // Ensure the loop has a preheader and a single latch block. The loop
53929c997c1SMatthew Simpson   // vectorizer will need the latch to set up the next iteration of the loop.
54029c997c1SMatthew Simpson   auto *Preheader = TheLoop->getLoopPreheader();
54129c997c1SMatthew Simpson   auto *Latch = TheLoop->getLoopLatch();
54229c997c1SMatthew Simpson   if (!Preheader || !Latch)
54329c997c1SMatthew Simpson     return false;
54429c997c1SMatthew Simpson 
54529c997c1SMatthew Simpson   // Ensure the phi node's incoming blocks are the loop preheader and latch.
54629c997c1SMatthew Simpson   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
54729c997c1SMatthew Simpson       Phi->getBasicBlockIndex(Latch) < 0)
54829c997c1SMatthew Simpson     return false;
54929c997c1SMatthew Simpson 
55029c997c1SMatthew Simpson   // Get the previous value. The previous value comes from the latch edge while
55129c997c1SMatthew Simpson   // the initial value comes form the preheader edge.
55229c997c1SMatthew Simpson   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
55353207a99SMatthew Simpson   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous))
55429c997c1SMatthew Simpson     return false;
55529c997c1SMatthew Simpson 
55629c997c1SMatthew Simpson   for (User *U : Phi->users())
557*00dc1b74SAnna Thomas     if (auto *I = dyn_cast<Instruction>(U)) {
558*00dc1b74SAnna Thomas       // Ensure every user of the phi node is dominated by the previous value.
559*00dc1b74SAnna Thomas       // The dominance requirement ensures the loop vectorizer will not need to
560*00dc1b74SAnna Thomas       // vectorize the initial value prior to the first iteration of the loop.
56129c997c1SMatthew Simpson       if (!DT->dominates(Previous, I))
56229c997c1SMatthew Simpson         return false;
563*00dc1b74SAnna Thomas       // When the phi node has users outside the loop, the current logic for
564*00dc1b74SAnna Thomas       // fixFirstOrderRecurrences may generate incorrect code. Specifically, we
565*00dc1b74SAnna Thomas       // extract the last element from the vectorized phi, which would be the
566*00dc1b74SAnna Thomas       // update to the phi before exiting the loop. However, what we want is the
567*00dc1b74SAnna Thomas       // previous phi value before the update (i.e. the second last update
568*00dc1b74SAnna Thomas       // before end of the vectorized loop).
569*00dc1b74SAnna Thomas       // See added test cases in first-order-recurrence.ll
570*00dc1b74SAnna Thomas       if (!TheLoop->contains(I))
571*00dc1b74SAnna Thomas         return false;
572*00dc1b74SAnna Thomas     }
57329c997c1SMatthew Simpson 
57429c997c1SMatthew Simpson   return true;
57529c997c1SMatthew Simpson }
57629c997c1SMatthew Simpson 
57776aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
57876aa662cSKarthik Bhat /// the operation K.
5790a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
5800a91310cSTyler Nowicki                                                       Type *Tp) {
58176aa662cSKarthik Bhat   switch (K) {
58276aa662cSKarthik Bhat   case RK_IntegerXor:
58376aa662cSKarthik Bhat   case RK_IntegerAdd:
58476aa662cSKarthik Bhat   case RK_IntegerOr:
58576aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
58676aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
58776aa662cSKarthik Bhat   case RK_IntegerMult:
58876aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
58976aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
59076aa662cSKarthik Bhat   case RK_IntegerAnd:
59176aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
59276aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
59376aa662cSKarthik Bhat   case RK_FloatMult:
59476aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
59576aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
59676aa662cSKarthik Bhat   case RK_FloatAdd:
59776aa662cSKarthik Bhat     // Adding zero to a number does not change it.
59876aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
59976aa662cSKarthik Bhat   default:
6000a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
60176aa662cSKarthik Bhat   }
60276aa662cSKarthik Bhat }
60376aa662cSKarthik Bhat 
6040a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
6050a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
60676aa662cSKarthik Bhat   switch (Kind) {
60776aa662cSKarthik Bhat   case RK_IntegerAdd:
60876aa662cSKarthik Bhat     return Instruction::Add;
60976aa662cSKarthik Bhat   case RK_IntegerMult:
61076aa662cSKarthik Bhat     return Instruction::Mul;
61176aa662cSKarthik Bhat   case RK_IntegerOr:
61276aa662cSKarthik Bhat     return Instruction::Or;
61376aa662cSKarthik Bhat   case RK_IntegerAnd:
61476aa662cSKarthik Bhat     return Instruction::And;
61576aa662cSKarthik Bhat   case RK_IntegerXor:
61676aa662cSKarthik Bhat     return Instruction::Xor;
61776aa662cSKarthik Bhat   case RK_FloatMult:
61876aa662cSKarthik Bhat     return Instruction::FMul;
61976aa662cSKarthik Bhat   case RK_FloatAdd:
62076aa662cSKarthik Bhat     return Instruction::FAdd;
62176aa662cSKarthik Bhat   case RK_IntegerMinMax:
62276aa662cSKarthik Bhat     return Instruction::ICmp;
62376aa662cSKarthik Bhat   case RK_FloatMinMax:
62476aa662cSKarthik Bhat     return Instruction::FCmp;
62576aa662cSKarthik Bhat   default:
6260a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
62776aa662cSKarthik Bhat   }
62876aa662cSKarthik Bhat }
62976aa662cSKarthik Bhat 
63027b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
63127b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
63276aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
63376aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
63476aa662cSKarthik Bhat   switch (RK) {
63576aa662cSKarthik Bhat   default:
6360a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
63727b2c39eSTyler Nowicki   case MRK_UIntMin:
63876aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
63976aa662cSKarthik Bhat     break;
64027b2c39eSTyler Nowicki   case MRK_UIntMax:
64176aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
64276aa662cSKarthik Bhat     break;
64327b2c39eSTyler Nowicki   case MRK_SIntMin:
64476aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
64576aa662cSKarthik Bhat     break;
64627b2c39eSTyler Nowicki   case MRK_SIntMax:
64776aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
64876aa662cSKarthik Bhat     break;
64927b2c39eSTyler Nowicki   case MRK_FloatMin:
65076aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
65176aa662cSKarthik Bhat     break;
65227b2c39eSTyler Nowicki   case MRK_FloatMax:
65376aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
65476aa662cSKarthik Bhat     break;
65576aa662cSKarthik Bhat   }
65676aa662cSKarthik Bhat 
65750a4c27fSJames Molloy   // We only match FP sequences with unsafe algebra, so we can unconditionally
65850a4c27fSJames Molloy   // set it on any generated instructions.
65950a4c27fSJames Molloy   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
66050a4c27fSJames Molloy   FastMathFlags FMF;
66150a4c27fSJames Molloy   FMF.setUnsafeAlgebra();
662a252815bSSanjay Patel   Builder.setFastMathFlags(FMF);
66350a4c27fSJames Molloy 
66476aa662cSKarthik Bhat   Value *Cmp;
66527b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
66676aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
66776aa662cSKarthik Bhat   else
66876aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
66976aa662cSKarthik Bhat 
67076aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
67176aa662cSKarthik Bhat   return Select;
67276aa662cSKarthik Bhat }
67324e6cc2dSKarthik Bhat 
6741bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
675376a18bdSElena Demikhovsky                                          const SCEV *Step, BinaryOperator *BOp)
676376a18bdSElena Demikhovsky   : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
6771bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
678c434d091SElena Demikhovsky 
679c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
680c434d091SElena Demikhovsky   // itself should not be null.
6811bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
6821bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
6831bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
6841bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
6851bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
686c434d091SElena Demikhovsky 
687c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
688c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
689c434d091SElena Demikhovsky          "Step value is zero");
690c434d091SElena Demikhovsky 
691c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
692c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
693376a18bdSElena Demikhovsky   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
694376a18bdSElena Demikhovsky          "StepValue is not an integer");
695376a18bdSElena Demikhovsky 
696376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
697376a18bdSElena Demikhovsky          "StepValue is not FP for FpInduction");
698376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || (InductionBinOp &&
699376a18bdSElena Demikhovsky           (InductionBinOp->getOpcode() == Instruction::FAdd ||
700376a18bdSElena Demikhovsky            InductionBinOp->getOpcode() == Instruction::FSub))) &&
701376a18bdSElena Demikhovsky          "Binary opcode should be specified for FP induction");
7021bbf15c5SJames Molloy }
7031bbf15c5SJames Molloy 
7041bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
705c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
706c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
707c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
7081bbf15c5SJames Molloy   return 0;
7091bbf15c5SJames Molloy }
7101bbf15c5SJames Molloy 
711c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
712c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
713c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
714c434d091SElena Demikhovsky   return nullptr;
715c434d091SElena Demikhovsky }
716c434d091SElena Demikhovsky 
717c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
718c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
719c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
720c434d091SElena Demikhovsky 
721c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
722376a18bdSElena Demikhovsky   assert(Index->getType() == Step->getType() &&
723376a18bdSElena Demikhovsky          "Index type does not match StepValue type");
7241bbf15c5SJames Molloy   switch (IK) {
725c434d091SElena Demikhovsky   case IK_IntInduction: {
7261bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
7271bbf15c5SJames Molloy            "Index type does not match StartValue type");
728c434d091SElena Demikhovsky 
729c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
730c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
731c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
732c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
733c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
734c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
735c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
736c434d091SElena Demikhovsky 
737c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
738c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
7391bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
740c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
741c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
7421bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
743c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
744c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
745c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
746c434d091SElena Demikhovsky   }
747c434d091SElena Demikhovsky   case IK_PtrInduction: {
748c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
749c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
750c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
751c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
7521bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
753c434d091SElena Demikhovsky   }
754376a18bdSElena Demikhovsky   case IK_FpInduction: {
755376a18bdSElena Demikhovsky     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
756376a18bdSElena Demikhovsky     assert(InductionBinOp &&
757376a18bdSElena Demikhovsky            (InductionBinOp->getOpcode() == Instruction::FAdd ||
758376a18bdSElena Demikhovsky             InductionBinOp->getOpcode() == Instruction::FSub) &&
759376a18bdSElena Demikhovsky            "Original bin op should be defined for FP induction");
760376a18bdSElena Demikhovsky 
761376a18bdSElena Demikhovsky     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
762376a18bdSElena Demikhovsky 
763376a18bdSElena Demikhovsky     // Floating point operations had to be 'fast' to enable the induction.
764376a18bdSElena Demikhovsky     FastMathFlags Flags;
765376a18bdSElena Demikhovsky     Flags.setUnsafeAlgebra();
766376a18bdSElena Demikhovsky 
767376a18bdSElena Demikhovsky     Value *MulExp = B.CreateFMul(StepValue, Index);
768376a18bdSElena Demikhovsky     if (isa<Instruction>(MulExp))
769376a18bdSElena Demikhovsky       // We have to check, the MulExp may be a constant.
770376a18bdSElena Demikhovsky       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
771376a18bdSElena Demikhovsky 
772376a18bdSElena Demikhovsky     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
773376a18bdSElena Demikhovsky                                MulExp, "induction");
774376a18bdSElena Demikhovsky     if (isa<Instruction>(BOp))
775376a18bdSElena Demikhovsky       cast<Instruction>(BOp)->setFastMathFlags(Flags);
776376a18bdSElena Demikhovsky 
777376a18bdSElena Demikhovsky     return BOp;
778376a18bdSElena Demikhovsky   }
7791bbf15c5SJames Molloy   case IK_NoInduction:
7801bbf15c5SJames Molloy     return nullptr;
7811bbf15c5SJames Molloy   }
7821bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
7831bbf15c5SJames Molloy }
7841bbf15c5SJames Molloy 
785376a18bdSElena Demikhovsky bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
786376a18bdSElena Demikhovsky                                            ScalarEvolution *SE,
787376a18bdSElena Demikhovsky                                            InductionDescriptor &D) {
788376a18bdSElena Demikhovsky 
789376a18bdSElena Demikhovsky   // Here we only handle FP induction variables.
790376a18bdSElena Demikhovsky   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
791376a18bdSElena Demikhovsky 
792376a18bdSElena Demikhovsky   if (TheLoop->getHeader() != Phi->getParent())
793376a18bdSElena Demikhovsky     return false;
794376a18bdSElena Demikhovsky 
795376a18bdSElena Demikhovsky   // The loop may have multiple entrances or multiple exits; we can analyze
796376a18bdSElena Demikhovsky   // this phi if it has a unique entry value and a unique backedge value.
797376a18bdSElena Demikhovsky   if (Phi->getNumIncomingValues() != 2)
798376a18bdSElena Demikhovsky     return false;
799376a18bdSElena Demikhovsky   Value *BEValue = nullptr, *StartValue = nullptr;
800376a18bdSElena Demikhovsky   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
801376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(0);
802376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(1);
803376a18bdSElena Demikhovsky   } else {
804376a18bdSElena Demikhovsky     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
805376a18bdSElena Demikhovsky            "Unexpected Phi node in the loop");
806376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(1);
807376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(0);
808376a18bdSElena Demikhovsky   }
809376a18bdSElena Demikhovsky 
810376a18bdSElena Demikhovsky   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
811376a18bdSElena Demikhovsky   if (!BOp)
812376a18bdSElena Demikhovsky     return false;
813376a18bdSElena Demikhovsky 
814376a18bdSElena Demikhovsky   Value *Addend = nullptr;
815376a18bdSElena Demikhovsky   if (BOp->getOpcode() == Instruction::FAdd) {
816376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
817376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
818376a18bdSElena Demikhovsky     else if (BOp->getOperand(1) == Phi)
819376a18bdSElena Demikhovsky       Addend = BOp->getOperand(0);
820376a18bdSElena Demikhovsky   } else if (BOp->getOpcode() == Instruction::FSub)
821376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
822376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
823376a18bdSElena Demikhovsky 
824376a18bdSElena Demikhovsky   if (!Addend)
825376a18bdSElena Demikhovsky     return false;
826376a18bdSElena Demikhovsky 
827376a18bdSElena Demikhovsky   // The addend should be loop invariant
828376a18bdSElena Demikhovsky   if (auto *I = dyn_cast<Instruction>(Addend))
829376a18bdSElena Demikhovsky     if (TheLoop->contains(I))
830376a18bdSElena Demikhovsky       return false;
831376a18bdSElena Demikhovsky 
832376a18bdSElena Demikhovsky   // FP Step has unknown SCEV
833376a18bdSElena Demikhovsky   const SCEV *Step = SE->getUnknown(Addend);
834376a18bdSElena Demikhovsky   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
835376a18bdSElena Demikhovsky   return true;
836376a18bdSElena Demikhovsky }
837376a18bdSElena Demikhovsky 
838376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
839c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
840c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
841c05bab8aSSilviu Baranga                                          bool Assume) {
842c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
843376a18bdSElena Demikhovsky 
844376a18bdSElena Demikhovsky   // Handle integer and pointer inductions variables.
845376a18bdSElena Demikhovsky   // Now we handle also FP induction but not trying to make a
846376a18bdSElena Demikhovsky   // recurrent expression from the PHI node in-place.
847376a18bdSElena Demikhovsky 
848376a18bdSElena Demikhovsky   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
849376a18bdSElena Demikhovsky       !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
850c05bab8aSSilviu Baranga     return false;
851c05bab8aSSilviu Baranga 
852376a18bdSElena Demikhovsky   if (PhiTy->isFloatingPointTy())
853376a18bdSElena Demikhovsky     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
854376a18bdSElena Demikhovsky 
855c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
856c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
857c05bab8aSSilviu Baranga 
858c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
859c05bab8aSSilviu Baranga   if (Assume && !AR)
860c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
861c05bab8aSSilviu Baranga 
862c05bab8aSSilviu Baranga   if (!AR) {
863c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
864c05bab8aSSilviu Baranga     return false;
865c05bab8aSSilviu Baranga   }
866c05bab8aSSilviu Baranga 
867376a18bdSElena Demikhovsky   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
868c05bab8aSSilviu Baranga }
869c05bab8aSSilviu Baranga 
870376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
871c05bab8aSSilviu Baranga                                          ScalarEvolution *SE,
872c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
873c05bab8aSSilviu Baranga                                          const SCEV *Expr) {
87424e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
87524e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
87624e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
87724e6cc2dSKarthik Bhat     return false;
87824e6cc2dSKarthik Bhat 
87924e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
880c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
88124e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
882c05bab8aSSilviu Baranga 
88324e6cc2dSKarthik Bhat   if (!AR) {
88424e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
88524e6cc2dSKarthik Bhat     return false;
88624e6cc2dSKarthik Bhat   }
88724e6cc2dSKarthik Bhat 
888ee31cbe3SMichael Kuperstein   if (AR->getLoop() != TheLoop) {
889ee31cbe3SMichael Kuperstein     // FIXME: We should treat this as a uniform. Unfortunately, we
890ee31cbe3SMichael Kuperstein     // don't currently know how to handled uniform PHIs.
891ee31cbe3SMichael Kuperstein     DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
892ee31cbe3SMichael Kuperstein     return false;
893ee31cbe3SMichael Kuperstein   }
894ee31cbe3SMichael Kuperstein 
8951bbf15c5SJames Molloy   Value *StartValue =
8961bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
89724e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
89824e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
899c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
900c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
901376a18bdSElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
90224e6cc2dSKarthik Bhat     return false;
90324e6cc2dSKarthik Bhat 
90424e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
905c434d091SElena Demikhovsky     D = InductionDescriptor(StartValue, IK_IntInduction, Step);
90624e6cc2dSKarthik Bhat     return true;
90724e6cc2dSKarthik Bhat   }
90824e6cc2dSKarthik Bhat 
90924e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
910c434d091SElena Demikhovsky   // Pointer induction should be a constant.
911c434d091SElena Demikhovsky   if (!ConstStep)
912c434d091SElena Demikhovsky     return false;
913c434d091SElena Demikhovsky 
914c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
91524e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
91624e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
91724e6cc2dSKarthik Bhat   // sized.
91824e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
91924e6cc2dSKarthik Bhat     return false;
92024e6cc2dSKarthik Bhat 
92124e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
92224e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
923b58f32f7SDavid Majnemer   if (!Size)
924b58f32f7SDavid Majnemer     return false;
925b58f32f7SDavid Majnemer 
92624e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
92724e6cc2dSKarthik Bhat   if (CVSize % Size)
92824e6cc2dSKarthik Bhat     return false;
929c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
930c434d091SElena Demikhovsky                                     true /* signed */);
9311bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
93224e6cc2dSKarthik Bhat   return true;
93324e6cc2dSKarthik Bhat }
934c5b7b555SAshutosh Nema 
935c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
936c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
937c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
938c5b7b555SAshutosh Nema 
939c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
940c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
941c5b7b555SAshutosh Nema     // be adapted into a pointer.
942c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
943c5b7b555SAshutosh Nema       auto Users = Inst.users();
9440a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
945c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
946c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
947c5b7b555SAshutosh Nema           }))
948c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
949c5b7b555SAshutosh Nema     }
950c5b7b555SAshutosh Nema 
951c5b7b555SAshutosh Nema   return UsedOutside;
952c5b7b555SAshutosh Nema }
95331088a9dSChandler Carruth 
95431088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
95531088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
95631088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
95731088a9dSChandler Carruth   // pass manager, they must also preserve these.
95831088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
95931088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
96031088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
96131088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
96231088a9dSChandler Carruth 
96331088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
96431088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
96531088a9dSChandler Carruth   extern char &LoopSimplifyID;
96631088a9dSChandler Carruth   extern char &LCSSAID;
96731088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
96831088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
96931088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
97031088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
971c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
972c3ccf5d7SIgor Laevsky   // which preserve lcssa form
973c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
974c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
97531088a9dSChandler Carruth 
97631088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
97731088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
97831088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
97931088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
98031088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
98131088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
98231088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
98331088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
98431088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
98531088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
98631088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
98731088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
98831088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
98931088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
99031088a9dSChandler Carruth }
99131088a9dSChandler Carruth 
99231088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
99331088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
99431088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
99531088a9dSChandler Carruth /// with:
99631088a9dSChandler Carruth ///
99731088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
99831088a9dSChandler Carruth ///
99931088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
100031088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
100131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
100231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
100331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1004e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
100531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
100631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
100731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
100831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
100931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
101031088a9dSChandler Carruth }
1011963341c8SAdam Nemet 
1012fe3def7cSAdam Nemet /// \brief Find string metadata for loop
1013fe3def7cSAdam Nemet ///
1014fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1015fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
1016fe3def7cSAdam Nemet /// Optional's not-a-value.
1017fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1018fe3def7cSAdam Nemet                                                             StringRef Name) {
1019963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
1020fe3def7cSAdam Nemet   // Return none if LoopID is false.
1021963341c8SAdam Nemet   if (!LoopID)
1022fe3def7cSAdam Nemet     return None;
1023293be666SAdam Nemet 
1024293be666SAdam Nemet   // First operand should refer to the loop id itself.
1025293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1026293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1027293be666SAdam Nemet 
1028963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
1029963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1030963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1031963341c8SAdam Nemet     if (!MD)
1032963341c8SAdam Nemet       continue;
1033963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1034963341c8SAdam Nemet     if (!S)
1035963341c8SAdam Nemet       continue;
1036963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
1037963341c8SAdam Nemet     if (Name.equals(S->getString()))
1038fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
1039fe3def7cSAdam Nemet       case 1:
1040fe3def7cSAdam Nemet         return nullptr;
1041fe3def7cSAdam Nemet       case 2:
1042fe3def7cSAdam Nemet         return &MD->getOperand(1);
1043fe3def7cSAdam Nemet       default:
1044fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
1045963341c8SAdam Nemet       }
1046fe3def7cSAdam Nemet   }
1047fe3def7cSAdam Nemet   return None;
1048963341c8SAdam Nemet }
1049122f984aSEvgeniy Stepanov 
1050122f984aSEvgeniy Stepanov /// Returns true if the instruction in a loop is guaranteed to execute at least
1051122f984aSEvgeniy Stepanov /// once.
1052122f984aSEvgeniy Stepanov bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1053122f984aSEvgeniy Stepanov                                  const DominatorTree *DT, const Loop *CurLoop,
1054122f984aSEvgeniy Stepanov                                  const LoopSafetyInfo *SafetyInfo) {
1055122f984aSEvgeniy Stepanov   // We have to check to make sure that the instruction dominates all
1056122f984aSEvgeniy Stepanov   // of the exit blocks.  If it doesn't, then there is a path out of the loop
1057122f984aSEvgeniy Stepanov   // which does not execute this instruction, so we can't hoist it.
1058122f984aSEvgeniy Stepanov 
1059122f984aSEvgeniy Stepanov   // If the instruction is in the header block for the loop (which is very
1060122f984aSEvgeniy Stepanov   // common), it is always guaranteed to dominate the exit blocks.  Since this
1061122f984aSEvgeniy Stepanov   // is a common case, and can save some work, check it now.
1062122f984aSEvgeniy Stepanov   if (Inst.getParent() == CurLoop->getHeader())
1063122f984aSEvgeniy Stepanov     // If there's a throw in the header block, we can't guarantee we'll reach
1064122f984aSEvgeniy Stepanov     // Inst.
1065122f984aSEvgeniy Stepanov     return !SafetyInfo->HeaderMayThrow;
1066122f984aSEvgeniy Stepanov 
1067122f984aSEvgeniy Stepanov   // Somewhere in this loop there is an instruction which may throw and make us
1068122f984aSEvgeniy Stepanov   // exit the loop.
1069122f984aSEvgeniy Stepanov   if (SafetyInfo->MayThrow)
1070122f984aSEvgeniy Stepanov     return false;
1071122f984aSEvgeniy Stepanov 
1072122f984aSEvgeniy Stepanov   // Get the exit blocks for the current loop.
1073122f984aSEvgeniy Stepanov   SmallVector<BasicBlock *, 8> ExitBlocks;
1074122f984aSEvgeniy Stepanov   CurLoop->getExitBlocks(ExitBlocks);
1075122f984aSEvgeniy Stepanov 
1076122f984aSEvgeniy Stepanov   // Verify that the block dominates each of the exit blocks of the loop.
1077122f984aSEvgeniy Stepanov   for (BasicBlock *ExitBlock : ExitBlocks)
1078122f984aSEvgeniy Stepanov     if (!DT->dominates(Inst.getParent(), ExitBlock))
1079122f984aSEvgeniy Stepanov       return false;
1080122f984aSEvgeniy Stepanov 
1081122f984aSEvgeniy Stepanov   // As a degenerate case, if the loop is statically infinite then we haven't
1082122f984aSEvgeniy Stepanov   // proven anything since there are no exit blocks.
1083122f984aSEvgeniy Stepanov   if (ExitBlocks.empty())
1084122f984aSEvgeniy Stepanov     return false;
1085122f984aSEvgeniy Stepanov 
1086f1da33e4SEli Friedman   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1087f1da33e4SEli Friedman   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
1088f1da33e4SEli Friedman   // just a special case of this.)
1089122f984aSEvgeniy Stepanov   return true;
1090122f984aSEvgeniy Stepanov }
109141d72a86SDehao Chen 
109241d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
109341d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
109441d72a86SDehao Chen   if (!L->getExitingBlock())
109541d72a86SDehao Chen     return None;
109641d72a86SDehao Chen 
109741d72a86SDehao Chen   // Get the branch weights for the the loop's backedge.
109841d72a86SDehao Chen   BranchInst *LatchBR =
109941d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
110041d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
110141d72a86SDehao Chen     return None;
110241d72a86SDehao Chen 
110341d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
110441d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
110541d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
110641d72a86SDehao Chen 
110741d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
110841d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
110941d72a86SDehao Chen   // we exited the loop.
111041d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
1111b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
111241d72a86SDehao Chen     return None;
111341d72a86SDehao Chen 
1114b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
1115b151a641SMichael Kuperstein     return 0;
111641d72a86SDehao Chen 
1117b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
1118b151a641SMichael Kuperstein   // rounding to nearest.
111941d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
1120b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
112141d72a86SDehao Chen   else
1122b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
112341d72a86SDehao Chen }
1124