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"
154a000883SChandler Carruth #include "llvm/ADT/ScopeExit.h"
1631088a9dSChandler Carruth #include "llvm/Analysis/AliasAnalysis.h"
1731088a9dSChandler Carruth #include "llvm/Analysis/BasicAliasAnalysis.h"
1831088a9dSChandler Carruth #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"
256bda14b3SChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
2631088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
2776aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
2845d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
2976aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
3076aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
3131088a9dSChandler Carruth #include "llvm/Pass.h"
3276aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
334a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3476aa662cSKarthik Bhat 
3576aa662cSKarthik Bhat using namespace llvm;
3676aa662cSKarthik Bhat using namespace llvm::PatternMatch;
3776aa662cSKarthik Bhat 
3876aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
3976aa662cSKarthik Bhat 
400a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
4176aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
4276aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4376aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
4476aa662cSKarthik Bhat       return false;
4576aa662cSKarthik Bhat   return true;
4676aa662cSKarthik Bhat }
4776aa662cSKarthik Bhat 
48c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
49c94f8e29SChad Rosier   switch (Kind) {
50c94f8e29SChad Rosier   default:
51c94f8e29SChad Rosier     break;
52c94f8e29SChad Rosier   case RK_IntegerAdd:
53c94f8e29SChad Rosier   case RK_IntegerMult:
54c94f8e29SChad Rosier   case RK_IntegerOr:
55c94f8e29SChad Rosier   case RK_IntegerAnd:
56c94f8e29SChad Rosier   case RK_IntegerXor:
57c94f8e29SChad Rosier   case RK_IntegerMinMax:
58c94f8e29SChad Rosier     return true;
59c94f8e29SChad Rosier   }
60c94f8e29SChad Rosier   return false;
61c94f8e29SChad Rosier }
62c94f8e29SChad Rosier 
63c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
64c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
65c94f8e29SChad Rosier }
66c94f8e29SChad Rosier 
67c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
68c94f8e29SChad Rosier   switch (Kind) {
69c94f8e29SChad Rosier   default:
70c94f8e29SChad Rosier     break;
71c94f8e29SChad Rosier   case RK_IntegerAdd:
72c94f8e29SChad Rosier   case RK_IntegerMult:
73c94f8e29SChad Rosier   case RK_FloatAdd:
74c94f8e29SChad Rosier   case RK_FloatMult:
75c94f8e29SChad Rosier     return true;
76c94f8e29SChad Rosier   }
77c94f8e29SChad Rosier   return false;
78c94f8e29SChad Rosier }
79c94f8e29SChad Rosier 
80c94f8e29SChad Rosier Instruction *
81c94f8e29SChad Rosier RecurrenceDescriptor::lookThroughAnd(PHINode *Phi, Type *&RT,
82c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &Visited,
83c94f8e29SChad Rosier                                      SmallPtrSetImpl<Instruction *> &CI) {
84c94f8e29SChad Rosier   if (!Phi->hasOneUse())
85c94f8e29SChad Rosier     return Phi;
86c94f8e29SChad Rosier 
87c94f8e29SChad Rosier   const APInt *M = nullptr;
88c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
89c94f8e29SChad Rosier 
90c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
91c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
9272ee6945SCraig Topper   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
93c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
94c94f8e29SChad Rosier     if (Bits > 0) {
95c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
96c94f8e29SChad Rosier       Visited.insert(Phi);
97c94f8e29SChad Rosier       CI.insert(J);
98c94f8e29SChad Rosier       return J;
99c94f8e29SChad Rosier     }
100c94f8e29SChad Rosier   }
101c94f8e29SChad Rosier   return Phi;
102c94f8e29SChad Rosier }
103c94f8e29SChad Rosier 
104c94f8e29SChad Rosier bool RecurrenceDescriptor::getSourceExtensionKind(
105c94f8e29SChad Rosier     Instruction *Start, Instruction *Exit, Type *RT, bool &IsSigned,
106c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &Visited,
107c94f8e29SChad Rosier     SmallPtrSetImpl<Instruction *> &CI) {
108c94f8e29SChad Rosier 
109c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
110c94f8e29SChad Rosier   bool FoundOneOperand = false;
11129dc0f70SMatthew Simpson   unsigned DstSize = RT->getPrimitiveSizeInBits();
112c94f8e29SChad Rosier   Worklist.push_back(Exit);
113c94f8e29SChad Rosier 
114c94f8e29SChad Rosier   // Traverse the instructions in the reduction expression, beginning with the
115c94f8e29SChad Rosier   // exit value.
116c94f8e29SChad Rosier   while (!Worklist.empty()) {
117c94f8e29SChad Rosier     Instruction *I = Worklist.pop_back_val();
118c94f8e29SChad Rosier     for (Use &U : I->operands()) {
119c94f8e29SChad Rosier 
120c94f8e29SChad Rosier       // Terminate the traversal if the operand is not an instruction, or we
121c94f8e29SChad Rosier       // reach the starting value.
122c94f8e29SChad Rosier       Instruction *J = dyn_cast<Instruction>(U.get());
123c94f8e29SChad Rosier       if (!J || J == Start)
124c94f8e29SChad Rosier         continue;
125c94f8e29SChad Rosier 
126c94f8e29SChad Rosier       // Otherwise, investigate the operation if it is also in the expression.
127c94f8e29SChad Rosier       if (Visited.count(J)) {
128c94f8e29SChad Rosier         Worklist.push_back(J);
129c94f8e29SChad Rosier         continue;
130c94f8e29SChad Rosier       }
131c94f8e29SChad Rosier 
132c94f8e29SChad Rosier       // If the operand is not in Visited, it is not a reduction operation, but
133c94f8e29SChad Rosier       // it does feed into one. Make sure it is either a single-use sign- or
13429dc0f70SMatthew Simpson       // zero-extend instruction.
135c94f8e29SChad Rosier       CastInst *Cast = dyn_cast<CastInst>(J);
136c94f8e29SChad Rosier       bool IsSExtInst = isa<SExtInst>(J);
13729dc0f70SMatthew Simpson       if (!Cast || !Cast->hasOneUse() || !(isa<ZExtInst>(J) || IsSExtInst))
13829dc0f70SMatthew Simpson         return false;
13929dc0f70SMatthew Simpson 
14029dc0f70SMatthew Simpson       // Ensure the source type of the extend is no larger than the reduction
14129dc0f70SMatthew Simpson       // type. It is not necessary for the types to be identical.
14229dc0f70SMatthew Simpson       unsigned SrcSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
14329dc0f70SMatthew Simpson       if (SrcSize > DstSize)
144c94f8e29SChad Rosier         return false;
145c94f8e29SChad Rosier 
146c94f8e29SChad Rosier       // Furthermore, ensure that all such extends are of the same kind.
147c94f8e29SChad Rosier       if (FoundOneOperand) {
148c94f8e29SChad Rosier         if (IsSigned != IsSExtInst)
149c94f8e29SChad Rosier           return false;
150c94f8e29SChad Rosier       } else {
151c94f8e29SChad Rosier         FoundOneOperand = true;
152c94f8e29SChad Rosier         IsSigned = IsSExtInst;
153c94f8e29SChad Rosier       }
154c94f8e29SChad Rosier 
15529dc0f70SMatthew Simpson       // Lastly, if the source type of the extend matches the reduction type,
15629dc0f70SMatthew Simpson       // add the extend to CI so that we can avoid accounting for it in the
15729dc0f70SMatthew Simpson       // cost model.
15829dc0f70SMatthew Simpson       if (SrcSize == DstSize)
159c94f8e29SChad Rosier         CI.insert(Cast);
160c94f8e29SChad Rosier     }
161c94f8e29SChad Rosier   }
162c94f8e29SChad Rosier   return true;
163c94f8e29SChad Rosier }
164c94f8e29SChad Rosier 
1650a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
16676aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
1670a91310cSTyler Nowicki                                            RecurrenceDescriptor &RedDes) {
16876aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
16976aa662cSKarthik Bhat     return false;
17076aa662cSKarthik Bhat 
17176aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
17276aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
17376aa662cSKarthik Bhat     return false;
17476aa662cSKarthik Bhat 
17576aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
17676aa662cSKarthik Bhat   // preheader.
17776aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
17876aa662cSKarthik Bhat 
17976aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
18076aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
18176aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
18276aa662cSKarthik Bhat   // which ends in the phi node).
18376aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
18476aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
18576aa662cSKarthik Bhat   bool FoundReduxOp = false;
18676aa662cSKarthik Bhat 
18776aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
18876aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
18976aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
19076aa662cSKarthik Bhat   // must include the original PHI.
19176aa662cSKarthik Bhat   bool FoundStartPHI = false;
19276aa662cSKarthik Bhat 
19376aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
19476aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
19576aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
19676aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
19727b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
19876aa662cSKarthik Bhat 
199c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
200c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
201c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
202c94f8e29SChad Rosier   Instruction *Start = Phi;
203c94f8e29SChad Rosier   bool IsSigned = false;
204c94f8e29SChad Rosier 
20576aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
20676aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
207c94f8e29SChad Rosier 
208c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
209c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
210c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
211c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
212c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
213c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
214c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
215c94f8e29SChad Rosier       return false;
216c94f8e29SChad Rosier   } else {
217c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
218c94f8e29SChad Rosier       return false;
219c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
220c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
221c94f8e29SChad Rosier   }
222c94f8e29SChad Rosier 
223c94f8e29SChad Rosier   Worklist.push_back(Start);
224c94f8e29SChad Rosier   VisitedInsts.insert(Start);
22576aa662cSKarthik Bhat 
22676aa662cSKarthik Bhat   // A value in the reduction can be used:
22776aa662cSKarthik Bhat   //  - By the reduction:
22876aa662cSKarthik Bhat   //      - Reduction operation:
22976aa662cSKarthik Bhat   //        - One use of reduction value (safe).
23076aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
23176aa662cSKarthik Bhat   //      - PHI:
23276aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
23376aa662cSKarthik Bhat   //        - Otherwise, not safe.
2347cefb409SMichael Kuperstein   //  - By instructions outside of the loop (safe).
2357cefb409SMichael Kuperstein   //      * One value may have several outside users, but all outside
2367cefb409SMichael Kuperstein   //        uses must be of the same value.
23776aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
23876aa662cSKarthik Bhat   //    This is either:
23976aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
24076aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
24176aa662cSKarthik Bhat   while (!Worklist.empty()) {
24276aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
24376aa662cSKarthik Bhat     Worklist.pop_back();
24476aa662cSKarthik Bhat 
24576aa662cSKarthik Bhat     // No Users.
24676aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
24776aa662cSKarthik Bhat     // a reduction variable.
24876aa662cSKarthik Bhat     if (Cur->use_empty())
24976aa662cSKarthik Bhat       return false;
25076aa662cSKarthik Bhat 
25176aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
25276aa662cSKarthik Bhat 
25376aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
25476aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
25576aa662cSKarthik Bhat       return false;
25676aa662cSKarthik Bhat 
25776aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
25876aa662cSKarthik Bhat     // LHS is the reduction variable.
25976aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
26076aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
26176aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
26276aa662cSKarthik Bhat       return false;
26376aa662cSKarthik Bhat 
264c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
265c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
266c94f8e29SChad Rosier     // type-promoted).
267c94f8e29SChad Rosier     if (Cur != Start) {
2680a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2690a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
27076aa662cSKarthik Bhat         return false;
271c94f8e29SChad Rosier     }
27276aa662cSKarthik Bhat 
27376aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
27476aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
27576aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
27676aa662cSKarthik Bhat       return false;
27776aa662cSKarthik Bhat 
27876aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
27976aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
28076aa662cSKarthik Bhat       return false;
28176aa662cSKarthik Bhat 
28276aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
28376aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
28476aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28576aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
28676aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
28776aa662cSKarthik Bhat 
28876aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
289c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
29076aa662cSKarthik Bhat 
29176aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
29276aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
29376aa662cSKarthik Bhat     // nodes once we get to them.
29476aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
29576aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
29676aa662cSKarthik Bhat     for (User *U : Cur->users()) {
29776aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
29876aa662cSKarthik Bhat 
29976aa662cSKarthik Bhat       // Check if we found the exit user.
30076aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
30176aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
3027cefb409SMichael Kuperstein         // If we already know this instruction is used externally, move on to
3037cefb409SMichael Kuperstein         // the next user.
3047cefb409SMichael Kuperstein         if (ExitInstruction == Cur)
3057cefb409SMichael Kuperstein           continue;
3067cefb409SMichael Kuperstein 
3077cefb409SMichael Kuperstein         // Exit if you find multiple values used outside or if the header phi
3087cefb409SMichael Kuperstein         // node is being used. In this case the user uses the value of the
3097cefb409SMichael Kuperstein         // previous iteration, in which case we would loose "VF-1" iterations of
3107cefb409SMichael Kuperstein         // the reduction operation if we vectorize.
31176aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
31276aa662cSKarthik Bhat           return false;
31376aa662cSKarthik Bhat 
31476aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
31576aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
31676aa662cSKarthik Bhat         // operations on the value.
31742531260SDavid Majnemer         if (!is_contained(Phi->operands(), Cur))
31876aa662cSKarthik Bhat           return false;
31976aa662cSKarthik Bhat 
32076aa662cSKarthik Bhat         ExitInstruction = Cur;
32176aa662cSKarthik Bhat         continue;
32276aa662cSKarthik Bhat       }
32376aa662cSKarthik Bhat 
32476aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
32576aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
32676aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
32727b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
32876aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
32976aa662cSKarthik Bhat         if (isa<PHINode>(UI))
33076aa662cSKarthik Bhat           PHIs.push_back(UI);
33176aa662cSKarthik Bhat         else
33276aa662cSKarthik Bhat           NonPHIs.push_back(UI);
33376aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
33476aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
33576aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3360a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
33776aa662cSKarthik Bhat         return false;
33876aa662cSKarthik Bhat 
33976aa662cSKarthik Bhat       // Remember that we completed the cycle.
34076aa662cSKarthik Bhat       if (UI == Phi)
34176aa662cSKarthik Bhat         FoundStartPHI = true;
34276aa662cSKarthik Bhat     }
34376aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
34476aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
34576aa662cSKarthik Bhat   }
34676aa662cSKarthik Bhat 
34776aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
34876aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
34976aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
35076aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
35176aa662cSKarthik Bhat     return false;
35276aa662cSKarthik Bhat 
35376aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
35476aa662cSKarthik Bhat     return false;
35576aa662cSKarthik Bhat 
356c94f8e29SChad Rosier   // If we think Phi may have been type-promoted, we also need to ensure that
357c94f8e29SChad Rosier   // all source operands of the reduction are either SExtInsts or ZEstInsts. If
358c94f8e29SChad Rosier   // so, we will be able to evaluate the reduction in the narrower bit width.
359c94f8e29SChad Rosier   if (Start != Phi)
360c94f8e29SChad Rosier     if (!getSourceExtensionKind(Start, ExitInstruction, RecurrenceType,
361c94f8e29SChad Rosier                                 IsSigned, VisitedInsts, CastInsts))
362c94f8e29SChad Rosier       return false;
363c94f8e29SChad Rosier 
36476aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
36576aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
36676aa662cSKarthik Bhat 
36776aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
3680a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
36976aa662cSKarthik Bhat 
37076aa662cSKarthik Bhat   // Save the description of this reduction variable.
371c94f8e29SChad Rosier   RecurrenceDescriptor RD(
372c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
373c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
37476aa662cSKarthik Bhat   RedDes = RD;
37576aa662cSKarthik Bhat 
37676aa662cSKarthik Bhat   return true;
37776aa662cSKarthik Bhat }
37876aa662cSKarthik Bhat 
37976aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
38076aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
38127b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
38227b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
38376aa662cSKarthik Bhat 
38476aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
38576aa662cSKarthik Bhat          "Expect a select instruction");
38676aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
38776aa662cSKarthik Bhat   SelectInst *Select = nullptr;
38876aa662cSKarthik Bhat 
38976aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
39076aa662cSKarthik Bhat   // select.
39176aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
39276aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
39327b2c39eSTyler Nowicki       return InstDesc(false, I);
39427b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
39576aa662cSKarthik Bhat   }
39676aa662cSKarthik Bhat 
39776aa662cSKarthik Bhat   // Only handle single use cases for now.
39876aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
39927b2c39eSTyler Nowicki     return InstDesc(false, I);
40076aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
40176aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
40227b2c39eSTyler Nowicki     return InstDesc(false, I);
40376aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
40427b2c39eSTyler Nowicki     return InstDesc(false, I);
40576aa662cSKarthik Bhat 
40676aa662cSKarthik Bhat   Value *CmpLeft;
40776aa662cSKarthik Bhat   Value *CmpRight;
40876aa662cSKarthik Bhat 
40976aa662cSKarthik Bhat   // Look for a min/max pattern.
41076aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41127b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
41276aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
41476aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
41676aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
41876aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
41927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
42076aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42127b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
42276aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
42476aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
42527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
42676aa662cSKarthik Bhat 
42727b2c39eSTyler Nowicki   return InstDesc(false, I);
42876aa662cSKarthik Bhat }
42976aa662cSKarthik Bhat 
43027b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4310a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
43227b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
43376aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
434c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
435629c4115SSanjay Patel   if (!UAI && FP && !I->isFast())
436c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
437c1a86f58STyler Nowicki 
43876aa662cSKarthik Bhat   switch (I->getOpcode()) {
43976aa662cSKarthik Bhat   default:
44027b2c39eSTyler Nowicki     return InstDesc(false, I);
44176aa662cSKarthik Bhat   case Instruction::PHI:
44210a1e8b1STim Northover     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
44376aa662cSKarthik Bhat   case Instruction::Sub:
44476aa662cSKarthik Bhat   case Instruction::Add:
44527b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
44676aa662cSKarthik Bhat   case Instruction::Mul:
44727b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
44876aa662cSKarthik Bhat   case Instruction::And:
44927b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
45076aa662cSKarthik Bhat   case Instruction::Or:
45127b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
45276aa662cSKarthik Bhat   case Instruction::Xor:
45327b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
45476aa662cSKarthik Bhat   case Instruction::FMul:
455c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
45676aa662cSKarthik Bhat   case Instruction::FSub:
45776aa662cSKarthik Bhat   case Instruction::FAdd:
458c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
45976aa662cSKarthik Bhat   case Instruction::FCmp:
46076aa662cSKarthik Bhat   case Instruction::ICmp:
46176aa662cSKarthik Bhat   case Instruction::Select:
46276aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
46376aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
46427b2c39eSTyler Nowicki       return InstDesc(false, I);
46576aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
46676aa662cSKarthik Bhat   }
46776aa662cSKarthik Bhat }
46876aa662cSKarthik Bhat 
4690a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
47076aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
47176aa662cSKarthik Bhat   unsigned NumUses = 0;
47276aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
47376aa662cSKarthik Bhat        ++Use) {
47476aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
47576aa662cSKarthik Bhat       ++NumUses;
47676aa662cSKarthik Bhat     if (NumUses > 1)
47776aa662cSKarthik Bhat       return true;
47876aa662cSKarthik Bhat   }
47976aa662cSKarthik Bhat 
48076aa662cSKarthik Bhat   return false;
48176aa662cSKarthik Bhat }
4820a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
4830a91310cSTyler Nowicki                                           RecurrenceDescriptor &RedDes) {
48476aa662cSKarthik Bhat 
48576aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
48676aa662cSKarthik Bhat   Function &F = *Header->getParent();
4878dd66e57SNirav Dave   bool HasFunNoNaNAttr =
48876aa662cSKarthik Bhat       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
48976aa662cSKarthik Bhat 
49076aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
49176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
49276aa662cSKarthik Bhat     return true;
49376aa662cSKarthik Bhat   }
49476aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
49576aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
49676aa662cSKarthik Bhat     return true;
49776aa662cSKarthik Bhat   }
49876aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes)) {
49976aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
50076aa662cSKarthik Bhat     return true;
50176aa662cSKarthik Bhat   }
50276aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes)) {
50376aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
50476aa662cSKarthik Bhat     return true;
50576aa662cSKarthik Bhat   }
50676aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes)) {
50776aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
50876aa662cSKarthik Bhat     return true;
50976aa662cSKarthik Bhat   }
51076aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr,
51176aa662cSKarthik Bhat                       RedDes)) {
51276aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
51376aa662cSKarthik Bhat     return true;
51476aa662cSKarthik Bhat   }
51576aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes)) {
51676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
51776aa662cSKarthik Bhat     return true;
51876aa662cSKarthik Bhat   }
51976aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes)) {
52076aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
52176aa662cSKarthik Bhat     return true;
52276aa662cSKarthik Bhat   }
52376aa662cSKarthik Bhat   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes)) {
52476aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
52576aa662cSKarthik Bhat     return true;
52676aa662cSKarthik Bhat   }
52776aa662cSKarthik Bhat   // Not a reduction of known type.
52876aa662cSKarthik Bhat   return false;
52976aa662cSKarthik Bhat }
53076aa662cSKarthik Bhat 
5312ff59d43SAyal Zaks bool RecurrenceDescriptor::isFirstOrderRecurrence(
5322ff59d43SAyal Zaks     PHINode *Phi, Loop *TheLoop,
5332ff59d43SAyal Zaks     DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
53429c997c1SMatthew Simpson 
53529c997c1SMatthew Simpson   // Ensure the phi node is in the loop header and has two incoming values.
53629c997c1SMatthew Simpson   if (Phi->getParent() != TheLoop->getHeader() ||
53729c997c1SMatthew Simpson       Phi->getNumIncomingValues() != 2)
53829c997c1SMatthew Simpson     return false;
53929c997c1SMatthew Simpson 
54029c997c1SMatthew Simpson   // Ensure the loop has a preheader and a single latch block. The loop
54129c997c1SMatthew Simpson   // vectorizer will need the latch to set up the next iteration of the loop.
54229c997c1SMatthew Simpson   auto *Preheader = TheLoop->getLoopPreheader();
54329c997c1SMatthew Simpson   auto *Latch = TheLoop->getLoopLatch();
54429c997c1SMatthew Simpson   if (!Preheader || !Latch)
54529c997c1SMatthew Simpson     return false;
54629c997c1SMatthew Simpson 
54729c997c1SMatthew Simpson   // Ensure the phi node's incoming blocks are the loop preheader and latch.
54829c997c1SMatthew Simpson   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
54929c997c1SMatthew Simpson       Phi->getBasicBlockIndex(Latch) < 0)
55029c997c1SMatthew Simpson     return false;
55129c997c1SMatthew Simpson 
55229c997c1SMatthew Simpson   // Get the previous value. The previous value comes from the latch edge while
55329c997c1SMatthew Simpson   // the initial value comes form the preheader edge.
55429c997c1SMatthew Simpson   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
5552ff59d43SAyal Zaks   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
5562ff59d43SAyal Zaks       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
55729c997c1SMatthew Simpson     return false;
55829c997c1SMatthew Simpson 
55900dc1b74SAnna Thomas   // Ensure every user of the phi node is dominated by the previous value.
56000dc1b74SAnna Thomas   // The dominance requirement ensures the loop vectorizer will not need to
56100dc1b74SAnna Thomas   // vectorize the initial value prior to the first iteration of the loop.
5622ff59d43SAyal Zaks   // TODO: Consider extending this sinking to handle other kinds of instructions
5632ff59d43SAyal Zaks   // and expressions, beyond sinking a single cast past Previous.
5642ff59d43SAyal Zaks   if (Phi->hasOneUse()) {
5652ff59d43SAyal Zaks     auto *I = Phi->user_back();
5662ff59d43SAyal Zaks     if (I->isCast() && (I->getParent() == Phi->getParent()) && I->hasOneUse() &&
5672ff59d43SAyal Zaks         DT->dominates(Previous, I->user_back())) {
56825e2800eSAyal Zaks       if (!DT->dominates(Previous, I)) // Otherwise we're good w/o sinking.
5692ff59d43SAyal Zaks         SinkAfter[I] = Previous;
5702ff59d43SAyal Zaks       return true;
5712ff59d43SAyal Zaks     }
5722ff59d43SAyal Zaks   }
5732ff59d43SAyal Zaks 
574dcdb325fSAnna Thomas   for (User *U : Phi->users())
575dcdb325fSAnna Thomas     if (auto *I = dyn_cast<Instruction>(U)) {
57629c997c1SMatthew Simpson       if (!DT->dominates(Previous, I))
57729c997c1SMatthew Simpson         return false;
57800dc1b74SAnna Thomas     }
57929c997c1SMatthew Simpson 
58029c997c1SMatthew Simpson   return true;
58129c997c1SMatthew Simpson }
58229c997c1SMatthew Simpson 
58376aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
58476aa662cSKarthik Bhat /// the operation K.
5850a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
5860a91310cSTyler Nowicki                                                       Type *Tp) {
58776aa662cSKarthik Bhat   switch (K) {
58876aa662cSKarthik Bhat   case RK_IntegerXor:
58976aa662cSKarthik Bhat   case RK_IntegerAdd:
59076aa662cSKarthik Bhat   case RK_IntegerOr:
59176aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
59276aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
59376aa662cSKarthik Bhat   case RK_IntegerMult:
59476aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
59576aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
59676aa662cSKarthik Bhat   case RK_IntegerAnd:
59776aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
59876aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
59976aa662cSKarthik Bhat   case RK_FloatMult:
60076aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
60176aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
60276aa662cSKarthik Bhat   case RK_FloatAdd:
60376aa662cSKarthik Bhat     // Adding zero to a number does not change it.
60476aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
60576aa662cSKarthik Bhat   default:
6060a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
60776aa662cSKarthik Bhat   }
60876aa662cSKarthik Bhat }
60976aa662cSKarthik Bhat 
6100a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
6110a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
61276aa662cSKarthik Bhat   switch (Kind) {
61376aa662cSKarthik Bhat   case RK_IntegerAdd:
61476aa662cSKarthik Bhat     return Instruction::Add;
61576aa662cSKarthik Bhat   case RK_IntegerMult:
61676aa662cSKarthik Bhat     return Instruction::Mul;
61776aa662cSKarthik Bhat   case RK_IntegerOr:
61876aa662cSKarthik Bhat     return Instruction::Or;
61976aa662cSKarthik Bhat   case RK_IntegerAnd:
62076aa662cSKarthik Bhat     return Instruction::And;
62176aa662cSKarthik Bhat   case RK_IntegerXor:
62276aa662cSKarthik Bhat     return Instruction::Xor;
62376aa662cSKarthik Bhat   case RK_FloatMult:
62476aa662cSKarthik Bhat     return Instruction::FMul;
62576aa662cSKarthik Bhat   case RK_FloatAdd:
62676aa662cSKarthik Bhat     return Instruction::FAdd;
62776aa662cSKarthik Bhat   case RK_IntegerMinMax:
62876aa662cSKarthik Bhat     return Instruction::ICmp;
62976aa662cSKarthik Bhat   case RK_FloatMinMax:
63076aa662cSKarthik Bhat     return Instruction::FCmp;
63176aa662cSKarthik Bhat   default:
6320a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
63376aa662cSKarthik Bhat   }
63476aa662cSKarthik Bhat }
63576aa662cSKarthik Bhat 
63627b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
63727b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
63876aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
63976aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
64076aa662cSKarthik Bhat   switch (RK) {
64176aa662cSKarthik Bhat   default:
6420a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
64327b2c39eSTyler Nowicki   case MRK_UIntMin:
64476aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
64576aa662cSKarthik Bhat     break;
64627b2c39eSTyler Nowicki   case MRK_UIntMax:
64776aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
64876aa662cSKarthik Bhat     break;
64927b2c39eSTyler Nowicki   case MRK_SIntMin:
65076aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
65176aa662cSKarthik Bhat     break;
65227b2c39eSTyler Nowicki   case MRK_SIntMax:
65376aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
65476aa662cSKarthik Bhat     break;
65527b2c39eSTyler Nowicki   case MRK_FloatMin:
65676aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
65776aa662cSKarthik Bhat     break;
65827b2c39eSTyler Nowicki   case MRK_FloatMax:
65976aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
66076aa662cSKarthik Bhat     break;
66176aa662cSKarthik Bhat   }
66276aa662cSKarthik Bhat 
663629c4115SSanjay Patel   // We only match FP sequences that are 'fast', so we can unconditionally
66450a4c27fSJames Molloy   // set it on any generated instructions.
66550a4c27fSJames Molloy   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
66650a4c27fSJames Molloy   FastMathFlags FMF;
667629c4115SSanjay Patel   FMF.setFast();
668a252815bSSanjay Patel   Builder.setFastMathFlags(FMF);
66950a4c27fSJames Molloy 
67076aa662cSKarthik Bhat   Value *Cmp;
67127b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
67276aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
67376aa662cSKarthik Bhat   else
67476aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
67576aa662cSKarthik Bhat 
67676aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
67776aa662cSKarthik Bhat   return Select;
67876aa662cSKarthik Bhat }
67924e6cc2dSKarthik Bhat 
6801bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
681376a18bdSElena Demikhovsky                                          const SCEV *Step, BinaryOperator *BOp)
682376a18bdSElena Demikhovsky   : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
6831bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
684c434d091SElena Demikhovsky 
685c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
686c434d091SElena Demikhovsky   // itself should not be null.
6871bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
6881bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
6891bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
6901bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
6911bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
692c434d091SElena Demikhovsky 
693c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
694c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
695c434d091SElena Demikhovsky          "Step value is zero");
696c434d091SElena Demikhovsky 
697c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
698c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
699376a18bdSElena Demikhovsky   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
700376a18bdSElena Demikhovsky          "StepValue is not an integer");
701376a18bdSElena Demikhovsky 
702376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
703376a18bdSElena Demikhovsky          "StepValue is not FP for FpInduction");
704376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || (InductionBinOp &&
705376a18bdSElena Demikhovsky           (InductionBinOp->getOpcode() == Instruction::FAdd ||
706376a18bdSElena Demikhovsky            InductionBinOp->getOpcode() == Instruction::FSub))) &&
707376a18bdSElena Demikhovsky          "Binary opcode should be specified for FP induction");
7081bbf15c5SJames Molloy }
7091bbf15c5SJames Molloy 
7101bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
711c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
712c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
713c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
7141bbf15c5SJames Molloy   return 0;
7151bbf15c5SJames Molloy }
7161bbf15c5SJames Molloy 
717c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
718c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
719c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
720c434d091SElena Demikhovsky   return nullptr;
721c434d091SElena Demikhovsky }
722c434d091SElena Demikhovsky 
723c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
724c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
725c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
726c434d091SElena Demikhovsky 
727c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
728376a18bdSElena Demikhovsky   assert(Index->getType() == Step->getType() &&
729376a18bdSElena Demikhovsky          "Index type does not match StepValue type");
7301bbf15c5SJames Molloy   switch (IK) {
731c434d091SElena Demikhovsky   case IK_IntInduction: {
7321bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
7331bbf15c5SJames Molloy            "Index type does not match StartValue type");
734c434d091SElena Demikhovsky 
735c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
736c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
737c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
738c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
739c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
740c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
741c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
742c434d091SElena Demikhovsky 
743c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
744c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
7451bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
746c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
747c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
7481bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
749c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
750c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
751c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
752c434d091SElena Demikhovsky   }
753c434d091SElena Demikhovsky   case IK_PtrInduction: {
754c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
755c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
756c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
757c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
7581bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
759c434d091SElena Demikhovsky   }
760376a18bdSElena Demikhovsky   case IK_FpInduction: {
761376a18bdSElena Demikhovsky     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
762376a18bdSElena Demikhovsky     assert(InductionBinOp &&
763376a18bdSElena Demikhovsky            (InductionBinOp->getOpcode() == Instruction::FAdd ||
764376a18bdSElena Demikhovsky             InductionBinOp->getOpcode() == Instruction::FSub) &&
765376a18bdSElena Demikhovsky            "Original bin op should be defined for FP induction");
766376a18bdSElena Demikhovsky 
767376a18bdSElena Demikhovsky     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
768376a18bdSElena Demikhovsky 
769376a18bdSElena Demikhovsky     // Floating point operations had to be 'fast' to enable the induction.
770376a18bdSElena Demikhovsky     FastMathFlags Flags;
771629c4115SSanjay Patel     Flags.setFast();
772376a18bdSElena Demikhovsky 
773376a18bdSElena Demikhovsky     Value *MulExp = B.CreateFMul(StepValue, Index);
774376a18bdSElena Demikhovsky     if (isa<Instruction>(MulExp))
775376a18bdSElena Demikhovsky       // We have to check, the MulExp may be a constant.
776376a18bdSElena Demikhovsky       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
777376a18bdSElena Demikhovsky 
778376a18bdSElena Demikhovsky     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
779376a18bdSElena Demikhovsky                                MulExp, "induction");
780376a18bdSElena Demikhovsky     if (isa<Instruction>(BOp))
781376a18bdSElena Demikhovsky       cast<Instruction>(BOp)->setFastMathFlags(Flags);
782376a18bdSElena Demikhovsky 
783376a18bdSElena Demikhovsky     return BOp;
784376a18bdSElena Demikhovsky   }
7851bbf15c5SJames Molloy   case IK_NoInduction:
7861bbf15c5SJames Molloy     return nullptr;
7871bbf15c5SJames Molloy   }
7881bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
7891bbf15c5SJames Molloy }
7901bbf15c5SJames Molloy 
791376a18bdSElena Demikhovsky bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
792376a18bdSElena Demikhovsky                                            ScalarEvolution *SE,
793376a18bdSElena Demikhovsky                                            InductionDescriptor &D) {
794376a18bdSElena Demikhovsky 
795376a18bdSElena Demikhovsky   // Here we only handle FP induction variables.
796376a18bdSElena Demikhovsky   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
797376a18bdSElena Demikhovsky 
798376a18bdSElena Demikhovsky   if (TheLoop->getHeader() != Phi->getParent())
799376a18bdSElena Demikhovsky     return false;
800376a18bdSElena Demikhovsky 
801376a18bdSElena Demikhovsky   // The loop may have multiple entrances or multiple exits; we can analyze
802376a18bdSElena Demikhovsky   // this phi if it has a unique entry value and a unique backedge value.
803376a18bdSElena Demikhovsky   if (Phi->getNumIncomingValues() != 2)
804376a18bdSElena Demikhovsky     return false;
805376a18bdSElena Demikhovsky   Value *BEValue = nullptr, *StartValue = nullptr;
806376a18bdSElena Demikhovsky   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
807376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(0);
808376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(1);
809376a18bdSElena Demikhovsky   } else {
810376a18bdSElena Demikhovsky     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
811376a18bdSElena Demikhovsky            "Unexpected Phi node in the loop");
812376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(1);
813376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(0);
814376a18bdSElena Demikhovsky   }
815376a18bdSElena Demikhovsky 
816376a18bdSElena Demikhovsky   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
817376a18bdSElena Demikhovsky   if (!BOp)
818376a18bdSElena Demikhovsky     return false;
819376a18bdSElena Demikhovsky 
820376a18bdSElena Demikhovsky   Value *Addend = nullptr;
821376a18bdSElena Demikhovsky   if (BOp->getOpcode() == Instruction::FAdd) {
822376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
823376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
824376a18bdSElena Demikhovsky     else if (BOp->getOperand(1) == Phi)
825376a18bdSElena Demikhovsky       Addend = BOp->getOperand(0);
826376a18bdSElena Demikhovsky   } else if (BOp->getOpcode() == Instruction::FSub)
827376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
828376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
829376a18bdSElena Demikhovsky 
830376a18bdSElena Demikhovsky   if (!Addend)
831376a18bdSElena Demikhovsky     return false;
832376a18bdSElena Demikhovsky 
833376a18bdSElena Demikhovsky   // The addend should be loop invariant
834376a18bdSElena Demikhovsky   if (auto *I = dyn_cast<Instruction>(Addend))
835376a18bdSElena Demikhovsky     if (TheLoop->contains(I))
836376a18bdSElena Demikhovsky       return false;
837376a18bdSElena Demikhovsky 
838376a18bdSElena Demikhovsky   // FP Step has unknown SCEV
839376a18bdSElena Demikhovsky   const SCEV *Step = SE->getUnknown(Addend);
840376a18bdSElena Demikhovsky   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
841376a18bdSElena Demikhovsky   return true;
842376a18bdSElena Demikhovsky }
843376a18bdSElena Demikhovsky 
844376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
845c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
846c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
847c05bab8aSSilviu Baranga                                          bool Assume) {
848c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
849376a18bdSElena Demikhovsky 
850376a18bdSElena Demikhovsky   // Handle integer and pointer inductions variables.
851376a18bdSElena Demikhovsky   // Now we handle also FP induction but not trying to make a
852376a18bdSElena Demikhovsky   // recurrent expression from the PHI node in-place.
853376a18bdSElena Demikhovsky 
854376a18bdSElena Demikhovsky   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
855376a18bdSElena Demikhovsky       !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
856c05bab8aSSilviu Baranga     return false;
857c05bab8aSSilviu Baranga 
858376a18bdSElena Demikhovsky   if (PhiTy->isFloatingPointTy())
859376a18bdSElena Demikhovsky     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
860376a18bdSElena Demikhovsky 
861c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
862c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
863c05bab8aSSilviu Baranga 
864c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
865c05bab8aSSilviu Baranga   if (Assume && !AR)
866c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
867c05bab8aSSilviu Baranga 
868c05bab8aSSilviu Baranga   if (!AR) {
869c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
870c05bab8aSSilviu Baranga     return false;
871c05bab8aSSilviu Baranga   }
872c05bab8aSSilviu Baranga 
873376a18bdSElena Demikhovsky   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
874c05bab8aSSilviu Baranga }
875c05bab8aSSilviu Baranga 
876376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
877c05bab8aSSilviu Baranga                                          ScalarEvolution *SE,
878c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
879c05bab8aSSilviu Baranga                                          const SCEV *Expr) {
88024e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
88124e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
88224e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
88324e6cc2dSKarthik Bhat     return false;
88424e6cc2dSKarthik Bhat 
88524e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
886c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
88724e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
888c05bab8aSSilviu Baranga 
88924e6cc2dSKarthik Bhat   if (!AR) {
89024e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
89124e6cc2dSKarthik Bhat     return false;
89224e6cc2dSKarthik Bhat   }
89324e6cc2dSKarthik Bhat 
894ee31cbe3SMichael Kuperstein   if (AR->getLoop() != TheLoop) {
895ee31cbe3SMichael Kuperstein     // FIXME: We should treat this as a uniform. Unfortunately, we
896ee31cbe3SMichael Kuperstein     // don't currently know how to handled uniform PHIs.
897ee31cbe3SMichael Kuperstein     DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
898ee31cbe3SMichael Kuperstein     return false;
899ee31cbe3SMichael Kuperstein   }
900ee31cbe3SMichael Kuperstein 
9011bbf15c5SJames Molloy   Value *StartValue =
9021bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
90324e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
90424e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
905c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
906c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
907376a18bdSElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
90824e6cc2dSKarthik Bhat     return false;
90924e6cc2dSKarthik Bhat 
91024e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
911c434d091SElena Demikhovsky     D = InductionDescriptor(StartValue, IK_IntInduction, Step);
91224e6cc2dSKarthik Bhat     return true;
91324e6cc2dSKarthik Bhat   }
91424e6cc2dSKarthik Bhat 
91524e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
916c434d091SElena Demikhovsky   // Pointer induction should be a constant.
917c434d091SElena Demikhovsky   if (!ConstStep)
918c434d091SElena Demikhovsky     return false;
919c434d091SElena Demikhovsky 
920c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
92124e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
92224e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
92324e6cc2dSKarthik Bhat   // sized.
92424e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
92524e6cc2dSKarthik Bhat     return false;
92624e6cc2dSKarthik Bhat 
92724e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
92824e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
929b58f32f7SDavid Majnemer   if (!Size)
930b58f32f7SDavid Majnemer     return false;
931b58f32f7SDavid Majnemer 
93224e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
93324e6cc2dSKarthik Bhat   if (CVSize % Size)
93424e6cc2dSKarthik Bhat     return false;
935c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
936c434d091SElena Demikhovsky                                     true /* signed */);
9371bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
93824e6cc2dSKarthik Bhat   return true;
93924e6cc2dSKarthik Bhat }
940c5b7b555SAshutosh Nema 
9414a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
9424a000883SChandler Carruth                                    bool PreserveLCSSA) {
9434a000883SChandler Carruth   bool Changed = false;
9444a000883SChandler Carruth 
9454a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
9464a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
9474a000883SChandler Carruth 
9484a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
9494a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
9504a000883SChandler Carruth            "Must start with an empty predecessors list!");
9514a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
9524a000883SChandler Carruth 
9534a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
9544a000883SChandler Carruth     // keep track of the in-loop predecessors.
9554a000883SChandler Carruth     bool IsDedicatedExit = true;
9564a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
9574a000883SChandler Carruth       if (L->contains(PredBB)) {
9584a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
9594a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
9604a000883SChandler Carruth           return false;
9614a000883SChandler Carruth 
9624a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
9634a000883SChandler Carruth       } else {
9644a000883SChandler Carruth         IsDedicatedExit = false;
9654a000883SChandler Carruth       }
9664a000883SChandler Carruth 
9674a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
9684a000883SChandler Carruth 
9694a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
9704a000883SChandler Carruth     if (IsDedicatedExit)
9714a000883SChandler Carruth       return false;
9724a000883SChandler Carruth 
9734a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
9744a000883SChandler Carruth         BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
9754a000883SChandler Carruth 
9764a000883SChandler Carruth     if (!NewExitBB)
9774a000883SChandler Carruth       DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
9784a000883SChandler Carruth                    << *L << "\n");
9794a000883SChandler Carruth     else
9804a000883SChandler Carruth       DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
9814a000883SChandler Carruth                    << NewExitBB->getName() << "\n");
9824a000883SChandler Carruth     return true;
9834a000883SChandler Carruth   };
9844a000883SChandler Carruth 
9854a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
9864a000883SChandler Carruth   // them, but only visit each one once.
9874a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
9884a000883SChandler Carruth   for (auto *BB : L->blocks())
9894a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
9904a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
9914a000883SChandler Carruth       if (L->contains(SuccBB))
9924a000883SChandler Carruth         continue;
9934a000883SChandler Carruth 
9944a000883SChandler Carruth       // Visit each exit block exactly once.
9954a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
9964a000883SChandler Carruth         continue;
9974a000883SChandler Carruth 
9984a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
9994a000883SChandler Carruth     }
10004a000883SChandler Carruth 
10014a000883SChandler Carruth   return Changed;
10024a000883SChandler Carruth }
10034a000883SChandler Carruth 
1004c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
1005c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
1006c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
1007c5b7b555SAshutosh Nema 
1008c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
1009c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
1010c5b7b555SAshutosh Nema     // be adapted into a pointer.
1011c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
1012c5b7b555SAshutosh Nema       auto Users = Inst.users();
10130a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
1014c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
1015c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
1016c5b7b555SAshutosh Nema           }))
1017c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
1018c5b7b555SAshutosh Nema     }
1019c5b7b555SAshutosh Nema 
1020c5b7b555SAshutosh Nema   return UsedOutside;
1021c5b7b555SAshutosh Nema }
102231088a9dSChandler Carruth 
102331088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
102431088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
102531088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
102631088a9dSChandler Carruth   // pass manager, they must also preserve these.
102731088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
102831088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
102931088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
103031088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
103131088a9dSChandler Carruth 
103231088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
103331088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
103431088a9dSChandler Carruth   extern char &LoopSimplifyID;
103531088a9dSChandler Carruth   extern char &LCSSAID;
103631088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
103731088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
103831088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
103931088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
1040c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
1041c3ccf5d7SIgor Laevsky   // which preserve lcssa form
1042c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
1043c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
104431088a9dSChandler Carruth 
104531088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
104631088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
104731088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
104831088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
104931088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
105031088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
105131088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
105231088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
105331088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
105431088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
105531088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
105631088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
105731088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
105831088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
105931088a9dSChandler Carruth }
106031088a9dSChandler Carruth 
106131088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
106231088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
106331088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
106431088a9dSChandler Carruth /// with:
106531088a9dSChandler Carruth ///
106631088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
106731088a9dSChandler Carruth ///
106831088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
106931088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
107031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
107131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
107231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1073e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
107431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
107531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
107631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
107731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
107831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
107931088a9dSChandler Carruth }
1080963341c8SAdam Nemet 
1081fe3def7cSAdam Nemet /// \brief Find string metadata for loop
1082fe3def7cSAdam Nemet ///
1083fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1084fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
1085fe3def7cSAdam Nemet /// Optional's not-a-value.
1086fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1087fe3def7cSAdam Nemet                                                             StringRef Name) {
1088963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
1089fe3def7cSAdam Nemet   // Return none if LoopID is false.
1090963341c8SAdam Nemet   if (!LoopID)
1091fe3def7cSAdam Nemet     return None;
1092293be666SAdam Nemet 
1093293be666SAdam Nemet   // First operand should refer to the loop id itself.
1094293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1095293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1096293be666SAdam Nemet 
1097963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
1098963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1099963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1100963341c8SAdam Nemet     if (!MD)
1101963341c8SAdam Nemet       continue;
1102963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1103963341c8SAdam Nemet     if (!S)
1104963341c8SAdam Nemet       continue;
1105963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
1106963341c8SAdam Nemet     if (Name.equals(S->getString()))
1107fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
1108fe3def7cSAdam Nemet       case 1:
1109fe3def7cSAdam Nemet         return nullptr;
1110fe3def7cSAdam Nemet       case 2:
1111fe3def7cSAdam Nemet         return &MD->getOperand(1);
1112fe3def7cSAdam Nemet       default:
1113fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
1114963341c8SAdam Nemet       }
1115fe3def7cSAdam Nemet   }
1116fe3def7cSAdam Nemet   return None;
1117963341c8SAdam Nemet }
1118122f984aSEvgeniy Stepanov 
11197ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
11207ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
11217ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
11227ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
11237ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
11247ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
11257ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
11267ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
11277ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
11287ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
11297ed5856aSAlina Sbirlea   };
11307ed5856aSAlina Sbirlea 
11317ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
11327ed5856aSAlina Sbirlea 
11337ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
11347ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
11357ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
11367ed5856aSAlina Sbirlea 
11377ed5856aSAlina Sbirlea   return Worklist;
11387ed5856aSAlina Sbirlea }
11397ed5856aSAlina Sbirlea 
1140df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
1141df3e71e0SMarcello Maggioni                           ScalarEvolution *SE = nullptr,
1142df3e71e0SMarcello Maggioni                           LoopInfo *LI = nullptr) {
1143899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
1144df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
1145df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
1146df3e71e0SMarcello Maggioni 
1147df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
1148df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
1149df3e71e0SMarcello Maggioni   //
1150df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
1151df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
1152df3e71e0SMarcello Maggioni 
1153df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
1154df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
1155df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
1156df3e71e0SMarcello Maggioni   if (SE)
1157df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
1158df3e71e0SMarcello Maggioni 
1159df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
1160df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
1161df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
1162df3e71e0SMarcello Maggioni 
1163df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1164df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
1165df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
1166df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
1167df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
1168df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
1169df3e71e0SMarcello Maggioni   // preheader -> header.
1170df3e71e0SMarcello Maggioni   //
1171df3e71e0SMarcello Maggioni   //
1172df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
1173df3e71e0SMarcello Maggioni   //        |                    |   |                   |
1174df3e71e0SMarcello Maggioni   //        V                    |   V                   |
1175df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
1176df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
1177df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
1178df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
1179df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
1180df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
1181df3e71e0SMarcello Maggioni   //
1182df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
1183df3e71e0SMarcello Maggioni   // update without using the batch update API.
1184df3e71e0SMarcello Maggioni   //
1185df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
1186df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
1187df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
1188df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
1189df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
1190df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
1191df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
1192df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
1193df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
1194df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
1195df3e71e0SMarcello Maggioni 
1196df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
1197df3e71e0SMarcello Maggioni   // instead of the exiting block.
1198df3e71e0SMarcello Maggioni   BasicBlock::iterator BI = ExitBlock->begin();
1199df3e71e0SMarcello Maggioni   while (PHINode *P = dyn_cast<PHINode>(BI)) {
1200df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
1201df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
1202df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
1203df3e71e0SMarcello Maggioni     int PredIndex = 0;
1204df3e71e0SMarcello Maggioni     P->setIncomingBlock(PredIndex, Preheader);
1205df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
1206df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
1207df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
1208df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
1209df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
1210df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
1211df3e71e0SMarcello Maggioni     // being deleted).
1212df3e71e0SMarcello Maggioni     for (unsigned i = 0, e = P->getNumIncomingValues() - 1; i != e; ++i)
1213df3e71e0SMarcello Maggioni       P->removeIncomingValue(e - i, false);
1214df3e71e0SMarcello Maggioni 
1215df3e71e0SMarcello Maggioni     assert((P->getNumIncomingValues() == 1 &&
1216df3e71e0SMarcello Maggioni             P->getIncomingBlock(PredIndex) == Preheader) &&
1217df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
1218df3e71e0SMarcello Maggioni     ++BI;
1219df3e71e0SMarcello Maggioni   }
1220df3e71e0SMarcello Maggioni 
1221df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
1222df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
1223df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
1224df3e71e0SMarcello Maggioni   // Remove the old branch.
1225df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
1226df3e71e0SMarcello Maggioni 
1227df3e71e0SMarcello Maggioni   if (DT) {
1228df3e71e0SMarcello Maggioni     // Update the dominator tree by informing it about the new edge from the
1229df3e71e0SMarcello Maggioni     // preheader to the exit.
1230df3e71e0SMarcello Maggioni     DT->insertEdge(Preheader, ExitBlock);
1231df3e71e0SMarcello Maggioni     // Inform the dominator tree about the removed edge.
1232df3e71e0SMarcello Maggioni     DT->deleteEdge(Preheader, L->getHeader());
1233df3e71e0SMarcello Maggioni   }
1234df3e71e0SMarcello Maggioni 
1235df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
1236df3e71e0SMarcello Maggioni   // delete it freely later.
1237df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
1238df3e71e0SMarcello Maggioni     Block->dropAllReferences();
1239df3e71e0SMarcello Maggioni 
1240df3e71e0SMarcello Maggioni   if (LI) {
1241df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
1242df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
1243df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
1244df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
1245df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
1246df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
1247df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
1248df3e71e0SMarcello Maggioni 
1249df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
1250df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
1251df3e71e0SMarcello Maggioni 
1252df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
1253df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
1254df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
1255df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
1256df3e71e0SMarcello Maggioni 
1257df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
1258df3e71e0SMarcello Maggioni     LI->erase(L);
1259df3e71e0SMarcello Maggioni   }
1260df3e71e0SMarcello Maggioni }
1261df3e71e0SMarcello Maggioni 
1262122f984aSEvgeniy Stepanov /// Returns true if the instruction in a loop is guaranteed to execute at least
1263122f984aSEvgeniy Stepanov /// once.
1264122f984aSEvgeniy Stepanov bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1265122f984aSEvgeniy Stepanov                                  const DominatorTree *DT, const Loop *CurLoop,
1266122f984aSEvgeniy Stepanov                                  const LoopSafetyInfo *SafetyInfo) {
1267122f984aSEvgeniy Stepanov   // We have to check to make sure that the instruction dominates all
126858ccc094SEvgeniy Stepanov   // of the exit blocks.  If it doesn't, then there is a path out of the loop
126958ccc094SEvgeniy Stepanov   // which does not execute this instruction, so we can't hoist it.
127058ccc094SEvgeniy Stepanov 
127158ccc094SEvgeniy Stepanov   // If the instruction is in the header block for the loop (which is very
127258ccc094SEvgeniy Stepanov   // common), it is always guaranteed to dominate the exit blocks.  Since this
127358ccc094SEvgeniy Stepanov   // is a common case, and can save some work, check it now.
127458ccc094SEvgeniy Stepanov   if (Inst.getParent() == CurLoop->getHeader())
127558ccc094SEvgeniy Stepanov     // If there's a throw in the header block, we can't guarantee we'll reach
127658ccc094SEvgeniy Stepanov     // Inst.
127758ccc094SEvgeniy Stepanov     return !SafetyInfo->HeaderMayThrow;
127858ccc094SEvgeniy Stepanov 
127958ccc094SEvgeniy Stepanov   // Somewhere in this loop there is an instruction which may throw and make us
128058ccc094SEvgeniy Stepanov   // exit the loop.
128158ccc094SEvgeniy Stepanov   if (SafetyInfo->MayThrow)
1282122f984aSEvgeniy Stepanov     return false;
1283122f984aSEvgeniy Stepanov 
1284122f984aSEvgeniy Stepanov   // Get the exit blocks for the current loop.
1285122f984aSEvgeniy Stepanov   SmallVector<BasicBlock *, 8> ExitBlocks;
1286122f984aSEvgeniy Stepanov   CurLoop->getExitBlocks(ExitBlocks);
1287122f984aSEvgeniy Stepanov 
1288122f984aSEvgeniy Stepanov   // Verify that the block dominates each of the exit blocks of the loop.
1289122f984aSEvgeniy Stepanov   for (BasicBlock *ExitBlock : ExitBlocks)
1290122f984aSEvgeniy Stepanov     if (!DT->dominates(Inst.getParent(), ExitBlock))
1291122f984aSEvgeniy Stepanov       return false;
1292122f984aSEvgeniy Stepanov 
1293122f984aSEvgeniy Stepanov   // As a degenerate case, if the loop is statically infinite then we haven't
1294122f984aSEvgeniy Stepanov   // proven anything since there are no exit blocks.
129558ccc094SEvgeniy Stepanov   if (ExitBlocks.empty())
1296122f984aSEvgeniy Stepanov     return false;
1297122f984aSEvgeniy Stepanov 
1298f1da33e4SEli Friedman   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1299f1da33e4SEli Friedman   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
1300f1da33e4SEli Friedman   // just a special case of this.)
1301122f984aSEvgeniy Stepanov   return true;
1302122f984aSEvgeniy Stepanov }
130341d72a86SDehao Chen 
130441d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
130541d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
130641d72a86SDehao Chen   if (!L->getExitingBlock())
130741d72a86SDehao Chen     return None;
130841d72a86SDehao Chen 
130941d72a86SDehao Chen   // Get the branch weights for the the loop's backedge.
131041d72a86SDehao Chen   BranchInst *LatchBR =
131141d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
131241d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
131341d72a86SDehao Chen     return None;
131441d72a86SDehao Chen 
131541d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
131641d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
131741d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
131841d72a86SDehao Chen 
131941d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
132041d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
132141d72a86SDehao Chen   // we exited the loop.
132241d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
1323b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
132441d72a86SDehao Chen     return None;
132541d72a86SDehao Chen 
1326b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
1327b151a641SMichael Kuperstein     return 0;
132841d72a86SDehao Chen 
1329b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
1330b151a641SMichael Kuperstein   // rounding to nearest.
133141d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
1332b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
133341d72a86SDehao Chen   else
1334b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
133541d72a86SDehao Chen }
1336cf9daa33SAmara Emerson 
1337cf9daa33SAmara Emerson /// \brief Adds a 'fast' flag to floating point operations.
1338cf9daa33SAmara Emerson static Value *addFastMathFlag(Value *V) {
1339cf9daa33SAmara Emerson   if (isa<FPMathOperator>(V)) {
1340cf9daa33SAmara Emerson     FastMathFlags Flags;
1341629c4115SSanjay Patel     Flags.setFast();
1342cf9daa33SAmara Emerson     cast<Instruction>(V)->setFastMathFlags(Flags);
1343cf9daa33SAmara Emerson   }
1344cf9daa33SAmara Emerson   return V;
1345cf9daa33SAmara Emerson }
1346cf9daa33SAmara Emerson 
1347cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
1348836b0f48SAmara Emerson Value *
1349836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1350836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1351836b0f48SAmara Emerson                           ArrayRef<Value *> RedOps) {
1352cf9daa33SAmara Emerson   unsigned VF = Src->getType()->getVectorNumElements();
1353cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1354cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
1355cf9daa33SAmara Emerson   // round.
1356cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
1357cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
1358cf9daa33SAmara Emerson   Value *TmpVec = Src;
1359cf9daa33SAmara Emerson   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1360cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
1361cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
1362cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
1363cf9daa33SAmara Emerson       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1364cf9daa33SAmara Emerson 
1365cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
1366cf9daa33SAmara Emerson     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1367cf9daa33SAmara Emerson               UndefValue::get(Builder.getInt32Ty()));
1368cf9daa33SAmara Emerson 
1369cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
1370cf9daa33SAmara Emerson         TmpVec, UndefValue::get(TmpVec->getType()),
1371cf9daa33SAmara Emerson         ConstantVector::get(ShuffleMask), "rdx.shuf");
1372cf9daa33SAmara Emerson 
1373cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1374cf9daa33SAmara Emerson       // Floating point operations had to be 'fast' to enable the reduction.
1375cf9daa33SAmara Emerson       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1376cf9daa33SAmara Emerson                                                    TmpVec, Shuf, "bin.rdx"));
1377cf9daa33SAmara Emerson     } else {
1378cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1379cf9daa33SAmara Emerson              "Invalid min/max");
1380cf9daa33SAmara Emerson       TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1381cf9daa33SAmara Emerson                                                     Shuf);
1382cf9daa33SAmara Emerson     }
1383cf9daa33SAmara Emerson     if (!RedOps.empty())
1384cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
1385cf9daa33SAmara Emerson   }
1386cf9daa33SAmara Emerson   // The result is in the first element of the vector.
1387cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1388cf9daa33SAmara Emerson }
1389cf9daa33SAmara Emerson 
1390cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
1391cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
1392cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
1393cf9daa33SAmara Emerson     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1394cf9daa33SAmara Emerson     Value *Src, TargetTransformInfo::ReductionFlags Flags,
1395cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
1396cf9daa33SAmara Emerson   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1397cf9daa33SAmara Emerson 
1398cf9daa33SAmara Emerson   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1399cf9daa33SAmara Emerson   std::function<Value*()> BuildFunc;
1400cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
1401cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1402cf9daa33SAmara Emerson   // TODO: Support creating ordered reductions.
1403*1ea7b6f7SSanjay Patel   FastMathFlags FMFFast;
1404*1ea7b6f7SSanjay Patel   FMFFast.setFast();
1405cf9daa33SAmara Emerson 
1406cf9daa33SAmara Emerson   switch (Opcode) {
1407cf9daa33SAmara Emerson   case Instruction::Add:
1408cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1409cf9daa33SAmara Emerson     break;
1410cf9daa33SAmara Emerson   case Instruction::Mul:
1411cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1412cf9daa33SAmara Emerson     break;
1413cf9daa33SAmara Emerson   case Instruction::And:
1414cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1415cf9daa33SAmara Emerson     break;
1416cf9daa33SAmara Emerson   case Instruction::Or:
1417cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1418cf9daa33SAmara Emerson     break;
1419cf9daa33SAmara Emerson   case Instruction::Xor:
1420cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1421cf9daa33SAmara Emerson     break;
1422cf9daa33SAmara Emerson   case Instruction::FAdd:
1423cf9daa33SAmara Emerson     BuildFunc = [&]() {
1424cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
1425*1ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1426cf9daa33SAmara Emerson       return Rdx;
1427cf9daa33SAmara Emerson     };
1428cf9daa33SAmara Emerson     break;
1429cf9daa33SAmara Emerson   case Instruction::FMul:
1430cf9daa33SAmara Emerson     BuildFunc = [&]() {
1431cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
1432*1ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1433cf9daa33SAmara Emerson       return Rdx;
1434cf9daa33SAmara Emerson     };
1435cf9daa33SAmara Emerson     break;
1436cf9daa33SAmara Emerson   case Instruction::ICmp:
1437cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1438cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1439cf9daa33SAmara Emerson       BuildFunc = [&]() {
1440cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1441cf9daa33SAmara Emerson       };
1442cf9daa33SAmara Emerson     } else {
1443cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1444cf9daa33SAmara Emerson       BuildFunc = [&]() {
1445cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1446cf9daa33SAmara Emerson       };
1447cf9daa33SAmara Emerson     }
1448cf9daa33SAmara Emerson     break;
1449cf9daa33SAmara Emerson   case Instruction::FCmp:
1450cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1451cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1452cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1453cf9daa33SAmara Emerson     } else {
1454cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1455cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1456cf9daa33SAmara Emerson     }
1457cf9daa33SAmara Emerson     break;
1458cf9daa33SAmara Emerson   default:
1459cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1460cf9daa33SAmara Emerson     break;
1461cf9daa33SAmara Emerson   }
1462cf9daa33SAmara Emerson   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1463cf9daa33SAmara Emerson     return BuildFunc();
1464cf9daa33SAmara Emerson   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1465cf9daa33SAmara Emerson }
1466cf9daa33SAmara Emerson 
1467cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
1468cf9daa33SAmara Emerson Value *llvm::createTargetReduction(IRBuilder<> &Builder,
1469cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1470cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1471cf9daa33SAmara Emerson                                    bool NoNaN) {
1472cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
1473cf9daa33SAmara Emerson   RecurrenceDescriptor::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1474cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1475cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1476cf9daa33SAmara Emerson   auto getSimpleRdx = [&](unsigned Opc) {
1477cf9daa33SAmara Emerson     return createSimpleTargetReduction(Builder, TTI, Opc, Src, Flags);
1478cf9daa33SAmara Emerson   };
1479cf9daa33SAmara Emerson   switch (RecKind) {
1480cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_FloatAdd:
1481cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::FAdd);
1482cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_FloatMult:
1483cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::FMul);
1484cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerAdd:
1485cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::Add);
1486cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerMult:
1487cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::Mul);
1488cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerAnd:
1489cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::And);
1490cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerOr:
1491cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::Or);
1492cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerXor:
1493cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::Xor);
1494cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_IntegerMinMax: {
1495cf9daa33SAmara Emerson     switch (Desc.getMinMaxRecurrenceKind()) {
1496cf9daa33SAmara Emerson     case RecurrenceDescriptor::MRK_SIntMax:
1497cf9daa33SAmara Emerson       Flags.IsSigned = true;
1498cf9daa33SAmara Emerson       Flags.IsMaxOp = true;
1499cf9daa33SAmara Emerson       break;
1500cf9daa33SAmara Emerson     case RecurrenceDescriptor::MRK_UIntMax:
1501cf9daa33SAmara Emerson       Flags.IsMaxOp = true;
1502cf9daa33SAmara Emerson       break;
1503cf9daa33SAmara Emerson     case RecurrenceDescriptor::MRK_SIntMin:
1504cf9daa33SAmara Emerson       Flags.IsSigned = true;
1505cf9daa33SAmara Emerson       break;
1506cf9daa33SAmara Emerson     case RecurrenceDescriptor::MRK_UIntMin:
1507cf9daa33SAmara Emerson       break;
1508cf9daa33SAmara Emerson     default:
1509cf9daa33SAmara Emerson       llvm_unreachable("Unhandled MRK");
1510cf9daa33SAmara Emerson     }
1511cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::ICmp);
1512cf9daa33SAmara Emerson   }
1513cf9daa33SAmara Emerson   case RecurrenceDescriptor::RK_FloatMinMax: {
1514cf9daa33SAmara Emerson     Flags.IsMaxOp =
1515cf9daa33SAmara Emerson         Desc.getMinMaxRecurrenceKind() == RecurrenceDescriptor::MRK_FloatMax;
1516cf9daa33SAmara Emerson     return getSimpleRdx(Instruction::FCmp);
1517cf9daa33SAmara Emerson   }
1518cf9daa33SAmara Emerson   default:
1519cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
1520cf9daa33SAmara Emerson   }
1521cf9daa33SAmara Emerson }
1522cf9daa33SAmara Emerson 
1523a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1524a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1525a61f4b89SDinar Temirbulatov   if (!VecOp)
1526a61f4b89SDinar Temirbulatov     return;
1527a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1528a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1529a61f4b89SDinar Temirbulatov   if (!Intersection)
1530a61f4b89SDinar Temirbulatov     return;
1531a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1532a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1533a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1534a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1535a61f4b89SDinar Temirbulatov     if (!Instr)
1536a61f4b89SDinar Temirbulatov       continue;
1537a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1538a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1539cf9daa33SAmara Emerson   }
1540cf9daa33SAmara Emerson }
1541