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,
6814750c785SDorit Nuzman                                          const SCEV *Step, BinaryOperator *BOp,
6824750c785SDorit Nuzman                                          SmallVectorImpl<Instruction *> *Casts)
683376a18bdSElena Demikhovsky   : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
6841bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
685c434d091SElena Demikhovsky 
686c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
687c434d091SElena Demikhovsky   // itself should not be null.
6881bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
6891bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
6901bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
6911bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
6921bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
693c434d091SElena Demikhovsky 
694c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
695c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
696c434d091SElena Demikhovsky          "Step value is zero");
697c434d091SElena Demikhovsky 
698c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
699c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
700376a18bdSElena Demikhovsky   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
701376a18bdSElena Demikhovsky          "StepValue is not an integer");
702376a18bdSElena Demikhovsky 
703376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
704376a18bdSElena Demikhovsky          "StepValue is not FP for FpInduction");
705376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || (InductionBinOp &&
706376a18bdSElena Demikhovsky           (InductionBinOp->getOpcode() == Instruction::FAdd ||
707376a18bdSElena Demikhovsky            InductionBinOp->getOpcode() == Instruction::FSub))) &&
708376a18bdSElena Demikhovsky          "Binary opcode should be specified for FP induction");
7094750c785SDorit Nuzman 
7104750c785SDorit Nuzman   if (Casts) {
7114750c785SDorit Nuzman     for (auto &Inst : *Casts) {
7124750c785SDorit Nuzman       RedundantCasts.push_back(Inst);
7134750c785SDorit Nuzman     }
7144750c785SDorit Nuzman   }
7151bbf15c5SJames Molloy }
7161bbf15c5SJames Molloy 
7171bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
718c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
719c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
720c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
7211bbf15c5SJames Molloy   return 0;
7221bbf15c5SJames Molloy }
7231bbf15c5SJames Molloy 
724c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
725c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
726c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
727c434d091SElena Demikhovsky   return nullptr;
728c434d091SElena Demikhovsky }
729c434d091SElena Demikhovsky 
730c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
731c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
732c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
733c434d091SElena Demikhovsky 
734c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
735376a18bdSElena Demikhovsky   assert(Index->getType() == Step->getType() &&
736376a18bdSElena Demikhovsky          "Index type does not match StepValue type");
7371bbf15c5SJames Molloy   switch (IK) {
738c434d091SElena Demikhovsky   case IK_IntInduction: {
7391bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
7401bbf15c5SJames Molloy            "Index type does not match StartValue type");
741c434d091SElena Demikhovsky 
742c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
743c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
744c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
745c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
746c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
747c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
748c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
749c434d091SElena Demikhovsky 
750c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
751c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
7521bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
753c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
754c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
7551bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
756c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
757c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
758c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
759c434d091SElena Demikhovsky   }
760c434d091SElena Demikhovsky   case IK_PtrInduction: {
761c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
762c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
763c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
764c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
7651bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
766c434d091SElena Demikhovsky   }
767376a18bdSElena Demikhovsky   case IK_FpInduction: {
768376a18bdSElena Demikhovsky     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
769376a18bdSElena Demikhovsky     assert(InductionBinOp &&
770376a18bdSElena Demikhovsky            (InductionBinOp->getOpcode() == Instruction::FAdd ||
771376a18bdSElena Demikhovsky             InductionBinOp->getOpcode() == Instruction::FSub) &&
772376a18bdSElena Demikhovsky            "Original bin op should be defined for FP induction");
773376a18bdSElena Demikhovsky 
774376a18bdSElena Demikhovsky     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
775376a18bdSElena Demikhovsky 
776376a18bdSElena Demikhovsky     // Floating point operations had to be 'fast' to enable the induction.
777376a18bdSElena Demikhovsky     FastMathFlags Flags;
778629c4115SSanjay Patel     Flags.setFast();
779376a18bdSElena Demikhovsky 
780376a18bdSElena Demikhovsky     Value *MulExp = B.CreateFMul(StepValue, Index);
781376a18bdSElena Demikhovsky     if (isa<Instruction>(MulExp))
782376a18bdSElena Demikhovsky       // We have to check, the MulExp may be a constant.
783376a18bdSElena Demikhovsky       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
784376a18bdSElena Demikhovsky 
785376a18bdSElena Demikhovsky     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
786376a18bdSElena Demikhovsky                                MulExp, "induction");
787376a18bdSElena Demikhovsky     if (isa<Instruction>(BOp))
788376a18bdSElena Demikhovsky       cast<Instruction>(BOp)->setFastMathFlags(Flags);
789376a18bdSElena Demikhovsky 
790376a18bdSElena Demikhovsky     return BOp;
791376a18bdSElena Demikhovsky   }
7921bbf15c5SJames Molloy   case IK_NoInduction:
7931bbf15c5SJames Molloy     return nullptr;
7941bbf15c5SJames Molloy   }
7951bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
7961bbf15c5SJames Molloy }
7971bbf15c5SJames Molloy 
798376a18bdSElena Demikhovsky bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
799376a18bdSElena Demikhovsky                                            ScalarEvolution *SE,
800376a18bdSElena Demikhovsky                                            InductionDescriptor &D) {
801376a18bdSElena Demikhovsky 
802376a18bdSElena Demikhovsky   // Here we only handle FP induction variables.
803376a18bdSElena Demikhovsky   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
804376a18bdSElena Demikhovsky 
805376a18bdSElena Demikhovsky   if (TheLoop->getHeader() != Phi->getParent())
806376a18bdSElena Demikhovsky     return false;
807376a18bdSElena Demikhovsky 
808376a18bdSElena Demikhovsky   // The loop may have multiple entrances or multiple exits; we can analyze
809376a18bdSElena Demikhovsky   // this phi if it has a unique entry value and a unique backedge value.
810376a18bdSElena Demikhovsky   if (Phi->getNumIncomingValues() != 2)
811376a18bdSElena Demikhovsky     return false;
812376a18bdSElena Demikhovsky   Value *BEValue = nullptr, *StartValue = nullptr;
813376a18bdSElena Demikhovsky   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
814376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(0);
815376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(1);
816376a18bdSElena Demikhovsky   } else {
817376a18bdSElena Demikhovsky     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
818376a18bdSElena Demikhovsky            "Unexpected Phi node in the loop");
819376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(1);
820376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(0);
821376a18bdSElena Demikhovsky   }
822376a18bdSElena Demikhovsky 
823376a18bdSElena Demikhovsky   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
824376a18bdSElena Demikhovsky   if (!BOp)
825376a18bdSElena Demikhovsky     return false;
826376a18bdSElena Demikhovsky 
827376a18bdSElena Demikhovsky   Value *Addend = nullptr;
828376a18bdSElena Demikhovsky   if (BOp->getOpcode() == Instruction::FAdd) {
829376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
830376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
831376a18bdSElena Demikhovsky     else if (BOp->getOperand(1) == Phi)
832376a18bdSElena Demikhovsky       Addend = BOp->getOperand(0);
833376a18bdSElena Demikhovsky   } else if (BOp->getOpcode() == Instruction::FSub)
834376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
835376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
836376a18bdSElena Demikhovsky 
837376a18bdSElena Demikhovsky   if (!Addend)
838376a18bdSElena Demikhovsky     return false;
839376a18bdSElena Demikhovsky 
840376a18bdSElena Demikhovsky   // The addend should be loop invariant
841376a18bdSElena Demikhovsky   if (auto *I = dyn_cast<Instruction>(Addend))
842376a18bdSElena Demikhovsky     if (TheLoop->contains(I))
843376a18bdSElena Demikhovsky       return false;
844376a18bdSElena Demikhovsky 
845376a18bdSElena Demikhovsky   // FP Step has unknown SCEV
846376a18bdSElena Demikhovsky   const SCEV *Step = SE->getUnknown(Addend);
847376a18bdSElena Demikhovsky   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
848376a18bdSElena Demikhovsky   return true;
849376a18bdSElena Demikhovsky }
850376a18bdSElena Demikhovsky 
8514750c785SDorit Nuzman /// This function is called when we suspect that the update-chain of a phi node
8524750c785SDorit Nuzman /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
8534750c785SDorit Nuzman /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
8544750c785SDorit Nuzman /// predicate P under which the SCEV expression for the phi can be the
8554750c785SDorit Nuzman /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
8564750c785SDorit Nuzman /// cast instructions that are involved in the update-chain of this induction.
8574750c785SDorit Nuzman /// A caller that adds the required runtime predicate can be free to drop these
8584750c785SDorit Nuzman /// cast instructions, and compute the phi using \p AR (instead of some scev
8594750c785SDorit Nuzman /// expression with casts).
8604750c785SDorit Nuzman ///
8614750c785SDorit Nuzman /// For example, without a predicate the scev expression can take the following
8624750c785SDorit Nuzman /// form:
8634750c785SDorit Nuzman ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
8644750c785SDorit Nuzman ///
8654750c785SDorit Nuzman /// It corresponds to the following IR sequence:
8664750c785SDorit Nuzman /// %for.body:
8674750c785SDorit Nuzman ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
8684750c785SDorit Nuzman ///   %casted_phi = "ExtTrunc i64 %x"
8694750c785SDorit Nuzman ///   %add = add i64 %casted_phi, %step
8704750c785SDorit Nuzman ///
8714750c785SDorit Nuzman /// where %x is given in \p PN,
8724750c785SDorit Nuzman /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
8734750c785SDorit Nuzman /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
8744750c785SDorit Nuzman /// several forms, for example, such as:
8754750c785SDorit Nuzman ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
8764750c785SDorit Nuzman /// or:
8774750c785SDorit Nuzman ///   ExtTrunc2:    %t = shl %x, m
8784750c785SDorit Nuzman ///                 %casted_phi = ashr %t, m
8794750c785SDorit Nuzman ///
8804750c785SDorit Nuzman /// If we are able to find such sequence, we return the instructions
8814750c785SDorit Nuzman /// we found, namely %casted_phi and the instructions on its use-def chain up
8824750c785SDorit Nuzman /// to the phi (not including the phi).
883802e6255SBenjamin Kramer static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
884802e6255SBenjamin Kramer                                     const SCEVUnknown *PhiScev,
885802e6255SBenjamin Kramer                                     const SCEVAddRecExpr *AR,
886802e6255SBenjamin Kramer                                     SmallVectorImpl<Instruction *> &CastInsts) {
8874750c785SDorit Nuzman 
8884750c785SDorit Nuzman   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
8894750c785SDorit Nuzman   auto *PN = cast<PHINode>(PhiScev->getValue());
8904750c785SDorit Nuzman   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
8914750c785SDorit Nuzman   const Loop *L = AR->getLoop();
8924750c785SDorit Nuzman 
8934750c785SDorit Nuzman   // Find any cast instructions that participate in the def-use chain of
8944750c785SDorit Nuzman   // PhiScev in the loop.
8954750c785SDorit Nuzman   // FORNOW/TODO: We currently expect the def-use chain to include only
8964750c785SDorit Nuzman   // two-operand instructions, where one of the operands is an invariant.
8974750c785SDorit Nuzman   // createAddRecFromPHIWithCasts() currently does not support anything more
8984750c785SDorit Nuzman   // involved than that, so we keep the search simple. This can be
8994750c785SDorit Nuzman   // extended/generalized as needed.
9004750c785SDorit Nuzman 
9014750c785SDorit Nuzman   auto getDef = [&](const Value *Val) -> Value * {
9024750c785SDorit Nuzman     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
9034750c785SDorit Nuzman     if (!BinOp)
9044750c785SDorit Nuzman       return nullptr;
9054750c785SDorit Nuzman     Value *Op0 = BinOp->getOperand(0);
9064750c785SDorit Nuzman     Value *Op1 = BinOp->getOperand(1);
9074750c785SDorit Nuzman     Value *Def = nullptr;
9084750c785SDorit Nuzman     if (L->isLoopInvariant(Op0))
9094750c785SDorit Nuzman       Def = Op1;
9104750c785SDorit Nuzman     else if (L->isLoopInvariant(Op1))
9114750c785SDorit Nuzman       Def = Op0;
9124750c785SDorit Nuzman     return Def;
9134750c785SDorit Nuzman   };
9144750c785SDorit Nuzman 
9154750c785SDorit Nuzman   // Look for the instruction that defines the induction via the
9164750c785SDorit Nuzman   // loop backedge.
9174750c785SDorit Nuzman   BasicBlock *Latch = L->getLoopLatch();
9184750c785SDorit Nuzman   if (!Latch)
9194750c785SDorit Nuzman     return false;
9204750c785SDorit Nuzman   Value *Val = PN->getIncomingValueForBlock(Latch);
9214750c785SDorit Nuzman   if (!Val)
9224750c785SDorit Nuzman     return false;
9234750c785SDorit Nuzman 
9244750c785SDorit Nuzman   // Follow the def-use chain until the induction phi is reached.
9254750c785SDorit Nuzman   // If on the way we encounter a Value that has the same SCEV Expr as the
9264750c785SDorit Nuzman   // phi node, we can consider the instructions we visit from that point
9274750c785SDorit Nuzman   // as part of the cast-sequence that can be ignored.
9284750c785SDorit Nuzman   bool InCastSequence = false;
9294750c785SDorit Nuzman   auto *Inst = dyn_cast<Instruction>(Val);
9304750c785SDorit Nuzman   while (Val != PN) {
9314750c785SDorit Nuzman     // If we encountered a phi node other than PN, or if we left the loop,
9324750c785SDorit Nuzman     // we bail out.
9334750c785SDorit Nuzman     if (!Inst || !L->contains(Inst)) {
9344750c785SDorit Nuzman       return false;
9354750c785SDorit Nuzman     }
9364750c785SDorit Nuzman     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
9374750c785SDorit Nuzman     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
9384750c785SDorit Nuzman       InCastSequence = true;
9394750c785SDorit Nuzman     if (InCastSequence) {
9404750c785SDorit Nuzman       // Only the last instruction in the cast sequence is expected to have
9414750c785SDorit Nuzman       // uses outside the induction def-use chain.
9424750c785SDorit Nuzman       if (!CastInsts.empty())
9434750c785SDorit Nuzman         if (!Inst->hasOneUse())
9444750c785SDorit Nuzman           return false;
9454750c785SDorit Nuzman       CastInsts.push_back(Inst);
9464750c785SDorit Nuzman     }
9474750c785SDorit Nuzman     Val = getDef(Val);
9484750c785SDorit Nuzman     if (!Val)
9494750c785SDorit Nuzman       return false;
9504750c785SDorit Nuzman     Inst = dyn_cast<Instruction>(Val);
9514750c785SDorit Nuzman   }
9524750c785SDorit Nuzman 
9534750c785SDorit Nuzman   return InCastSequence;
9544750c785SDorit Nuzman }
9554750c785SDorit Nuzman 
956376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
957c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
958c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
959c05bab8aSSilviu Baranga                                          bool Assume) {
960c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
961376a18bdSElena Demikhovsky 
962376a18bdSElena Demikhovsky   // Handle integer and pointer inductions variables.
963376a18bdSElena Demikhovsky   // Now we handle also FP induction but not trying to make a
964376a18bdSElena Demikhovsky   // recurrent expression from the PHI node in-place.
965376a18bdSElena Demikhovsky 
966376a18bdSElena Demikhovsky   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
967376a18bdSElena Demikhovsky       !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
968c05bab8aSSilviu Baranga     return false;
969c05bab8aSSilviu Baranga 
970376a18bdSElena Demikhovsky   if (PhiTy->isFloatingPointTy())
971376a18bdSElena Demikhovsky     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
972376a18bdSElena Demikhovsky 
973c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
974c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
975c05bab8aSSilviu Baranga 
976c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
977c05bab8aSSilviu Baranga   if (Assume && !AR)
978c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
979c05bab8aSSilviu Baranga 
980c05bab8aSSilviu Baranga   if (!AR) {
981c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
982c05bab8aSSilviu Baranga     return false;
983c05bab8aSSilviu Baranga   }
984c05bab8aSSilviu Baranga 
9854750c785SDorit Nuzman   // Record any Cast instructions that participate in the induction update
9864750c785SDorit Nuzman   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
9874750c785SDorit Nuzman   // If we started from an UnknownSCEV, and managed to build an addRecurrence
9884750c785SDorit Nuzman   // only after enabling Assume with PSCEV, this means we may have encountered
9894750c785SDorit Nuzman   // cast instructions that required adding a runtime check in order to
9904750c785SDorit Nuzman   // guarantee the correctness of the AddRecurence respresentation of the
9914750c785SDorit Nuzman   // induction.
9924750c785SDorit Nuzman   if (PhiScev != AR && SymbolicPhi) {
9934750c785SDorit Nuzman     SmallVector<Instruction *, 2> Casts;
9944750c785SDorit Nuzman     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
9954750c785SDorit Nuzman       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
9964750c785SDorit Nuzman   }
9974750c785SDorit Nuzman 
998376a18bdSElena Demikhovsky   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
999c05bab8aSSilviu Baranga }
1000c05bab8aSSilviu Baranga 
10014750c785SDorit Nuzman bool InductionDescriptor::isInductionPHI(
10024750c785SDorit Nuzman     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
10034750c785SDorit Nuzman     InductionDescriptor &D, const SCEV *Expr,
10044750c785SDorit Nuzman     SmallVectorImpl<Instruction *> *CastsToIgnore) {
100524e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
100624e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
100724e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
100824e6cc2dSKarthik Bhat     return false;
100924e6cc2dSKarthik Bhat 
101024e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
1011c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
101224e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1013c05bab8aSSilviu Baranga 
101424e6cc2dSKarthik Bhat   if (!AR) {
101524e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
101624e6cc2dSKarthik Bhat     return false;
101724e6cc2dSKarthik Bhat   }
101824e6cc2dSKarthik Bhat 
1019ee31cbe3SMichael Kuperstein   if (AR->getLoop() != TheLoop) {
1020ee31cbe3SMichael Kuperstein     // FIXME: We should treat this as a uniform. Unfortunately, we
1021ee31cbe3SMichael Kuperstein     // don't currently know how to handled uniform PHIs.
1022ee31cbe3SMichael Kuperstein     DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1023ee31cbe3SMichael Kuperstein     return false;
1024ee31cbe3SMichael Kuperstein   }
1025ee31cbe3SMichael Kuperstein 
10261bbf15c5SJames Molloy   Value *StartValue =
10271bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
102824e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
102924e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
1030c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
1031c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1032376a18bdSElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
103324e6cc2dSKarthik Bhat     return false;
103424e6cc2dSKarthik Bhat 
103524e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
10364750c785SDorit Nuzman     D = InductionDescriptor(StartValue, IK_IntInduction, Step, /*BOp=*/ nullptr,
10374750c785SDorit Nuzman                             CastsToIgnore);
103824e6cc2dSKarthik Bhat     return true;
103924e6cc2dSKarthik Bhat   }
104024e6cc2dSKarthik Bhat 
104124e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1042c434d091SElena Demikhovsky   // Pointer induction should be a constant.
1043c434d091SElena Demikhovsky   if (!ConstStep)
1044c434d091SElena Demikhovsky     return false;
1045c434d091SElena Demikhovsky 
1046c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
104724e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
104824e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
104924e6cc2dSKarthik Bhat   // sized.
105024e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
105124e6cc2dSKarthik Bhat     return false;
105224e6cc2dSKarthik Bhat 
105324e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
105424e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1055b58f32f7SDavid Majnemer   if (!Size)
1056b58f32f7SDavid Majnemer     return false;
1057b58f32f7SDavid Majnemer 
105824e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
105924e6cc2dSKarthik Bhat   if (CVSize % Size)
106024e6cc2dSKarthik Bhat     return false;
1061c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
1062c434d091SElena Demikhovsky                                     true /* signed */);
10631bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
106424e6cc2dSKarthik Bhat   return true;
106524e6cc2dSKarthik Bhat }
1066c5b7b555SAshutosh Nema 
10674a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
10684a000883SChandler Carruth                                    bool PreserveLCSSA) {
10694a000883SChandler Carruth   bool Changed = false;
10704a000883SChandler Carruth 
10714a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
10724a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
10734a000883SChandler Carruth 
10744a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
10754a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
10764a000883SChandler Carruth            "Must start with an empty predecessors list!");
10774a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
10784a000883SChandler Carruth 
10794a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
10804a000883SChandler Carruth     // keep track of the in-loop predecessors.
10814a000883SChandler Carruth     bool IsDedicatedExit = true;
10824a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
10834a000883SChandler Carruth       if (L->contains(PredBB)) {
10844a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
10854a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
10864a000883SChandler Carruth           return false;
10874a000883SChandler Carruth 
10884a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
10894a000883SChandler Carruth       } else {
10904a000883SChandler Carruth         IsDedicatedExit = false;
10914a000883SChandler Carruth       }
10924a000883SChandler Carruth 
10934a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
10944a000883SChandler Carruth 
10954a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
10964a000883SChandler Carruth     if (IsDedicatedExit)
10974a000883SChandler Carruth       return false;
10984a000883SChandler Carruth 
10994a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
11004a000883SChandler Carruth         BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
11014a000883SChandler Carruth 
11024a000883SChandler Carruth     if (!NewExitBB)
11034a000883SChandler Carruth       DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
11044a000883SChandler Carruth                    << *L << "\n");
11054a000883SChandler Carruth     else
11064a000883SChandler Carruth       DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
11074a000883SChandler Carruth                    << NewExitBB->getName() << "\n");
11084a000883SChandler Carruth     return true;
11094a000883SChandler Carruth   };
11104a000883SChandler Carruth 
11114a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
11124a000883SChandler Carruth   // them, but only visit each one once.
11134a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
11144a000883SChandler Carruth   for (auto *BB : L->blocks())
11154a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
11164a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
11174a000883SChandler Carruth       if (L->contains(SuccBB))
11184a000883SChandler Carruth         continue;
11194a000883SChandler Carruth 
11204a000883SChandler Carruth       // Visit each exit block exactly once.
11214a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
11224a000883SChandler Carruth         continue;
11234a000883SChandler Carruth 
11244a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
11254a000883SChandler Carruth     }
11264a000883SChandler Carruth 
11274a000883SChandler Carruth   return Changed;
11284a000883SChandler Carruth }
11294a000883SChandler Carruth 
1130c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
1131c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
1132c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
1133c5b7b555SAshutosh Nema 
1134c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
1135c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
1136c5b7b555SAshutosh Nema     // be adapted into a pointer.
1137c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
1138c5b7b555SAshutosh Nema       auto Users = Inst.users();
11390a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
1140c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
1141c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
1142c5b7b555SAshutosh Nema           }))
1143c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
1144c5b7b555SAshutosh Nema     }
1145c5b7b555SAshutosh Nema 
1146c5b7b555SAshutosh Nema   return UsedOutside;
1147c5b7b555SAshutosh Nema }
114831088a9dSChandler Carruth 
114931088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
115031088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
115131088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
115231088a9dSChandler Carruth   // pass manager, they must also preserve these.
115331088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
115431088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
115531088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
115631088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
115731088a9dSChandler Carruth 
115831088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
115931088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
116031088a9dSChandler Carruth   extern char &LoopSimplifyID;
116131088a9dSChandler Carruth   extern char &LCSSAID;
116231088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
116331088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
116431088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
116531088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
1166c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
1167c3ccf5d7SIgor Laevsky   // which preserve lcssa form
1168c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
1169c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
117031088a9dSChandler Carruth 
117131088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
117231088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
117331088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
117431088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
117531088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
117631088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
117731088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
117831088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
117931088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
118031088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
118131088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
118231088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
118331088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
118431088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
118531088a9dSChandler Carruth }
118631088a9dSChandler Carruth 
118731088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
118831088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
118931088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
119031088a9dSChandler Carruth /// with:
119131088a9dSChandler Carruth ///
119231088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
119331088a9dSChandler Carruth ///
119431088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
119531088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
119631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
119731088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
119831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1199e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
120031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
120131088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
120231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
120331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
120431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
120531088a9dSChandler Carruth }
1206963341c8SAdam Nemet 
1207fe3def7cSAdam Nemet /// \brief Find string metadata for loop
1208fe3def7cSAdam Nemet ///
1209fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1210fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
1211fe3def7cSAdam Nemet /// Optional's not-a-value.
1212fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1213fe3def7cSAdam Nemet                                                             StringRef Name) {
1214963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
1215fe3def7cSAdam Nemet   // Return none if LoopID is false.
1216963341c8SAdam Nemet   if (!LoopID)
1217fe3def7cSAdam Nemet     return None;
1218293be666SAdam Nemet 
1219293be666SAdam Nemet   // First operand should refer to the loop id itself.
1220293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1221293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1222293be666SAdam Nemet 
1223963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
1224963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1225963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1226963341c8SAdam Nemet     if (!MD)
1227963341c8SAdam Nemet       continue;
1228963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1229963341c8SAdam Nemet     if (!S)
1230963341c8SAdam Nemet       continue;
1231963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
1232963341c8SAdam Nemet     if (Name.equals(S->getString()))
1233fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
1234fe3def7cSAdam Nemet       case 1:
1235fe3def7cSAdam Nemet         return nullptr;
1236fe3def7cSAdam Nemet       case 2:
1237fe3def7cSAdam Nemet         return &MD->getOperand(1);
1238fe3def7cSAdam Nemet       default:
1239fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
1240963341c8SAdam Nemet       }
1241fe3def7cSAdam Nemet   }
1242fe3def7cSAdam Nemet   return None;
1243963341c8SAdam Nemet }
1244122f984aSEvgeniy Stepanov 
12457ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
12467ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
12477ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
12487ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
12497ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
12507ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
12517ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
12527ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
12537ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
12547ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
12557ed5856aSAlina Sbirlea   };
12567ed5856aSAlina Sbirlea 
12577ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
12587ed5856aSAlina Sbirlea 
12597ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
12607ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
12617ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
12627ed5856aSAlina Sbirlea 
12637ed5856aSAlina Sbirlea   return Worklist;
12647ed5856aSAlina Sbirlea }
12657ed5856aSAlina Sbirlea 
1266df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
1267df3e71e0SMarcello Maggioni                           ScalarEvolution *SE = nullptr,
1268df3e71e0SMarcello Maggioni                           LoopInfo *LI = nullptr) {
1269899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
1270df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
1271df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
1272df3e71e0SMarcello Maggioni 
1273df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
1274df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
1275df3e71e0SMarcello Maggioni   //
1276df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
1277df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
1278df3e71e0SMarcello Maggioni 
1279df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
1280df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
1281df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
1282df3e71e0SMarcello Maggioni   if (SE)
1283df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
1284df3e71e0SMarcello Maggioni 
1285df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
1286df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
1287df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
1288df3e71e0SMarcello Maggioni 
1289df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1290df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
1291df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
1292df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
1293df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
1294df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
1295df3e71e0SMarcello Maggioni   // preheader -> header.
1296df3e71e0SMarcello Maggioni   //
1297df3e71e0SMarcello Maggioni   //
1298df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
1299df3e71e0SMarcello Maggioni   //        |                    |   |                   |
1300df3e71e0SMarcello Maggioni   //        V                    |   V                   |
1301df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
1302df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
1303df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
1304df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
1305df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
1306df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
1307df3e71e0SMarcello Maggioni   //
1308df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
1309df3e71e0SMarcello Maggioni   // update without using the batch update API.
1310df3e71e0SMarcello Maggioni   //
1311df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
1312df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
1313df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
1314df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
1315df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
1316df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
1317df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
1318df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
1319df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
1320df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
1321df3e71e0SMarcello Maggioni 
1322df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
1323df3e71e0SMarcello Maggioni   // instead of the exiting block.
1324c7fc81e6SBenjamin Kramer   for (PHINode &P : ExitBlock->phis()) {
1325df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
1326df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
1327df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
1328df3e71e0SMarcello Maggioni     int PredIndex = 0;
1329c7fc81e6SBenjamin Kramer     P.setIncomingBlock(PredIndex, Preheader);
1330df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
1331df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
1332df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
1333df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
1334df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
1335df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
1336df3e71e0SMarcello Maggioni     // being deleted).
1337c7fc81e6SBenjamin Kramer     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
1338c7fc81e6SBenjamin Kramer       P.removeIncomingValue(e - i, false);
1339df3e71e0SMarcello Maggioni 
1340c7fc81e6SBenjamin Kramer     assert((P.getNumIncomingValues() == 1 &&
1341c7fc81e6SBenjamin Kramer             P.getIncomingBlock(PredIndex) == Preheader) &&
1342df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
1343df3e71e0SMarcello Maggioni   }
1344df3e71e0SMarcello Maggioni 
1345df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
1346df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
1347df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
1348df3e71e0SMarcello Maggioni   // Remove the old branch.
1349df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
1350df3e71e0SMarcello Maggioni 
1351df3e71e0SMarcello Maggioni   if (DT) {
1352df3e71e0SMarcello Maggioni     // Update the dominator tree by informing it about the new edge from the
1353df3e71e0SMarcello Maggioni     // preheader to the exit.
1354df3e71e0SMarcello Maggioni     DT->insertEdge(Preheader, ExitBlock);
1355df3e71e0SMarcello Maggioni     // Inform the dominator tree about the removed edge.
1356df3e71e0SMarcello Maggioni     DT->deleteEdge(Preheader, L->getHeader());
1357df3e71e0SMarcello Maggioni   }
1358df3e71e0SMarcello Maggioni 
1359a757d65cSSerguei Katkov   // Given LCSSA form is satisfied, we should not have users of instructions
1360a757d65cSSerguei Katkov   // within the dead loop outside of the loop. However, LCSSA doesn't take
1361a757d65cSSerguei Katkov   // unreachable uses into account. We handle them here.
1362a757d65cSSerguei Katkov   // We could do it after drop all references (in this case all users in the
1363a757d65cSSerguei Katkov   // loop will be already eliminated and we have less work to do but according
1364a757d65cSSerguei Katkov   // to API doc of User::dropAllReferences only valid operation after dropping
1365a757d65cSSerguei Katkov   // references, is deletion. So let's substitute all usages of
1366a757d65cSSerguei Katkov   // instruction from the loop with undef value of corresponding type first.
1367a757d65cSSerguei Katkov   for (auto *Block : L->blocks())
1368a757d65cSSerguei Katkov     for (Instruction &I : *Block) {
1369a757d65cSSerguei Katkov       auto *Undef = UndefValue::get(I.getType());
1370a757d65cSSerguei Katkov       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
1371a757d65cSSerguei Katkov         Use &U = *UI;
1372a757d65cSSerguei Katkov         ++UI;
1373a757d65cSSerguei Katkov         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
1374a757d65cSSerguei Katkov           if (L->contains(Usr->getParent()))
1375a757d65cSSerguei Katkov             continue;
1376a757d65cSSerguei Katkov         // If we have a DT then we can check that uses outside a loop only in
1377a757d65cSSerguei Katkov         // unreachable block.
1378a757d65cSSerguei Katkov         if (DT)
1379a757d65cSSerguei Katkov           assert(!DT->isReachableFromEntry(U) &&
1380a757d65cSSerguei Katkov                  "Unexpected user in reachable block");
1381a757d65cSSerguei Katkov         U.set(Undef);
1382a757d65cSSerguei Katkov       }
1383a757d65cSSerguei Katkov     }
1384a757d65cSSerguei Katkov 
1385df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
1386df3e71e0SMarcello Maggioni   // delete it freely later.
1387df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
1388df3e71e0SMarcello Maggioni     Block->dropAllReferences();
1389df3e71e0SMarcello Maggioni 
1390df3e71e0SMarcello Maggioni   if (LI) {
1391df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
1392df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
1393df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
1394df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
1395df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
1396df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
1397df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
1398df3e71e0SMarcello Maggioni 
1399df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
1400df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
1401df3e71e0SMarcello Maggioni 
1402df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
1403df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
1404df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
1405df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
1406df3e71e0SMarcello Maggioni 
1407df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
1408df3e71e0SMarcello Maggioni     LI->erase(L);
1409df3e71e0SMarcello Maggioni   }
1410df3e71e0SMarcello Maggioni }
1411df3e71e0SMarcello Maggioni 
1412122f984aSEvgeniy Stepanov /// Returns true if the instruction in a loop is guaranteed to execute at least
1413122f984aSEvgeniy Stepanov /// once.
1414122f984aSEvgeniy Stepanov bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1415122f984aSEvgeniy Stepanov                                  const DominatorTree *DT, const Loop *CurLoop,
1416122f984aSEvgeniy Stepanov                                  const LoopSafetyInfo *SafetyInfo) {
1417122f984aSEvgeniy Stepanov   // We have to check to make sure that the instruction dominates all
141858ccc094SEvgeniy Stepanov   // of the exit blocks.  If it doesn't, then there is a path out of the loop
141958ccc094SEvgeniy Stepanov   // which does not execute this instruction, so we can't hoist it.
142058ccc094SEvgeniy Stepanov 
142158ccc094SEvgeniy Stepanov   // If the instruction is in the header block for the loop (which is very
142258ccc094SEvgeniy Stepanov   // common), it is always guaranteed to dominate the exit blocks.  Since this
142358ccc094SEvgeniy Stepanov   // is a common case, and can save some work, check it now.
142458ccc094SEvgeniy Stepanov   if (Inst.getParent() == CurLoop->getHeader())
142558ccc094SEvgeniy Stepanov     // If there's a throw in the header block, we can't guarantee we'll reach
142658ccc094SEvgeniy Stepanov     // Inst.
142758ccc094SEvgeniy Stepanov     return !SafetyInfo->HeaderMayThrow;
142858ccc094SEvgeniy Stepanov 
142958ccc094SEvgeniy Stepanov   // Somewhere in this loop there is an instruction which may throw and make us
143058ccc094SEvgeniy Stepanov   // exit the loop.
143158ccc094SEvgeniy Stepanov   if (SafetyInfo->MayThrow)
1432122f984aSEvgeniy Stepanov     return false;
1433122f984aSEvgeniy Stepanov 
1434122f984aSEvgeniy Stepanov   // Get the exit blocks for the current loop.
1435122f984aSEvgeniy Stepanov   SmallVector<BasicBlock *, 8> ExitBlocks;
1436122f984aSEvgeniy Stepanov   CurLoop->getExitBlocks(ExitBlocks);
1437122f984aSEvgeniy Stepanov 
1438122f984aSEvgeniy Stepanov   // Verify that the block dominates each of the exit blocks of the loop.
1439122f984aSEvgeniy Stepanov   for (BasicBlock *ExitBlock : ExitBlocks)
1440122f984aSEvgeniy Stepanov     if (!DT->dominates(Inst.getParent(), ExitBlock))
1441122f984aSEvgeniy Stepanov       return false;
1442122f984aSEvgeniy Stepanov 
1443122f984aSEvgeniy Stepanov   // As a degenerate case, if the loop is statically infinite then we haven't
1444122f984aSEvgeniy Stepanov   // proven anything since there are no exit blocks.
144558ccc094SEvgeniy Stepanov   if (ExitBlocks.empty())
1446122f984aSEvgeniy Stepanov     return false;
1447122f984aSEvgeniy Stepanov 
1448f1da33e4SEli Friedman   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1449f1da33e4SEli Friedman   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
1450f1da33e4SEli Friedman   // just a special case of this.)
1451122f984aSEvgeniy Stepanov   return true;
1452122f984aSEvgeniy Stepanov }
145341d72a86SDehao Chen 
145441d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
145541d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
145641d72a86SDehao Chen   if (!L->getExitingBlock())
145741d72a86SDehao Chen     return None;
145841d72a86SDehao Chen 
1459*d24ddcd6SHiroshi Inoue   // Get the branch weights for the loop's backedge.
146041d72a86SDehao Chen   BranchInst *LatchBR =
146141d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
146241d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
146341d72a86SDehao Chen     return None;
146441d72a86SDehao Chen 
146541d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
146641d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
146741d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
146841d72a86SDehao Chen 
146941d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
147041d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
147141d72a86SDehao Chen   // we exited the loop.
147241d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
1473b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
147441d72a86SDehao Chen     return None;
147541d72a86SDehao Chen 
1476b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
1477b151a641SMichael Kuperstein     return 0;
147841d72a86SDehao Chen 
1479b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
1480b151a641SMichael Kuperstein   // rounding to nearest.
148141d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
1482b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
148341d72a86SDehao Chen   else
1484b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
148541d72a86SDehao Chen }
1486cf9daa33SAmara Emerson 
1487cf9daa33SAmara Emerson /// \brief Adds a 'fast' flag to floating point operations.
1488cf9daa33SAmara Emerson static Value *addFastMathFlag(Value *V) {
1489cf9daa33SAmara Emerson   if (isa<FPMathOperator>(V)) {
1490cf9daa33SAmara Emerson     FastMathFlags Flags;
1491629c4115SSanjay Patel     Flags.setFast();
1492cf9daa33SAmara Emerson     cast<Instruction>(V)->setFastMathFlags(Flags);
1493cf9daa33SAmara Emerson   }
1494cf9daa33SAmara Emerson   return V;
1495cf9daa33SAmara Emerson }
1496cf9daa33SAmara Emerson 
1497cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
1498836b0f48SAmara Emerson Value *
1499836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1500836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1501836b0f48SAmara Emerson                           ArrayRef<Value *> RedOps) {
1502cf9daa33SAmara Emerson   unsigned VF = Src->getType()->getVectorNumElements();
1503cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1504cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
1505cf9daa33SAmara Emerson   // round.
1506cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
1507cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
1508cf9daa33SAmara Emerson   Value *TmpVec = Src;
1509cf9daa33SAmara Emerson   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1510cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
1511cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
1512cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
1513cf9daa33SAmara Emerson       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1514cf9daa33SAmara Emerson 
1515cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
1516cf9daa33SAmara Emerson     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1517cf9daa33SAmara Emerson               UndefValue::get(Builder.getInt32Ty()));
1518cf9daa33SAmara Emerson 
1519cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
1520cf9daa33SAmara Emerson         TmpVec, UndefValue::get(TmpVec->getType()),
1521cf9daa33SAmara Emerson         ConstantVector::get(ShuffleMask), "rdx.shuf");
1522cf9daa33SAmara Emerson 
1523cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1524cf9daa33SAmara Emerson       // Floating point operations had to be 'fast' to enable the reduction.
1525cf9daa33SAmara Emerson       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1526cf9daa33SAmara Emerson                                                    TmpVec, Shuf, "bin.rdx"));
1527cf9daa33SAmara Emerson     } else {
1528cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1529cf9daa33SAmara Emerson              "Invalid min/max");
1530cf9daa33SAmara Emerson       TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1531cf9daa33SAmara Emerson                                                     Shuf);
1532cf9daa33SAmara Emerson     }
1533cf9daa33SAmara Emerson     if (!RedOps.empty())
1534cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
1535cf9daa33SAmara Emerson   }
1536cf9daa33SAmara Emerson   // The result is in the first element of the vector.
1537cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1538cf9daa33SAmara Emerson }
1539cf9daa33SAmara Emerson 
1540cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
1541cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
1542cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
1543cf9daa33SAmara Emerson     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1544cf9daa33SAmara Emerson     Value *Src, TargetTransformInfo::ReductionFlags Flags,
1545cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
1546cf9daa33SAmara Emerson   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1547cf9daa33SAmara Emerson 
1548cf9daa33SAmara Emerson   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1549cf9daa33SAmara Emerson   std::function<Value*()> BuildFunc;
1550cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
1551cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1552cf9daa33SAmara Emerson   // TODO: Support creating ordered reductions.
15531ea7b6f7SSanjay Patel   FastMathFlags FMFFast;
15541ea7b6f7SSanjay Patel   FMFFast.setFast();
1555cf9daa33SAmara Emerson 
1556cf9daa33SAmara Emerson   switch (Opcode) {
1557cf9daa33SAmara Emerson   case Instruction::Add:
1558cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1559cf9daa33SAmara Emerson     break;
1560cf9daa33SAmara Emerson   case Instruction::Mul:
1561cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1562cf9daa33SAmara Emerson     break;
1563cf9daa33SAmara Emerson   case Instruction::And:
1564cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1565cf9daa33SAmara Emerson     break;
1566cf9daa33SAmara Emerson   case Instruction::Or:
1567cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1568cf9daa33SAmara Emerson     break;
1569cf9daa33SAmara Emerson   case Instruction::Xor:
1570cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1571cf9daa33SAmara Emerson     break;
1572cf9daa33SAmara Emerson   case Instruction::FAdd:
1573cf9daa33SAmara Emerson     BuildFunc = [&]() {
1574cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
15751ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1576cf9daa33SAmara Emerson       return Rdx;
1577cf9daa33SAmara Emerson     };
1578cf9daa33SAmara Emerson     break;
1579cf9daa33SAmara Emerson   case Instruction::FMul:
1580cf9daa33SAmara Emerson     BuildFunc = [&]() {
1581cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
15821ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1583cf9daa33SAmara Emerson       return Rdx;
1584cf9daa33SAmara Emerson     };
1585cf9daa33SAmara Emerson     break;
1586cf9daa33SAmara Emerson   case Instruction::ICmp:
1587cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1588cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1589cf9daa33SAmara Emerson       BuildFunc = [&]() {
1590cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1591cf9daa33SAmara Emerson       };
1592cf9daa33SAmara Emerson     } else {
1593cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1594cf9daa33SAmara Emerson       BuildFunc = [&]() {
1595cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1596cf9daa33SAmara Emerson       };
1597cf9daa33SAmara Emerson     }
1598cf9daa33SAmara Emerson     break;
1599cf9daa33SAmara Emerson   case Instruction::FCmp:
1600cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1601cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1602cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1603cf9daa33SAmara Emerson     } else {
1604cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1605cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1606cf9daa33SAmara Emerson     }
1607cf9daa33SAmara Emerson     break;
1608cf9daa33SAmara Emerson   default:
1609cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1610cf9daa33SAmara Emerson     break;
1611cf9daa33SAmara Emerson   }
1612cf9daa33SAmara Emerson   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1613cf9daa33SAmara Emerson     return BuildFunc();
1614cf9daa33SAmara Emerson   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1615cf9daa33SAmara Emerson }
1616cf9daa33SAmara Emerson 
1617cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
16183e069f57SSanjay Patel Value *llvm::createTargetReduction(IRBuilder<> &B,
1619cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1620cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1621cf9daa33SAmara Emerson                                    bool NoNaN) {
1622cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
16233e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
16243e069f57SSanjay Patel   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1625cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1626cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1627cf9daa33SAmara Emerson   switch (RecKind) {
16283e069f57SSanjay Patel   case RD::RK_FloatAdd:
16293e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
16303e069f57SSanjay Patel   case RD::RK_FloatMult:
16313e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
16323e069f57SSanjay Patel   case RD::RK_IntegerAdd:
16333e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
16343e069f57SSanjay Patel   case RD::RK_IntegerMult:
16353e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
16363e069f57SSanjay Patel   case RD::RK_IntegerAnd:
16373e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
16383e069f57SSanjay Patel   case RD::RK_IntegerOr:
16393e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
16403e069f57SSanjay Patel   case RD::RK_IntegerXor:
16413e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
16423e069f57SSanjay Patel   case RD::RK_IntegerMinMax: {
16433e069f57SSanjay Patel     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
16443e069f57SSanjay Patel     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
16453e069f57SSanjay Patel     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
16463e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1647cf9daa33SAmara Emerson   }
16483e069f57SSanjay Patel   case RD::RK_FloatMinMax: {
16493e069f57SSanjay Patel     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
16503e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1651cf9daa33SAmara Emerson   }
1652cf9daa33SAmara Emerson   default:
1653cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
1654cf9daa33SAmara Emerson   }
1655cf9daa33SAmara Emerson }
1656cf9daa33SAmara Emerson 
1657a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1658a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1659a61f4b89SDinar Temirbulatov   if (!VecOp)
1660a61f4b89SDinar Temirbulatov     return;
1661a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1662a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1663a61f4b89SDinar Temirbulatov   if (!Intersection)
1664a61f4b89SDinar Temirbulatov     return;
1665a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1666a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1667a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1668a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1669a61f4b89SDinar Temirbulatov     if (!Instr)
1670a61f4b89SDinar Temirbulatov       continue;
1671a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1672a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1673cf9daa33SAmara Emerson   }
1674cf9daa33SAmara Emerson }
1675