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"
26*a097bc69SChad Rosier #include "llvm/Analysis/ValueTracking.h"
2731088a9dSChandler Carruth #include "llvm/IR/Dominators.h"
2876aa662cSKarthik Bhat #include "llvm/IR/Instructions.h"
2945d4cb9aSWeiming Zhao #include "llvm/IR/Module.h"
3076aa662cSKarthik Bhat #include "llvm/IR/PatternMatch.h"
3176aa662cSKarthik Bhat #include "llvm/IR/ValueHandle.h"
3231088a9dSChandler Carruth #include "llvm/Pass.h"
3376aa662cSKarthik Bhat #include "llvm/Support/Debug.h"
34*a097bc69SChad Rosier #include "llvm/Support/KnownBits.h"
354a000883SChandler Carruth #include "llvm/Transforms/Utils/BasicBlockUtils.h"
3676aa662cSKarthik Bhat 
3776aa662cSKarthik Bhat using namespace llvm;
3876aa662cSKarthik Bhat using namespace llvm::PatternMatch;
3976aa662cSKarthik Bhat 
4076aa662cSKarthik Bhat #define DEBUG_TYPE "loop-utils"
4176aa662cSKarthik Bhat 
420a91310cSTyler Nowicki bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
4376aa662cSKarthik Bhat                                         SmallPtrSetImpl<Instruction *> &Set) {
4476aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
4576aa662cSKarthik Bhat     if (!Set.count(dyn_cast<Instruction>(*Use)))
4676aa662cSKarthik Bhat       return false;
4776aa662cSKarthik Bhat   return true;
4876aa662cSKarthik Bhat }
4976aa662cSKarthik Bhat 
50c94f8e29SChad Rosier bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurrenceKind Kind) {
51c94f8e29SChad Rosier   switch (Kind) {
52c94f8e29SChad Rosier   default:
53c94f8e29SChad Rosier     break;
54c94f8e29SChad Rosier   case RK_IntegerAdd:
55c94f8e29SChad Rosier   case RK_IntegerMult:
56c94f8e29SChad Rosier   case RK_IntegerOr:
57c94f8e29SChad Rosier   case RK_IntegerAnd:
58c94f8e29SChad Rosier   case RK_IntegerXor:
59c94f8e29SChad Rosier   case RK_IntegerMinMax:
60c94f8e29SChad Rosier     return true;
61c94f8e29SChad Rosier   }
62c94f8e29SChad Rosier   return false;
63c94f8e29SChad Rosier }
64c94f8e29SChad Rosier 
65c94f8e29SChad Rosier bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurrenceKind Kind) {
66c94f8e29SChad Rosier   return (Kind != RK_NoRecurrence) && !isIntegerRecurrenceKind(Kind);
67c94f8e29SChad Rosier }
68c94f8e29SChad Rosier 
69c94f8e29SChad Rosier bool RecurrenceDescriptor::isArithmeticRecurrenceKind(RecurrenceKind Kind) {
70c94f8e29SChad Rosier   switch (Kind) {
71c94f8e29SChad Rosier   default:
72c94f8e29SChad Rosier     break;
73c94f8e29SChad Rosier   case RK_IntegerAdd:
74c94f8e29SChad Rosier   case RK_IntegerMult:
75c94f8e29SChad Rosier   case RK_FloatAdd:
76c94f8e29SChad Rosier   case RK_FloatMult:
77c94f8e29SChad Rosier     return true;
78c94f8e29SChad Rosier   }
79c94f8e29SChad Rosier   return false;
80c94f8e29SChad Rosier }
81c94f8e29SChad Rosier 
82*a097bc69SChad Rosier /// Determines if Phi may have been type-promoted. If Phi has a single user
83*a097bc69SChad Rosier /// that ANDs the Phi with a type mask, return the user. RT is updated to
84*a097bc69SChad Rosier /// account for the narrower bit width represented by the mask, and the AND
85*a097bc69SChad Rosier /// instruction is added to CI.
86*a097bc69SChad Rosier static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
87c94f8e29SChad Rosier                                    SmallPtrSetImpl<Instruction *> &Visited,
88c94f8e29SChad Rosier                                    SmallPtrSetImpl<Instruction *> &CI) {
89c94f8e29SChad Rosier   if (!Phi->hasOneUse())
90c94f8e29SChad Rosier     return Phi;
91c94f8e29SChad Rosier 
92c94f8e29SChad Rosier   const APInt *M = nullptr;
93c94f8e29SChad Rosier   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
94c94f8e29SChad Rosier 
95c94f8e29SChad Rosier   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
96c94f8e29SChad Rosier   // with a new integer type of the corresponding bit width.
9772ee6945SCraig Topper   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
98c94f8e29SChad Rosier     int32_t Bits = (*M + 1).exactLogBase2();
99c94f8e29SChad Rosier     if (Bits > 0) {
100c94f8e29SChad Rosier       RT = IntegerType::get(Phi->getContext(), Bits);
101c94f8e29SChad Rosier       Visited.insert(Phi);
102c94f8e29SChad Rosier       CI.insert(J);
103c94f8e29SChad Rosier       return J;
104c94f8e29SChad Rosier     }
105c94f8e29SChad Rosier   }
106c94f8e29SChad Rosier   return Phi;
107c94f8e29SChad Rosier }
108c94f8e29SChad Rosier 
109*a097bc69SChad Rosier /// Compute the minimal bit width needed to represent a reduction whose exit
110*a097bc69SChad Rosier /// instruction is given by Exit.
111*a097bc69SChad Rosier static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
112*a097bc69SChad Rosier                                                      DemandedBits *DB,
113*a097bc69SChad Rosier                                                      AssumptionCache *AC,
114*a097bc69SChad Rosier                                                      DominatorTree *DT) {
115*a097bc69SChad Rosier   bool IsSigned = false;
116*a097bc69SChad Rosier   const DataLayout &DL = Exit->getModule()->getDataLayout();
117*a097bc69SChad Rosier   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
118*a097bc69SChad Rosier 
119*a097bc69SChad Rosier   if (DB) {
120*a097bc69SChad Rosier     // Use the demanded bits analysis to determine the bits that are live out
121*a097bc69SChad Rosier     // of the exit instruction, rounding up to the nearest power of two. If the
122*a097bc69SChad Rosier     // use of demanded bits results in a smaller bit width, we know the value
123*a097bc69SChad Rosier     // must be positive (i.e., IsSigned = false), because if this were not the
124*a097bc69SChad Rosier     // case, the sign bit would have been demanded.
125*a097bc69SChad Rosier     auto Mask = DB->getDemandedBits(Exit);
126*a097bc69SChad Rosier     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
127*a097bc69SChad Rosier   }
128*a097bc69SChad Rosier 
129*a097bc69SChad Rosier   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
130*a097bc69SChad Rosier     // If demanded bits wasn't able to limit the bit width, we can try to use
131*a097bc69SChad Rosier     // value tracking instead. This can be the case, for example, if the value
132*a097bc69SChad Rosier     // may be negative.
133*a097bc69SChad Rosier     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
134*a097bc69SChad Rosier     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
135*a097bc69SChad Rosier     MaxBitWidth = NumTypeBits - NumSignBits;
136*a097bc69SChad Rosier     KnownBits Bits = computeKnownBits(Exit, DL);
137*a097bc69SChad Rosier     if (!Bits.isNonNegative()) {
138*a097bc69SChad Rosier       // If the value is not known to be non-negative, we set IsSigned to true,
139*a097bc69SChad Rosier       // meaning that we will use sext instructions instead of zext
140*a097bc69SChad Rosier       // instructions to restore the original type.
141*a097bc69SChad Rosier       IsSigned = true;
142*a097bc69SChad Rosier       if (!Bits.isNegative())
143*a097bc69SChad Rosier         // If the value is not known to be negative, we don't known what the
144*a097bc69SChad Rosier         // upper bit is, and therefore, we don't know what kind of extend we
145*a097bc69SChad Rosier         // will need. In this case, just increase the bit width by one bit and
146*a097bc69SChad Rosier         // use sext.
147*a097bc69SChad Rosier         ++MaxBitWidth;
148*a097bc69SChad Rosier     }
149*a097bc69SChad Rosier   }
150*a097bc69SChad Rosier   if (!isPowerOf2_64(MaxBitWidth))
151*a097bc69SChad Rosier     MaxBitWidth = NextPowerOf2(MaxBitWidth);
152*a097bc69SChad Rosier 
153*a097bc69SChad Rosier   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
154*a097bc69SChad Rosier                         IsSigned);
155*a097bc69SChad Rosier }
156*a097bc69SChad Rosier 
157*a097bc69SChad Rosier /// Collect cast instructions that can be ignored in the vectorizer's cost
158*a097bc69SChad Rosier /// model, given a reduction exit value and the minimal type in which the
159*a097bc69SChad Rosier /// reduction can be represented.
160*a097bc69SChad Rosier static void collectCastsToIgnore(Loop *TheLoop, Instruction *Exit,
161*a097bc69SChad Rosier                                  Type *RecurrenceType,
162*a097bc69SChad Rosier                                  SmallPtrSetImpl<Instruction *> &Casts) {
163c94f8e29SChad Rosier 
164c94f8e29SChad Rosier   SmallVector<Instruction *, 8> Worklist;
165*a097bc69SChad Rosier   SmallPtrSet<Instruction *, 8> Visited;
166c94f8e29SChad Rosier   Worklist.push_back(Exit);
167c94f8e29SChad Rosier 
168c94f8e29SChad Rosier   while (!Worklist.empty()) {
169*a097bc69SChad Rosier     Instruction *Val = Worklist.pop_back_val();
170*a097bc69SChad Rosier     Visited.insert(Val);
171*a097bc69SChad Rosier     if (auto *Cast = dyn_cast<CastInst>(Val))
172*a097bc69SChad Rosier       if (Cast->getSrcTy() == RecurrenceType) {
173*a097bc69SChad Rosier         // If the source type of a cast instruction is equal to the recurrence
174*a097bc69SChad Rosier         // type, it will be eliminated, and should be ignored in the vectorizer
17529dc0f70SMatthew Simpson         // cost model.
176*a097bc69SChad Rosier         Casts.insert(Cast);
177*a097bc69SChad Rosier         continue;
178c94f8e29SChad Rosier       }
179*a097bc69SChad Rosier 
180*a097bc69SChad Rosier     // Add all operands to the work list if they are loop-varying values that
181*a097bc69SChad Rosier     // we haven't yet visited.
182*a097bc69SChad Rosier     for (Value *O : cast<User>(Val)->operands())
183*a097bc69SChad Rosier       if (auto *I = dyn_cast<Instruction>(O))
184*a097bc69SChad Rosier         if (TheLoop->contains(I) && !Visited.count(I))
185*a097bc69SChad Rosier           Worklist.push_back(I);
186c94f8e29SChad Rosier   }
187c94f8e29SChad Rosier }
188c94f8e29SChad Rosier 
1890a91310cSTyler Nowicki bool RecurrenceDescriptor::AddReductionVar(PHINode *Phi, RecurrenceKind Kind,
19076aa662cSKarthik Bhat                                            Loop *TheLoop, bool HasFunNoNaNAttr,
191*a097bc69SChad Rosier                                            RecurrenceDescriptor &RedDes,
192*a097bc69SChad Rosier                                            DemandedBits *DB,
193*a097bc69SChad Rosier                                            AssumptionCache *AC,
194*a097bc69SChad Rosier                                            DominatorTree *DT) {
19576aa662cSKarthik Bhat   if (Phi->getNumIncomingValues() != 2)
19676aa662cSKarthik Bhat     return false;
19776aa662cSKarthik Bhat 
19876aa662cSKarthik Bhat   // Reduction variables are only found in the loop header block.
19976aa662cSKarthik Bhat   if (Phi->getParent() != TheLoop->getHeader())
20076aa662cSKarthik Bhat     return false;
20176aa662cSKarthik Bhat 
20276aa662cSKarthik Bhat   // Obtain the reduction start value from the value that comes from the loop
20376aa662cSKarthik Bhat   // preheader.
20476aa662cSKarthik Bhat   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
20576aa662cSKarthik Bhat 
20676aa662cSKarthik Bhat   // ExitInstruction is the single value which is used outside the loop.
20776aa662cSKarthik Bhat   // We only allow for a single reduction value to be used outside the loop.
20876aa662cSKarthik Bhat   // This includes users of the reduction, variables (which form a cycle
20976aa662cSKarthik Bhat   // which ends in the phi node).
21076aa662cSKarthik Bhat   Instruction *ExitInstruction = nullptr;
21176aa662cSKarthik Bhat   // Indicates that we found a reduction operation in our scan.
21276aa662cSKarthik Bhat   bool FoundReduxOp = false;
21376aa662cSKarthik Bhat 
21476aa662cSKarthik Bhat   // We start with the PHI node and scan for all of the users of this
21576aa662cSKarthik Bhat   // instruction. All users must be instructions that can be used as reduction
21676aa662cSKarthik Bhat   // variables (such as ADD). We must have a single out-of-block user. The cycle
21776aa662cSKarthik Bhat   // must include the original PHI.
21876aa662cSKarthik Bhat   bool FoundStartPHI = false;
21976aa662cSKarthik Bhat 
22076aa662cSKarthik Bhat   // To recognize min/max patterns formed by a icmp select sequence, we store
22176aa662cSKarthik Bhat   // the number of instruction we saw from the recognized min/max pattern,
22276aa662cSKarthik Bhat   //  to make sure we only see exactly the two instructions.
22376aa662cSKarthik Bhat   unsigned NumCmpSelectPatternInst = 0;
22427b2c39eSTyler Nowicki   InstDesc ReduxDesc(false, nullptr);
22576aa662cSKarthik Bhat 
226c94f8e29SChad Rosier   // Data used for determining if the recurrence has been type-promoted.
227c94f8e29SChad Rosier   Type *RecurrenceType = Phi->getType();
228c94f8e29SChad Rosier   SmallPtrSet<Instruction *, 4> CastInsts;
229c94f8e29SChad Rosier   Instruction *Start = Phi;
230c94f8e29SChad Rosier   bool IsSigned = false;
231c94f8e29SChad Rosier 
23276aa662cSKarthik Bhat   SmallPtrSet<Instruction *, 8> VisitedInsts;
23376aa662cSKarthik Bhat   SmallVector<Instruction *, 8> Worklist;
234c94f8e29SChad Rosier 
235c94f8e29SChad Rosier   // Return early if the recurrence kind does not match the type of Phi. If the
236c94f8e29SChad Rosier   // recurrence kind is arithmetic, we attempt to look through AND operations
237c94f8e29SChad Rosier   // resulting from the type promotion performed by InstCombine.  Vector
238c94f8e29SChad Rosier   // operations are not limited to the legal integer widths, so we may be able
239c94f8e29SChad Rosier   // to evaluate the reduction in the narrower width.
240c94f8e29SChad Rosier   if (RecurrenceType->isFloatingPointTy()) {
241c94f8e29SChad Rosier     if (!isFloatingPointRecurrenceKind(Kind))
242c94f8e29SChad Rosier       return false;
243c94f8e29SChad Rosier   } else {
244c94f8e29SChad Rosier     if (!isIntegerRecurrenceKind(Kind))
245c94f8e29SChad Rosier       return false;
246c94f8e29SChad Rosier     if (isArithmeticRecurrenceKind(Kind))
247c94f8e29SChad Rosier       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
248c94f8e29SChad Rosier   }
249c94f8e29SChad Rosier 
250c94f8e29SChad Rosier   Worklist.push_back(Start);
251c94f8e29SChad Rosier   VisitedInsts.insert(Start);
25276aa662cSKarthik Bhat 
25376aa662cSKarthik Bhat   // A value in the reduction can be used:
25476aa662cSKarthik Bhat   //  - By the reduction:
25576aa662cSKarthik Bhat   //      - Reduction operation:
25676aa662cSKarthik Bhat   //        - One use of reduction value (safe).
25776aa662cSKarthik Bhat   //        - Multiple use of reduction value (not safe).
25876aa662cSKarthik Bhat   //      - PHI:
25976aa662cSKarthik Bhat   //        - All uses of the PHI must be the reduction (safe).
26076aa662cSKarthik Bhat   //        - Otherwise, not safe.
2617cefb409SMichael Kuperstein   //  - By instructions outside of the loop (safe).
2627cefb409SMichael Kuperstein   //      * One value may have several outside users, but all outside
2637cefb409SMichael Kuperstein   //        uses must be of the same value.
26476aa662cSKarthik Bhat   //  - By an instruction that is not part of the reduction (not safe).
26576aa662cSKarthik Bhat   //    This is either:
26676aa662cSKarthik Bhat   //      * An instruction type other than PHI or the reduction operation.
26776aa662cSKarthik Bhat   //      * A PHI in the header other than the initial PHI.
26876aa662cSKarthik Bhat   while (!Worklist.empty()) {
26976aa662cSKarthik Bhat     Instruction *Cur = Worklist.back();
27076aa662cSKarthik Bhat     Worklist.pop_back();
27176aa662cSKarthik Bhat 
27276aa662cSKarthik Bhat     // No Users.
27376aa662cSKarthik Bhat     // If the instruction has no users then this is a broken chain and can't be
27476aa662cSKarthik Bhat     // a reduction variable.
27576aa662cSKarthik Bhat     if (Cur->use_empty())
27676aa662cSKarthik Bhat       return false;
27776aa662cSKarthik Bhat 
27876aa662cSKarthik Bhat     bool IsAPhi = isa<PHINode>(Cur);
27976aa662cSKarthik Bhat 
28076aa662cSKarthik Bhat     // A header PHI use other than the original PHI.
28176aa662cSKarthik Bhat     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
28276aa662cSKarthik Bhat       return false;
28376aa662cSKarthik Bhat 
28476aa662cSKarthik Bhat     // Reductions of instructions such as Div, and Sub is only possible if the
28576aa662cSKarthik Bhat     // LHS is the reduction variable.
28676aa662cSKarthik Bhat     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
28776aa662cSKarthik Bhat         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
28876aa662cSKarthik Bhat         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
28976aa662cSKarthik Bhat       return false;
29076aa662cSKarthik Bhat 
291c94f8e29SChad Rosier     // Any reduction instruction must be of one of the allowed kinds. We ignore
292c94f8e29SChad Rosier     // the starting value (the Phi or an AND instruction if the Phi has been
293c94f8e29SChad Rosier     // type-promoted).
294c94f8e29SChad Rosier     if (Cur != Start) {
2950a91310cSTyler Nowicki       ReduxDesc = isRecurrenceInstr(Cur, Kind, ReduxDesc, HasFunNoNaNAttr);
2960a91310cSTyler Nowicki       if (!ReduxDesc.isRecurrence())
29776aa662cSKarthik Bhat         return false;
298c94f8e29SChad Rosier     }
29976aa662cSKarthik Bhat 
30076aa662cSKarthik Bhat     // A reduction operation must only have one use of the reduction value.
30176aa662cSKarthik Bhat     if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
30276aa662cSKarthik Bhat         hasMultipleUsesOf(Cur, VisitedInsts))
30376aa662cSKarthik Bhat       return false;
30476aa662cSKarthik Bhat 
30576aa662cSKarthik Bhat     // All inputs to a PHI node must be a reduction value.
30676aa662cSKarthik Bhat     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
30776aa662cSKarthik Bhat       return false;
30876aa662cSKarthik Bhat 
30976aa662cSKarthik Bhat     if (Kind == RK_IntegerMinMax &&
31076aa662cSKarthik Bhat         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
31176aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
31276aa662cSKarthik Bhat     if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
31376aa662cSKarthik Bhat       ++NumCmpSelectPatternInst;
31476aa662cSKarthik Bhat 
31576aa662cSKarthik Bhat     // Check  whether we found a reduction operator.
316c94f8e29SChad Rosier     FoundReduxOp |= !IsAPhi && Cur != Start;
31776aa662cSKarthik Bhat 
31876aa662cSKarthik Bhat     // Process users of current instruction. Push non-PHI nodes after PHI nodes
31976aa662cSKarthik Bhat     // onto the stack. This way we are going to have seen all inputs to PHI
32076aa662cSKarthik Bhat     // nodes once we get to them.
32176aa662cSKarthik Bhat     SmallVector<Instruction *, 8> NonPHIs;
32276aa662cSKarthik Bhat     SmallVector<Instruction *, 8> PHIs;
32376aa662cSKarthik Bhat     for (User *U : Cur->users()) {
32476aa662cSKarthik Bhat       Instruction *UI = cast<Instruction>(U);
32576aa662cSKarthik Bhat 
32676aa662cSKarthik Bhat       // Check if we found the exit user.
32776aa662cSKarthik Bhat       BasicBlock *Parent = UI->getParent();
32876aa662cSKarthik Bhat       if (!TheLoop->contains(Parent)) {
3297cefb409SMichael Kuperstein         // If we already know this instruction is used externally, move on to
3307cefb409SMichael Kuperstein         // the next user.
3317cefb409SMichael Kuperstein         if (ExitInstruction == Cur)
3327cefb409SMichael Kuperstein           continue;
3337cefb409SMichael Kuperstein 
3347cefb409SMichael Kuperstein         // Exit if you find multiple values used outside or if the header phi
3357cefb409SMichael Kuperstein         // node is being used. In this case the user uses the value of the
3367cefb409SMichael Kuperstein         // previous iteration, in which case we would loose "VF-1" iterations of
3377cefb409SMichael Kuperstein         // the reduction operation if we vectorize.
33876aa662cSKarthik Bhat         if (ExitInstruction != nullptr || Cur == Phi)
33976aa662cSKarthik Bhat           return false;
34076aa662cSKarthik Bhat 
34176aa662cSKarthik Bhat         // The instruction used by an outside user must be the last instruction
34276aa662cSKarthik Bhat         // before we feed back to the reduction phi. Otherwise, we loose VF-1
34376aa662cSKarthik Bhat         // operations on the value.
34442531260SDavid Majnemer         if (!is_contained(Phi->operands(), Cur))
34576aa662cSKarthik Bhat           return false;
34676aa662cSKarthik Bhat 
34776aa662cSKarthik Bhat         ExitInstruction = Cur;
34876aa662cSKarthik Bhat         continue;
34976aa662cSKarthik Bhat       }
35076aa662cSKarthik Bhat 
35176aa662cSKarthik Bhat       // Process instructions only once (termination). Each reduction cycle
35276aa662cSKarthik Bhat       // value must only be used once, except by phi nodes and min/max
35376aa662cSKarthik Bhat       // reductions which are represented as a cmp followed by a select.
35427b2c39eSTyler Nowicki       InstDesc IgnoredVal(false, nullptr);
35576aa662cSKarthik Bhat       if (VisitedInsts.insert(UI).second) {
35676aa662cSKarthik Bhat         if (isa<PHINode>(UI))
35776aa662cSKarthik Bhat           PHIs.push_back(UI);
35876aa662cSKarthik Bhat         else
35976aa662cSKarthik Bhat           NonPHIs.push_back(UI);
36076aa662cSKarthik Bhat       } else if (!isa<PHINode>(UI) &&
36176aa662cSKarthik Bhat                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
36276aa662cSKarthik Bhat                    !isa<SelectInst>(UI)) ||
3630a91310cSTyler Nowicki                   !isMinMaxSelectCmpPattern(UI, IgnoredVal).isRecurrence()))
36476aa662cSKarthik Bhat         return false;
36576aa662cSKarthik Bhat 
36676aa662cSKarthik Bhat       // Remember that we completed the cycle.
36776aa662cSKarthik Bhat       if (UI == Phi)
36876aa662cSKarthik Bhat         FoundStartPHI = true;
36976aa662cSKarthik Bhat     }
37076aa662cSKarthik Bhat     Worklist.append(PHIs.begin(), PHIs.end());
37176aa662cSKarthik Bhat     Worklist.append(NonPHIs.begin(), NonPHIs.end());
37276aa662cSKarthik Bhat   }
37376aa662cSKarthik Bhat 
37476aa662cSKarthik Bhat   // This means we have seen one but not the other instruction of the
37576aa662cSKarthik Bhat   // pattern or more than just a select and cmp.
37676aa662cSKarthik Bhat   if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
37776aa662cSKarthik Bhat       NumCmpSelectPatternInst != 2)
37876aa662cSKarthik Bhat     return false;
37976aa662cSKarthik Bhat 
38076aa662cSKarthik Bhat   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
38176aa662cSKarthik Bhat     return false;
38276aa662cSKarthik Bhat 
383*a097bc69SChad Rosier   if (Start != Phi) {
384*a097bc69SChad Rosier     // If the starting value is not the same as the phi node, we speculatively
385*a097bc69SChad Rosier     // looked through an 'and' instruction when evaluating a potential
386*a097bc69SChad Rosier     // arithmetic reduction to determine if it may have been type-promoted.
387*a097bc69SChad Rosier     //
388*a097bc69SChad Rosier     // We now compute the minimal bit width that is required to represent the
389*a097bc69SChad Rosier     // reduction. If this is the same width that was indicated by the 'and', we
390*a097bc69SChad Rosier     // can represent the reduction in the smaller type. The 'and' instruction
391*a097bc69SChad Rosier     // will be eliminated since it will essentially be a cast instruction that
392*a097bc69SChad Rosier     // can be ignore in the cost model. If we compute a different type than we
393*a097bc69SChad Rosier     // did when evaluating the 'and', the 'and' will not be eliminated, and we
394*a097bc69SChad Rosier     // will end up with different kinds of operations in the recurrence
395*a097bc69SChad Rosier     // expression (e.g., RK_IntegerAND, RK_IntegerADD). We give up if this is
396*a097bc69SChad Rosier     // the case.
397*a097bc69SChad Rosier     //
398*a097bc69SChad Rosier     // The vectorizer relies on InstCombine to perform the actual
399*a097bc69SChad Rosier     // type-shrinking. It does this by inserting instructions to truncate the
400*a097bc69SChad Rosier     // exit value of the reduction to the width indicated by RecurrenceType and
401*a097bc69SChad Rosier     // then extend this value back to the original width. If IsSigned is false,
402*a097bc69SChad Rosier     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
403*a097bc69SChad Rosier     // used.
404*a097bc69SChad Rosier     //
405*a097bc69SChad Rosier     // TODO: We should not rely on InstCombine to rewrite the reduction in the
406*a097bc69SChad Rosier     //       smaller type. We should just generate a correctly typed expression
407*a097bc69SChad Rosier     //       to begin with.
408*a097bc69SChad Rosier     Type *ComputedType;
409*a097bc69SChad Rosier     std::tie(ComputedType, IsSigned) =
410*a097bc69SChad Rosier         computeRecurrenceType(ExitInstruction, DB, AC, DT);
411*a097bc69SChad Rosier     if (ComputedType != RecurrenceType)
412c94f8e29SChad Rosier       return false;
413c94f8e29SChad Rosier 
414*a097bc69SChad Rosier     // The recurrence expression will be represented in a narrower type. If
415*a097bc69SChad Rosier     // there are any cast instructions that will be unnecessary, collect them
416*a097bc69SChad Rosier     // in CastInsts. Note that the 'and' instruction was already included in
417*a097bc69SChad Rosier     // this list.
418*a097bc69SChad Rosier     //
419*a097bc69SChad Rosier     // TODO: A better way to represent this may be to tag in some way all the
420*a097bc69SChad Rosier     //       instructions that are a part of the reduction. The vectorizer cost
421*a097bc69SChad Rosier     //       model could then apply the recurrence type to these instructions,
422*a097bc69SChad Rosier     //       without needing a white list of instructions to ignore.
423*a097bc69SChad Rosier     collectCastsToIgnore(TheLoop, ExitInstruction, RecurrenceType, CastInsts);
424*a097bc69SChad Rosier   }
425*a097bc69SChad Rosier 
42676aa662cSKarthik Bhat   // We found a reduction var if we have reached the original phi node and we
42776aa662cSKarthik Bhat   // only have a single instruction with out-of-loop users.
42876aa662cSKarthik Bhat 
42976aa662cSKarthik Bhat   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
4300a91310cSTyler Nowicki   // is saved as part of the RecurrenceDescriptor.
43176aa662cSKarthik Bhat 
43276aa662cSKarthik Bhat   // Save the description of this reduction variable.
433c94f8e29SChad Rosier   RecurrenceDescriptor RD(
434c94f8e29SChad Rosier       RdxStart, ExitInstruction, Kind, ReduxDesc.getMinMaxKind(),
435c94f8e29SChad Rosier       ReduxDesc.getUnsafeAlgebraInst(), RecurrenceType, IsSigned, CastInsts);
43676aa662cSKarthik Bhat   RedDes = RD;
43776aa662cSKarthik Bhat 
43876aa662cSKarthik Bhat   return true;
43976aa662cSKarthik Bhat }
44076aa662cSKarthik Bhat 
44176aa662cSKarthik Bhat /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
44276aa662cSKarthik Bhat /// pattern corresponding to a min(X, Y) or max(X, Y).
44327b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
44427b2c39eSTyler Nowicki RecurrenceDescriptor::isMinMaxSelectCmpPattern(Instruction *I, InstDesc &Prev) {
44576aa662cSKarthik Bhat 
44676aa662cSKarthik Bhat   assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
44776aa662cSKarthik Bhat          "Expect a select instruction");
44876aa662cSKarthik Bhat   Instruction *Cmp = nullptr;
44976aa662cSKarthik Bhat   SelectInst *Select = nullptr;
45076aa662cSKarthik Bhat 
45176aa662cSKarthik Bhat   // We must handle the select(cmp()) as a single instruction. Advance to the
45276aa662cSKarthik Bhat   // select.
45376aa662cSKarthik Bhat   if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
45476aa662cSKarthik Bhat     if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->user_begin())))
45527b2c39eSTyler Nowicki       return InstDesc(false, I);
45627b2c39eSTyler Nowicki     return InstDesc(Select, Prev.getMinMaxKind());
45776aa662cSKarthik Bhat   }
45876aa662cSKarthik Bhat 
45976aa662cSKarthik Bhat   // Only handle single use cases for now.
46076aa662cSKarthik Bhat   if (!(Select = dyn_cast<SelectInst>(I)))
46127b2c39eSTyler Nowicki     return InstDesc(false, I);
46276aa662cSKarthik Bhat   if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
46376aa662cSKarthik Bhat       !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
46427b2c39eSTyler Nowicki     return InstDesc(false, I);
46576aa662cSKarthik Bhat   if (!Cmp->hasOneUse())
46627b2c39eSTyler Nowicki     return InstDesc(false, I);
46776aa662cSKarthik Bhat 
46876aa662cSKarthik Bhat   Value *CmpLeft;
46976aa662cSKarthik Bhat   Value *CmpRight;
47076aa662cSKarthik Bhat 
47176aa662cSKarthik Bhat   // Look for a min/max pattern.
47276aa662cSKarthik Bhat   if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMin);
47476aa662cSKarthik Bhat   else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_UIntMax);
47676aa662cSKarthik Bhat   else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMax);
47876aa662cSKarthik Bhat   else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
47927b2c39eSTyler Nowicki     return InstDesc(Select, MRK_SIntMin);
48076aa662cSKarthik Bhat   else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48127b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
48276aa662cSKarthik Bhat   else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48327b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
48476aa662cSKarthik Bhat   else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48527b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMin);
48676aa662cSKarthik Bhat   else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
48727b2c39eSTyler Nowicki     return InstDesc(Select, MRK_FloatMax);
48876aa662cSKarthik Bhat 
48927b2c39eSTyler Nowicki   return InstDesc(false, I);
49076aa662cSKarthik Bhat }
49176aa662cSKarthik Bhat 
49227b2c39eSTyler Nowicki RecurrenceDescriptor::InstDesc
4930a91310cSTyler Nowicki RecurrenceDescriptor::isRecurrenceInstr(Instruction *I, RecurrenceKind Kind,
49427b2c39eSTyler Nowicki                                         InstDesc &Prev, bool HasFunNoNaNAttr) {
49576aa662cSKarthik Bhat   bool FP = I->getType()->isFloatingPointTy();
496c1a86f58STyler Nowicki   Instruction *UAI = Prev.getUnsafeAlgebraInst();
497629c4115SSanjay Patel   if (!UAI && FP && !I->isFast())
498c1a86f58STyler Nowicki     UAI = I; // Found an unsafe (unvectorizable) algebra instruction.
499c1a86f58STyler Nowicki 
50076aa662cSKarthik Bhat   switch (I->getOpcode()) {
50176aa662cSKarthik Bhat   default:
50227b2c39eSTyler Nowicki     return InstDesc(false, I);
50376aa662cSKarthik Bhat   case Instruction::PHI:
50410a1e8b1STim Northover     return InstDesc(I, Prev.getMinMaxKind(), Prev.getUnsafeAlgebraInst());
50576aa662cSKarthik Bhat   case Instruction::Sub:
50676aa662cSKarthik Bhat   case Instruction::Add:
50727b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAdd, I);
50876aa662cSKarthik Bhat   case Instruction::Mul:
50927b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerMult, I);
51076aa662cSKarthik Bhat   case Instruction::And:
51127b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerAnd, I);
51276aa662cSKarthik Bhat   case Instruction::Or:
51327b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerOr, I);
51476aa662cSKarthik Bhat   case Instruction::Xor:
51527b2c39eSTyler Nowicki     return InstDesc(Kind == RK_IntegerXor, I);
51676aa662cSKarthik Bhat   case Instruction::FMul:
517c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatMult, I, UAI);
51876aa662cSKarthik Bhat   case Instruction::FSub:
51976aa662cSKarthik Bhat   case Instruction::FAdd:
520c1a86f58STyler Nowicki     return InstDesc(Kind == RK_FloatAdd, I, UAI);
52176aa662cSKarthik Bhat   case Instruction::FCmp:
52276aa662cSKarthik Bhat   case Instruction::ICmp:
52376aa662cSKarthik Bhat   case Instruction::Select:
52476aa662cSKarthik Bhat     if (Kind != RK_IntegerMinMax &&
52576aa662cSKarthik Bhat         (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
52627b2c39eSTyler Nowicki       return InstDesc(false, I);
52776aa662cSKarthik Bhat     return isMinMaxSelectCmpPattern(I, Prev);
52876aa662cSKarthik Bhat   }
52976aa662cSKarthik Bhat }
53076aa662cSKarthik Bhat 
5310a91310cSTyler Nowicki bool RecurrenceDescriptor::hasMultipleUsesOf(
53276aa662cSKarthik Bhat     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts) {
53376aa662cSKarthik Bhat   unsigned NumUses = 0;
53476aa662cSKarthik Bhat   for (User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E;
53576aa662cSKarthik Bhat        ++Use) {
53676aa662cSKarthik Bhat     if (Insts.count(dyn_cast<Instruction>(*Use)))
53776aa662cSKarthik Bhat       ++NumUses;
53876aa662cSKarthik Bhat     if (NumUses > 1)
53976aa662cSKarthik Bhat       return true;
54076aa662cSKarthik Bhat   }
54176aa662cSKarthik Bhat 
54276aa662cSKarthik Bhat   return false;
54376aa662cSKarthik Bhat }
5440a91310cSTyler Nowicki bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
545*a097bc69SChad Rosier                                           RecurrenceDescriptor &RedDes,
546*a097bc69SChad Rosier                                           DemandedBits *DB, AssumptionCache *AC,
547*a097bc69SChad Rosier                                           DominatorTree *DT) {
54876aa662cSKarthik Bhat 
54976aa662cSKarthik Bhat   BasicBlock *Header = TheLoop->getHeader();
55076aa662cSKarthik Bhat   Function &F = *Header->getParent();
5518dd66e57SNirav Dave   bool HasFunNoNaNAttr =
55276aa662cSKarthik Bhat       F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
55376aa662cSKarthik Bhat 
554*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
555*a097bc69SChad Rosier                       AC, DT)) {
55676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
55776aa662cSKarthik Bhat     return true;
55876aa662cSKarthik Bhat   }
559*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
560*a097bc69SChad Rosier                       AC, DT)) {
56176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
56276aa662cSKarthik Bhat     return true;
56376aa662cSKarthik Bhat   }
564*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerOr, TheLoop, HasFunNoNaNAttr, RedDes, DB,
565*a097bc69SChad Rosier                       AC, DT)) {
56676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
56776aa662cSKarthik Bhat     return true;
56876aa662cSKarthik Bhat   }
569*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerAnd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
570*a097bc69SChad Rosier                       AC, DT)) {
57176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
57276aa662cSKarthik Bhat     return true;
57376aa662cSKarthik Bhat   }
574*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerXor, TheLoop, HasFunNoNaNAttr, RedDes, DB,
575*a097bc69SChad Rosier                       AC, DT)) {
57676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
57776aa662cSKarthik Bhat     return true;
57876aa662cSKarthik Bhat   }
579*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_IntegerMinMax, TheLoop, HasFunNoNaNAttr, RedDes,
580*a097bc69SChad Rosier                       DB, AC, DT)) {
58176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found a MINMAX reduction PHI." << *Phi << "\n");
58276aa662cSKarthik Bhat     return true;
58376aa662cSKarthik Bhat   }
584*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatMult, TheLoop, HasFunNoNaNAttr, RedDes, DB,
585*a097bc69SChad Rosier                       AC, DT)) {
58676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
58776aa662cSKarthik Bhat     return true;
58876aa662cSKarthik Bhat   }
589*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatAdd, TheLoop, HasFunNoNaNAttr, RedDes, DB,
590*a097bc69SChad Rosier                       AC, DT)) {
59176aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
59276aa662cSKarthik Bhat     return true;
59376aa662cSKarthik Bhat   }
594*a097bc69SChad Rosier   if (AddReductionVar(Phi, RK_FloatMinMax, TheLoop, HasFunNoNaNAttr, RedDes, DB,
595*a097bc69SChad Rosier                       AC, DT)) {
59676aa662cSKarthik Bhat     DEBUG(dbgs() << "Found an float MINMAX reduction PHI." << *Phi << "\n");
59776aa662cSKarthik Bhat     return true;
59876aa662cSKarthik Bhat   }
59976aa662cSKarthik Bhat   // Not a reduction of known type.
60076aa662cSKarthik Bhat   return false;
60176aa662cSKarthik Bhat }
60276aa662cSKarthik Bhat 
6032ff59d43SAyal Zaks bool RecurrenceDescriptor::isFirstOrderRecurrence(
6042ff59d43SAyal Zaks     PHINode *Phi, Loop *TheLoop,
6052ff59d43SAyal Zaks     DenseMap<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
60629c997c1SMatthew Simpson 
60729c997c1SMatthew Simpson   // Ensure the phi node is in the loop header and has two incoming values.
60829c997c1SMatthew Simpson   if (Phi->getParent() != TheLoop->getHeader() ||
60929c997c1SMatthew Simpson       Phi->getNumIncomingValues() != 2)
61029c997c1SMatthew Simpson     return false;
61129c997c1SMatthew Simpson 
61229c997c1SMatthew Simpson   // Ensure the loop has a preheader and a single latch block. The loop
61329c997c1SMatthew Simpson   // vectorizer will need the latch to set up the next iteration of the loop.
61429c997c1SMatthew Simpson   auto *Preheader = TheLoop->getLoopPreheader();
61529c997c1SMatthew Simpson   auto *Latch = TheLoop->getLoopLatch();
61629c997c1SMatthew Simpson   if (!Preheader || !Latch)
61729c997c1SMatthew Simpson     return false;
61829c997c1SMatthew Simpson 
61929c997c1SMatthew Simpson   // Ensure the phi node's incoming blocks are the loop preheader and latch.
62029c997c1SMatthew Simpson   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
62129c997c1SMatthew Simpson       Phi->getBasicBlockIndex(Latch) < 0)
62229c997c1SMatthew Simpson     return false;
62329c997c1SMatthew Simpson 
62429c997c1SMatthew Simpson   // Get the previous value. The previous value comes from the latch edge while
62529c997c1SMatthew Simpson   // the initial value comes form the preheader edge.
62629c997c1SMatthew Simpson   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
6272ff59d43SAyal Zaks   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
6282ff59d43SAyal Zaks       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
62929c997c1SMatthew Simpson     return false;
63029c997c1SMatthew Simpson 
63100dc1b74SAnna Thomas   // Ensure every user of the phi node is dominated by the previous value.
63200dc1b74SAnna Thomas   // The dominance requirement ensures the loop vectorizer will not need to
63300dc1b74SAnna Thomas   // vectorize the initial value prior to the first iteration of the loop.
6342ff59d43SAyal Zaks   // TODO: Consider extending this sinking to handle other kinds of instructions
6352ff59d43SAyal Zaks   // and expressions, beyond sinking a single cast past Previous.
6362ff59d43SAyal Zaks   if (Phi->hasOneUse()) {
6372ff59d43SAyal Zaks     auto *I = Phi->user_back();
6382ff59d43SAyal Zaks     if (I->isCast() && (I->getParent() == Phi->getParent()) && I->hasOneUse() &&
6392ff59d43SAyal Zaks         DT->dominates(Previous, I->user_back())) {
64025e2800eSAyal Zaks       if (!DT->dominates(Previous, I)) // Otherwise we're good w/o sinking.
6412ff59d43SAyal Zaks         SinkAfter[I] = Previous;
6422ff59d43SAyal Zaks       return true;
6432ff59d43SAyal Zaks     }
6442ff59d43SAyal Zaks   }
6452ff59d43SAyal Zaks 
646dcdb325fSAnna Thomas   for (User *U : Phi->users())
647dcdb325fSAnna Thomas     if (auto *I = dyn_cast<Instruction>(U)) {
64829c997c1SMatthew Simpson       if (!DT->dominates(Previous, I))
64929c997c1SMatthew Simpson         return false;
65000dc1b74SAnna Thomas     }
65129c997c1SMatthew Simpson 
65229c997c1SMatthew Simpson   return true;
65329c997c1SMatthew Simpson }
65429c997c1SMatthew Simpson 
65576aa662cSKarthik Bhat /// This function returns the identity element (or neutral element) for
65676aa662cSKarthik Bhat /// the operation K.
6570a91310cSTyler Nowicki Constant *RecurrenceDescriptor::getRecurrenceIdentity(RecurrenceKind K,
6580a91310cSTyler Nowicki                                                       Type *Tp) {
65976aa662cSKarthik Bhat   switch (K) {
66076aa662cSKarthik Bhat   case RK_IntegerXor:
66176aa662cSKarthik Bhat   case RK_IntegerAdd:
66276aa662cSKarthik Bhat   case RK_IntegerOr:
66376aa662cSKarthik Bhat     // Adding, Xoring, Oring zero to a number does not change it.
66476aa662cSKarthik Bhat     return ConstantInt::get(Tp, 0);
66576aa662cSKarthik Bhat   case RK_IntegerMult:
66676aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
66776aa662cSKarthik Bhat     return ConstantInt::get(Tp, 1);
66876aa662cSKarthik Bhat   case RK_IntegerAnd:
66976aa662cSKarthik Bhat     // AND-ing a number with an all-1 value does not change it.
67076aa662cSKarthik Bhat     return ConstantInt::get(Tp, -1, true);
67176aa662cSKarthik Bhat   case RK_FloatMult:
67276aa662cSKarthik Bhat     // Multiplying a number by 1 does not change it.
67376aa662cSKarthik Bhat     return ConstantFP::get(Tp, 1.0L);
67476aa662cSKarthik Bhat   case RK_FloatAdd:
67576aa662cSKarthik Bhat     // Adding zero to a number does not change it.
67676aa662cSKarthik Bhat     return ConstantFP::get(Tp, 0.0L);
67776aa662cSKarthik Bhat   default:
6780a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence kind");
67976aa662cSKarthik Bhat   }
68076aa662cSKarthik Bhat }
68176aa662cSKarthik Bhat 
6820a91310cSTyler Nowicki /// This function translates the recurrence kind to an LLVM binary operator.
6830a91310cSTyler Nowicki unsigned RecurrenceDescriptor::getRecurrenceBinOp(RecurrenceKind Kind) {
68476aa662cSKarthik Bhat   switch (Kind) {
68576aa662cSKarthik Bhat   case RK_IntegerAdd:
68676aa662cSKarthik Bhat     return Instruction::Add;
68776aa662cSKarthik Bhat   case RK_IntegerMult:
68876aa662cSKarthik Bhat     return Instruction::Mul;
68976aa662cSKarthik Bhat   case RK_IntegerOr:
69076aa662cSKarthik Bhat     return Instruction::Or;
69176aa662cSKarthik Bhat   case RK_IntegerAnd:
69276aa662cSKarthik Bhat     return Instruction::And;
69376aa662cSKarthik Bhat   case RK_IntegerXor:
69476aa662cSKarthik Bhat     return Instruction::Xor;
69576aa662cSKarthik Bhat   case RK_FloatMult:
69676aa662cSKarthik Bhat     return Instruction::FMul;
69776aa662cSKarthik Bhat   case RK_FloatAdd:
69876aa662cSKarthik Bhat     return Instruction::FAdd;
69976aa662cSKarthik Bhat   case RK_IntegerMinMax:
70076aa662cSKarthik Bhat     return Instruction::ICmp;
70176aa662cSKarthik Bhat   case RK_FloatMinMax:
70276aa662cSKarthik Bhat     return Instruction::FCmp;
70376aa662cSKarthik Bhat   default:
7040a91310cSTyler Nowicki     llvm_unreachable("Unknown recurrence operation");
70576aa662cSKarthik Bhat   }
70676aa662cSKarthik Bhat }
70776aa662cSKarthik Bhat 
70827b2c39eSTyler Nowicki Value *RecurrenceDescriptor::createMinMaxOp(IRBuilder<> &Builder,
70927b2c39eSTyler Nowicki                                             MinMaxRecurrenceKind RK,
71076aa662cSKarthik Bhat                                             Value *Left, Value *Right) {
71176aa662cSKarthik Bhat   CmpInst::Predicate P = CmpInst::ICMP_NE;
71276aa662cSKarthik Bhat   switch (RK) {
71376aa662cSKarthik Bhat   default:
7140a91310cSTyler Nowicki     llvm_unreachable("Unknown min/max recurrence kind");
71527b2c39eSTyler Nowicki   case MRK_UIntMin:
71676aa662cSKarthik Bhat     P = CmpInst::ICMP_ULT;
71776aa662cSKarthik Bhat     break;
71827b2c39eSTyler Nowicki   case MRK_UIntMax:
71976aa662cSKarthik Bhat     P = CmpInst::ICMP_UGT;
72076aa662cSKarthik Bhat     break;
72127b2c39eSTyler Nowicki   case MRK_SIntMin:
72276aa662cSKarthik Bhat     P = CmpInst::ICMP_SLT;
72376aa662cSKarthik Bhat     break;
72427b2c39eSTyler Nowicki   case MRK_SIntMax:
72576aa662cSKarthik Bhat     P = CmpInst::ICMP_SGT;
72676aa662cSKarthik Bhat     break;
72727b2c39eSTyler Nowicki   case MRK_FloatMin:
72876aa662cSKarthik Bhat     P = CmpInst::FCMP_OLT;
72976aa662cSKarthik Bhat     break;
73027b2c39eSTyler Nowicki   case MRK_FloatMax:
73176aa662cSKarthik Bhat     P = CmpInst::FCMP_OGT;
73276aa662cSKarthik Bhat     break;
73376aa662cSKarthik Bhat   }
73476aa662cSKarthik Bhat 
735629c4115SSanjay Patel   // We only match FP sequences that are 'fast', so we can unconditionally
73650a4c27fSJames Molloy   // set it on any generated instructions.
73750a4c27fSJames Molloy   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
73850a4c27fSJames Molloy   FastMathFlags FMF;
739629c4115SSanjay Patel   FMF.setFast();
740a252815bSSanjay Patel   Builder.setFastMathFlags(FMF);
74150a4c27fSJames Molloy 
74276aa662cSKarthik Bhat   Value *Cmp;
74327b2c39eSTyler Nowicki   if (RK == MRK_FloatMin || RK == MRK_FloatMax)
74476aa662cSKarthik Bhat     Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
74576aa662cSKarthik Bhat   else
74676aa662cSKarthik Bhat     Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
74776aa662cSKarthik Bhat 
74876aa662cSKarthik Bhat   Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
74976aa662cSKarthik Bhat   return Select;
75076aa662cSKarthik Bhat }
75124e6cc2dSKarthik Bhat 
7521bbf15c5SJames Molloy InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
7534750c785SDorit Nuzman                                          const SCEV *Step, BinaryOperator *BOp,
7544750c785SDorit Nuzman                                          SmallVectorImpl<Instruction *> *Casts)
755376a18bdSElena Demikhovsky   : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp) {
7561bbf15c5SJames Molloy   assert(IK != IK_NoInduction && "Not an induction");
757c434d091SElena Demikhovsky 
758c434d091SElena Demikhovsky   // Start value type should match the induction kind and the value
759c434d091SElena Demikhovsky   // itself should not be null.
7601bbf15c5SJames Molloy   assert(StartValue && "StartValue is null");
7611bbf15c5SJames Molloy   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
7621bbf15c5SJames Molloy          "StartValue is not a pointer for pointer induction");
7631bbf15c5SJames Molloy   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
7641bbf15c5SJames Molloy          "StartValue is not an integer for integer induction");
765c434d091SElena Demikhovsky 
766c434d091SElena Demikhovsky   // Check the Step Value. It should be non-zero integer value.
767c434d091SElena Demikhovsky   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
768c434d091SElena Demikhovsky          "Step value is zero");
769c434d091SElena Demikhovsky 
770c434d091SElena Demikhovsky   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
771c434d091SElena Demikhovsky          "Step value should be constant for pointer induction");
772376a18bdSElena Demikhovsky   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
773376a18bdSElena Demikhovsky          "StepValue is not an integer");
774376a18bdSElena Demikhovsky 
775376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
776376a18bdSElena Demikhovsky          "StepValue is not FP for FpInduction");
777376a18bdSElena Demikhovsky   assert((IK != IK_FpInduction || (InductionBinOp &&
778376a18bdSElena Demikhovsky           (InductionBinOp->getOpcode() == Instruction::FAdd ||
779376a18bdSElena Demikhovsky            InductionBinOp->getOpcode() == Instruction::FSub))) &&
780376a18bdSElena Demikhovsky          "Binary opcode should be specified for FP induction");
7814750c785SDorit Nuzman 
7824750c785SDorit Nuzman   if (Casts) {
7834750c785SDorit Nuzman     for (auto &Inst : *Casts) {
7844750c785SDorit Nuzman       RedundantCasts.push_back(Inst);
7854750c785SDorit Nuzman     }
7864750c785SDorit Nuzman   }
7871bbf15c5SJames Molloy }
7881bbf15c5SJames Molloy 
7891bbf15c5SJames Molloy int InductionDescriptor::getConsecutiveDirection() const {
790c434d091SElena Demikhovsky   ConstantInt *ConstStep = getConstIntStepValue();
791c434d091SElena Demikhovsky   if (ConstStep && (ConstStep->isOne() || ConstStep->isMinusOne()))
792c434d091SElena Demikhovsky     return ConstStep->getSExtValue();
7931bbf15c5SJames Molloy   return 0;
7941bbf15c5SJames Molloy }
7951bbf15c5SJames Molloy 
796c434d091SElena Demikhovsky ConstantInt *InductionDescriptor::getConstIntStepValue() const {
797c434d091SElena Demikhovsky   if (isa<SCEVConstant>(Step))
798c434d091SElena Demikhovsky     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
799c434d091SElena Demikhovsky   return nullptr;
800c434d091SElena Demikhovsky }
801c434d091SElena Demikhovsky 
802c434d091SElena Demikhovsky Value *InductionDescriptor::transform(IRBuilder<> &B, Value *Index,
803c434d091SElena Demikhovsky                                       ScalarEvolution *SE,
804c434d091SElena Demikhovsky                                       const DataLayout& DL) const {
805c434d091SElena Demikhovsky 
806c434d091SElena Demikhovsky   SCEVExpander Exp(*SE, DL, "induction");
807376a18bdSElena Demikhovsky   assert(Index->getType() == Step->getType() &&
808376a18bdSElena Demikhovsky          "Index type does not match StepValue type");
8091bbf15c5SJames Molloy   switch (IK) {
810c434d091SElena Demikhovsky   case IK_IntInduction: {
8111bbf15c5SJames Molloy     assert(Index->getType() == StartValue->getType() &&
8121bbf15c5SJames Molloy            "Index type does not match StartValue type");
813c434d091SElena Demikhovsky 
814c434d091SElena Demikhovsky     // FIXME: Theoretically, we can call getAddExpr() of ScalarEvolution
815c434d091SElena Demikhovsky     // and calculate (Start + Index * Step) for all cases, without
816c434d091SElena Demikhovsky     // special handling for "isOne" and "isMinusOne".
817c434d091SElena Demikhovsky     // But in the real life the result code getting worse. We mix SCEV
818c434d091SElena Demikhovsky     // expressions and ADD/SUB operations and receive redundant
819c434d091SElena Demikhovsky     // intermediate values being calculated in different ways and
820c434d091SElena Demikhovsky     // Instcombine is unable to reduce them all.
821c434d091SElena Demikhovsky 
822c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
823c434d091SElena Demikhovsky         getConstIntStepValue()->isMinusOne())
8241bbf15c5SJames Molloy       return B.CreateSub(StartValue, Index);
825c434d091SElena Demikhovsky     if (getConstIntStepValue() &&
826c434d091SElena Demikhovsky         getConstIntStepValue()->isOne())
8271bbf15c5SJames Molloy       return B.CreateAdd(StartValue, Index);
828c434d091SElena Demikhovsky     const SCEV *S = SE->getAddExpr(SE->getSCEV(StartValue),
829c434d091SElena Demikhovsky                                    SE->getMulExpr(Step, SE->getSCEV(Index)));
830c434d091SElena Demikhovsky     return Exp.expandCodeFor(S, StartValue->getType(), &*B.GetInsertPoint());
831c434d091SElena Demikhovsky   }
832c434d091SElena Demikhovsky   case IK_PtrInduction: {
833c434d091SElena Demikhovsky     assert(isa<SCEVConstant>(Step) &&
834c434d091SElena Demikhovsky            "Expected constant step for pointer induction");
835c434d091SElena Demikhovsky     const SCEV *S = SE->getMulExpr(SE->getSCEV(Index), Step);
836c434d091SElena Demikhovsky     Index = Exp.expandCodeFor(S, Index->getType(), &*B.GetInsertPoint());
8371bbf15c5SJames Molloy     return B.CreateGEP(nullptr, StartValue, Index);
838c434d091SElena Demikhovsky   }
839376a18bdSElena Demikhovsky   case IK_FpInduction: {
840376a18bdSElena Demikhovsky     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
841376a18bdSElena Demikhovsky     assert(InductionBinOp &&
842376a18bdSElena Demikhovsky            (InductionBinOp->getOpcode() == Instruction::FAdd ||
843376a18bdSElena Demikhovsky             InductionBinOp->getOpcode() == Instruction::FSub) &&
844376a18bdSElena Demikhovsky            "Original bin op should be defined for FP induction");
845376a18bdSElena Demikhovsky 
846376a18bdSElena Demikhovsky     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
847376a18bdSElena Demikhovsky 
848376a18bdSElena Demikhovsky     // Floating point operations had to be 'fast' to enable the induction.
849376a18bdSElena Demikhovsky     FastMathFlags Flags;
850629c4115SSanjay Patel     Flags.setFast();
851376a18bdSElena Demikhovsky 
852376a18bdSElena Demikhovsky     Value *MulExp = B.CreateFMul(StepValue, Index);
853376a18bdSElena Demikhovsky     if (isa<Instruction>(MulExp))
854376a18bdSElena Demikhovsky       // We have to check, the MulExp may be a constant.
855376a18bdSElena Demikhovsky       cast<Instruction>(MulExp)->setFastMathFlags(Flags);
856376a18bdSElena Demikhovsky 
857376a18bdSElena Demikhovsky     Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode() , StartValue,
858376a18bdSElena Demikhovsky                                MulExp, "induction");
859376a18bdSElena Demikhovsky     if (isa<Instruction>(BOp))
860376a18bdSElena Demikhovsky       cast<Instruction>(BOp)->setFastMathFlags(Flags);
861376a18bdSElena Demikhovsky 
862376a18bdSElena Demikhovsky     return BOp;
863376a18bdSElena Demikhovsky   }
8641bbf15c5SJames Molloy   case IK_NoInduction:
8651bbf15c5SJames Molloy     return nullptr;
8661bbf15c5SJames Molloy   }
8671bbf15c5SJames Molloy   llvm_unreachable("invalid enum");
8681bbf15c5SJames Molloy }
8691bbf15c5SJames Molloy 
870376a18bdSElena Demikhovsky bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
871376a18bdSElena Demikhovsky                                            ScalarEvolution *SE,
872376a18bdSElena Demikhovsky                                            InductionDescriptor &D) {
873376a18bdSElena Demikhovsky 
874376a18bdSElena Demikhovsky   // Here we only handle FP induction variables.
875376a18bdSElena Demikhovsky   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
876376a18bdSElena Demikhovsky 
877376a18bdSElena Demikhovsky   if (TheLoop->getHeader() != Phi->getParent())
878376a18bdSElena Demikhovsky     return false;
879376a18bdSElena Demikhovsky 
880376a18bdSElena Demikhovsky   // The loop may have multiple entrances or multiple exits; we can analyze
881376a18bdSElena Demikhovsky   // this phi if it has a unique entry value and a unique backedge value.
882376a18bdSElena Demikhovsky   if (Phi->getNumIncomingValues() != 2)
883376a18bdSElena Demikhovsky     return false;
884376a18bdSElena Demikhovsky   Value *BEValue = nullptr, *StartValue = nullptr;
885376a18bdSElena Demikhovsky   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
886376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(0);
887376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(1);
888376a18bdSElena Demikhovsky   } else {
889376a18bdSElena Demikhovsky     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
890376a18bdSElena Demikhovsky            "Unexpected Phi node in the loop");
891376a18bdSElena Demikhovsky     BEValue = Phi->getIncomingValue(1);
892376a18bdSElena Demikhovsky     StartValue = Phi->getIncomingValue(0);
893376a18bdSElena Demikhovsky   }
894376a18bdSElena Demikhovsky 
895376a18bdSElena Demikhovsky   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
896376a18bdSElena Demikhovsky   if (!BOp)
897376a18bdSElena Demikhovsky     return false;
898376a18bdSElena Demikhovsky 
899376a18bdSElena Demikhovsky   Value *Addend = nullptr;
900376a18bdSElena Demikhovsky   if (BOp->getOpcode() == Instruction::FAdd) {
901376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
902376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
903376a18bdSElena Demikhovsky     else if (BOp->getOperand(1) == Phi)
904376a18bdSElena Demikhovsky       Addend = BOp->getOperand(0);
905376a18bdSElena Demikhovsky   } else if (BOp->getOpcode() == Instruction::FSub)
906376a18bdSElena Demikhovsky     if (BOp->getOperand(0) == Phi)
907376a18bdSElena Demikhovsky       Addend = BOp->getOperand(1);
908376a18bdSElena Demikhovsky 
909376a18bdSElena Demikhovsky   if (!Addend)
910376a18bdSElena Demikhovsky     return false;
911376a18bdSElena Demikhovsky 
912376a18bdSElena Demikhovsky   // The addend should be loop invariant
913376a18bdSElena Demikhovsky   if (auto *I = dyn_cast<Instruction>(Addend))
914376a18bdSElena Demikhovsky     if (TheLoop->contains(I))
915376a18bdSElena Demikhovsky       return false;
916376a18bdSElena Demikhovsky 
917376a18bdSElena Demikhovsky   // FP Step has unknown SCEV
918376a18bdSElena Demikhovsky   const SCEV *Step = SE->getUnknown(Addend);
919376a18bdSElena Demikhovsky   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
920376a18bdSElena Demikhovsky   return true;
921376a18bdSElena Demikhovsky }
922376a18bdSElena Demikhovsky 
9234750c785SDorit Nuzman /// This function is called when we suspect that the update-chain of a phi node
9244750c785SDorit Nuzman /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
9254750c785SDorit Nuzman /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
9264750c785SDorit Nuzman /// predicate P under which the SCEV expression for the phi can be the
9274750c785SDorit Nuzman /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
9284750c785SDorit Nuzman /// cast instructions that are involved in the update-chain of this induction.
9294750c785SDorit Nuzman /// A caller that adds the required runtime predicate can be free to drop these
9304750c785SDorit Nuzman /// cast instructions, and compute the phi using \p AR (instead of some scev
9314750c785SDorit Nuzman /// expression with casts).
9324750c785SDorit Nuzman ///
9334750c785SDorit Nuzman /// For example, without a predicate the scev expression can take the following
9344750c785SDorit Nuzman /// form:
9354750c785SDorit Nuzman ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
9364750c785SDorit Nuzman ///
9374750c785SDorit Nuzman /// It corresponds to the following IR sequence:
9384750c785SDorit Nuzman /// %for.body:
9394750c785SDorit Nuzman ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
9404750c785SDorit Nuzman ///   %casted_phi = "ExtTrunc i64 %x"
9414750c785SDorit Nuzman ///   %add = add i64 %casted_phi, %step
9424750c785SDorit Nuzman ///
9434750c785SDorit Nuzman /// where %x is given in \p PN,
9444750c785SDorit Nuzman /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
9454750c785SDorit Nuzman /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
9464750c785SDorit Nuzman /// several forms, for example, such as:
9474750c785SDorit Nuzman ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
9484750c785SDorit Nuzman /// or:
9494750c785SDorit Nuzman ///   ExtTrunc2:    %t = shl %x, m
9504750c785SDorit Nuzman ///                 %casted_phi = ashr %t, m
9514750c785SDorit Nuzman ///
9524750c785SDorit Nuzman /// If we are able to find such sequence, we return the instructions
9534750c785SDorit Nuzman /// we found, namely %casted_phi and the instructions on its use-def chain up
9544750c785SDorit Nuzman /// to the phi (not including the phi).
955802e6255SBenjamin Kramer static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
956802e6255SBenjamin Kramer                                     const SCEVUnknown *PhiScev,
957802e6255SBenjamin Kramer                                     const SCEVAddRecExpr *AR,
958802e6255SBenjamin Kramer                                     SmallVectorImpl<Instruction *> &CastInsts) {
9594750c785SDorit Nuzman 
9604750c785SDorit Nuzman   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
9614750c785SDorit Nuzman   auto *PN = cast<PHINode>(PhiScev->getValue());
9624750c785SDorit Nuzman   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
9634750c785SDorit Nuzman   const Loop *L = AR->getLoop();
9644750c785SDorit Nuzman 
9654750c785SDorit Nuzman   // Find any cast instructions that participate in the def-use chain of
9664750c785SDorit Nuzman   // PhiScev in the loop.
9674750c785SDorit Nuzman   // FORNOW/TODO: We currently expect the def-use chain to include only
9684750c785SDorit Nuzman   // two-operand instructions, where one of the operands is an invariant.
9694750c785SDorit Nuzman   // createAddRecFromPHIWithCasts() currently does not support anything more
9704750c785SDorit Nuzman   // involved than that, so we keep the search simple. This can be
9714750c785SDorit Nuzman   // extended/generalized as needed.
9724750c785SDorit Nuzman 
9734750c785SDorit Nuzman   auto getDef = [&](const Value *Val) -> Value * {
9744750c785SDorit Nuzman     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
9754750c785SDorit Nuzman     if (!BinOp)
9764750c785SDorit Nuzman       return nullptr;
9774750c785SDorit Nuzman     Value *Op0 = BinOp->getOperand(0);
9784750c785SDorit Nuzman     Value *Op1 = BinOp->getOperand(1);
9794750c785SDorit Nuzman     Value *Def = nullptr;
9804750c785SDorit Nuzman     if (L->isLoopInvariant(Op0))
9814750c785SDorit Nuzman       Def = Op1;
9824750c785SDorit Nuzman     else if (L->isLoopInvariant(Op1))
9834750c785SDorit Nuzman       Def = Op0;
9844750c785SDorit Nuzman     return Def;
9854750c785SDorit Nuzman   };
9864750c785SDorit Nuzman 
9874750c785SDorit Nuzman   // Look for the instruction that defines the induction via the
9884750c785SDorit Nuzman   // loop backedge.
9894750c785SDorit Nuzman   BasicBlock *Latch = L->getLoopLatch();
9904750c785SDorit Nuzman   if (!Latch)
9914750c785SDorit Nuzman     return false;
9924750c785SDorit Nuzman   Value *Val = PN->getIncomingValueForBlock(Latch);
9934750c785SDorit Nuzman   if (!Val)
9944750c785SDorit Nuzman     return false;
9954750c785SDorit Nuzman 
9964750c785SDorit Nuzman   // Follow the def-use chain until the induction phi is reached.
9974750c785SDorit Nuzman   // If on the way we encounter a Value that has the same SCEV Expr as the
9984750c785SDorit Nuzman   // phi node, we can consider the instructions we visit from that point
9994750c785SDorit Nuzman   // as part of the cast-sequence that can be ignored.
10004750c785SDorit Nuzman   bool InCastSequence = false;
10014750c785SDorit Nuzman   auto *Inst = dyn_cast<Instruction>(Val);
10024750c785SDorit Nuzman   while (Val != PN) {
10034750c785SDorit Nuzman     // If we encountered a phi node other than PN, or if we left the loop,
10044750c785SDorit Nuzman     // we bail out.
10054750c785SDorit Nuzman     if (!Inst || !L->contains(Inst)) {
10064750c785SDorit Nuzman       return false;
10074750c785SDorit Nuzman     }
10084750c785SDorit Nuzman     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
10094750c785SDorit Nuzman     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
10104750c785SDorit Nuzman       InCastSequence = true;
10114750c785SDorit Nuzman     if (InCastSequence) {
10124750c785SDorit Nuzman       // Only the last instruction in the cast sequence is expected to have
10134750c785SDorit Nuzman       // uses outside the induction def-use chain.
10144750c785SDorit Nuzman       if (!CastInsts.empty())
10154750c785SDorit Nuzman         if (!Inst->hasOneUse())
10164750c785SDorit Nuzman           return false;
10174750c785SDorit Nuzman       CastInsts.push_back(Inst);
10184750c785SDorit Nuzman     }
10194750c785SDorit Nuzman     Val = getDef(Val);
10204750c785SDorit Nuzman     if (!Val)
10214750c785SDorit Nuzman       return false;
10224750c785SDorit Nuzman     Inst = dyn_cast<Instruction>(Val);
10234750c785SDorit Nuzman   }
10244750c785SDorit Nuzman 
10254750c785SDorit Nuzman   return InCastSequence;
10264750c785SDorit Nuzman }
10274750c785SDorit Nuzman 
1028376a18bdSElena Demikhovsky bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
1029c05bab8aSSilviu Baranga                                          PredicatedScalarEvolution &PSE,
1030c05bab8aSSilviu Baranga                                          InductionDescriptor &D,
1031c05bab8aSSilviu Baranga                                          bool Assume) {
1032c05bab8aSSilviu Baranga   Type *PhiTy = Phi->getType();
1033376a18bdSElena Demikhovsky 
1034376a18bdSElena Demikhovsky   // Handle integer and pointer inductions variables.
1035376a18bdSElena Demikhovsky   // Now we handle also FP induction but not trying to make a
1036376a18bdSElena Demikhovsky   // recurrent expression from the PHI node in-place.
1037376a18bdSElena Demikhovsky 
1038376a18bdSElena Demikhovsky   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() &&
1039376a18bdSElena Demikhovsky       !PhiTy->isFloatTy() && !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
1040c05bab8aSSilviu Baranga     return false;
1041c05bab8aSSilviu Baranga 
1042376a18bdSElena Demikhovsky   if (PhiTy->isFloatingPointTy())
1043376a18bdSElena Demikhovsky     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
1044376a18bdSElena Demikhovsky 
1045c05bab8aSSilviu Baranga   const SCEV *PhiScev = PSE.getSCEV(Phi);
1046c05bab8aSSilviu Baranga   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1047c05bab8aSSilviu Baranga 
1048c05bab8aSSilviu Baranga   // We need this expression to be an AddRecExpr.
1049c05bab8aSSilviu Baranga   if (Assume && !AR)
1050c05bab8aSSilviu Baranga     AR = PSE.getAsAddRec(Phi);
1051c05bab8aSSilviu Baranga 
1052c05bab8aSSilviu Baranga   if (!AR) {
1053c05bab8aSSilviu Baranga     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
1054c05bab8aSSilviu Baranga     return false;
1055c05bab8aSSilviu Baranga   }
1056c05bab8aSSilviu Baranga 
10574750c785SDorit Nuzman   // Record any Cast instructions that participate in the induction update
10584750c785SDorit Nuzman   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
10594750c785SDorit Nuzman   // If we started from an UnknownSCEV, and managed to build an addRecurrence
10604750c785SDorit Nuzman   // only after enabling Assume with PSCEV, this means we may have encountered
10614750c785SDorit Nuzman   // cast instructions that required adding a runtime check in order to
10624750c785SDorit Nuzman   // guarantee the correctness of the AddRecurence respresentation of the
10634750c785SDorit Nuzman   // induction.
10644750c785SDorit Nuzman   if (PhiScev != AR && SymbolicPhi) {
10654750c785SDorit Nuzman     SmallVector<Instruction *, 2> Casts;
10664750c785SDorit Nuzman     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
10674750c785SDorit Nuzman       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
10684750c785SDorit Nuzman   }
10694750c785SDorit Nuzman 
1070376a18bdSElena Demikhovsky   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
1071c05bab8aSSilviu Baranga }
1072c05bab8aSSilviu Baranga 
10734750c785SDorit Nuzman bool InductionDescriptor::isInductionPHI(
10744750c785SDorit Nuzman     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
10754750c785SDorit Nuzman     InductionDescriptor &D, const SCEV *Expr,
10764750c785SDorit Nuzman     SmallVectorImpl<Instruction *> *CastsToIgnore) {
107724e6cc2dSKarthik Bhat   Type *PhiTy = Phi->getType();
107824e6cc2dSKarthik Bhat   // We only handle integer and pointer inductions variables.
107924e6cc2dSKarthik Bhat   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
108024e6cc2dSKarthik Bhat     return false;
108124e6cc2dSKarthik Bhat 
108224e6cc2dSKarthik Bhat   // Check that the PHI is consecutive.
1083c05bab8aSSilviu Baranga   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
108424e6cc2dSKarthik Bhat   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
1085c05bab8aSSilviu Baranga 
108624e6cc2dSKarthik Bhat   if (!AR) {
108724e6cc2dSKarthik Bhat     DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
108824e6cc2dSKarthik Bhat     return false;
108924e6cc2dSKarthik Bhat   }
109024e6cc2dSKarthik Bhat 
1091ee31cbe3SMichael Kuperstein   if (AR->getLoop() != TheLoop) {
1092ee31cbe3SMichael Kuperstein     // FIXME: We should treat this as a uniform. Unfortunately, we
1093ee31cbe3SMichael Kuperstein     // don't currently know how to handled uniform PHIs.
1094ee31cbe3SMichael Kuperstein     DEBUG(dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
1095ee31cbe3SMichael Kuperstein     return false;
1096ee31cbe3SMichael Kuperstein   }
1097ee31cbe3SMichael Kuperstein 
10981bbf15c5SJames Molloy   Value *StartValue =
10991bbf15c5SJames Molloy     Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
110024e6cc2dSKarthik Bhat   const SCEV *Step = AR->getStepRecurrence(*SE);
110124e6cc2dSKarthik Bhat   // Calculate the pointer stride and check if it is consecutive.
1102c434d091SElena Demikhovsky   // The stride may be a constant or a loop invariant integer value.
1103c434d091SElena Demikhovsky   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
1104376a18bdSElena Demikhovsky   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
110524e6cc2dSKarthik Bhat     return false;
110624e6cc2dSKarthik Bhat 
110724e6cc2dSKarthik Bhat   if (PhiTy->isIntegerTy()) {
11084750c785SDorit Nuzman     D = InductionDescriptor(StartValue, IK_IntInduction, Step, /*BOp=*/ nullptr,
11094750c785SDorit Nuzman                             CastsToIgnore);
111024e6cc2dSKarthik Bhat     return true;
111124e6cc2dSKarthik Bhat   }
111224e6cc2dSKarthik Bhat 
111324e6cc2dSKarthik Bhat   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
1114c434d091SElena Demikhovsky   // Pointer induction should be a constant.
1115c434d091SElena Demikhovsky   if (!ConstStep)
1116c434d091SElena Demikhovsky     return false;
1117c434d091SElena Demikhovsky 
1118c434d091SElena Demikhovsky   ConstantInt *CV = ConstStep->getValue();
111924e6cc2dSKarthik Bhat   Type *PointerElementType = PhiTy->getPointerElementType();
112024e6cc2dSKarthik Bhat   // The pointer stride cannot be determined if the pointer element type is not
112124e6cc2dSKarthik Bhat   // sized.
112224e6cc2dSKarthik Bhat   if (!PointerElementType->isSized())
112324e6cc2dSKarthik Bhat     return false;
112424e6cc2dSKarthik Bhat 
112524e6cc2dSKarthik Bhat   const DataLayout &DL = Phi->getModule()->getDataLayout();
112624e6cc2dSKarthik Bhat   int64_t Size = static_cast<int64_t>(DL.getTypeAllocSize(PointerElementType));
1127b58f32f7SDavid Majnemer   if (!Size)
1128b58f32f7SDavid Majnemer     return false;
1129b58f32f7SDavid Majnemer 
113024e6cc2dSKarthik Bhat   int64_t CVSize = CV->getSExtValue();
113124e6cc2dSKarthik Bhat   if (CVSize % Size)
113224e6cc2dSKarthik Bhat     return false;
1133c434d091SElena Demikhovsky   auto *StepValue = SE->getConstant(CV->getType(), CVSize / Size,
1134c434d091SElena Demikhovsky                                     true /* signed */);
11351bbf15c5SJames Molloy   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue);
113624e6cc2dSKarthik Bhat   return true;
113724e6cc2dSKarthik Bhat }
1138c5b7b555SAshutosh Nema 
11394a000883SChandler Carruth bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
11404a000883SChandler Carruth                                    bool PreserveLCSSA) {
11414a000883SChandler Carruth   bool Changed = false;
11424a000883SChandler Carruth 
11434a000883SChandler Carruth   // We re-use a vector for the in-loop predecesosrs.
11444a000883SChandler Carruth   SmallVector<BasicBlock *, 4> InLoopPredecessors;
11454a000883SChandler Carruth 
11464a000883SChandler Carruth   auto RewriteExit = [&](BasicBlock *BB) {
11474a000883SChandler Carruth     assert(InLoopPredecessors.empty() &&
11484a000883SChandler Carruth            "Must start with an empty predecessors list!");
11494a000883SChandler Carruth     auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
11504a000883SChandler Carruth 
11514a000883SChandler Carruth     // See if there are any non-loop predecessors of this exit block and
11524a000883SChandler Carruth     // keep track of the in-loop predecessors.
11534a000883SChandler Carruth     bool IsDedicatedExit = true;
11544a000883SChandler Carruth     for (auto *PredBB : predecessors(BB))
11554a000883SChandler Carruth       if (L->contains(PredBB)) {
11564a000883SChandler Carruth         if (isa<IndirectBrInst>(PredBB->getTerminator()))
11574a000883SChandler Carruth           // We cannot rewrite exiting edges from an indirectbr.
11584a000883SChandler Carruth           return false;
11594a000883SChandler Carruth 
11604a000883SChandler Carruth         InLoopPredecessors.push_back(PredBB);
11614a000883SChandler Carruth       } else {
11624a000883SChandler Carruth         IsDedicatedExit = false;
11634a000883SChandler Carruth       }
11644a000883SChandler Carruth 
11654a000883SChandler Carruth     assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
11664a000883SChandler Carruth 
11674a000883SChandler Carruth     // Nothing to do if this is already a dedicated exit.
11684a000883SChandler Carruth     if (IsDedicatedExit)
11694a000883SChandler Carruth       return false;
11704a000883SChandler Carruth 
11714a000883SChandler Carruth     auto *NewExitBB = SplitBlockPredecessors(
11724a000883SChandler Carruth         BB, InLoopPredecessors, ".loopexit", DT, LI, PreserveLCSSA);
11734a000883SChandler Carruth 
11744a000883SChandler Carruth     if (!NewExitBB)
11754a000883SChandler Carruth       DEBUG(dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
11764a000883SChandler Carruth                    << *L << "\n");
11774a000883SChandler Carruth     else
11784a000883SChandler Carruth       DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
11794a000883SChandler Carruth                    << NewExitBB->getName() << "\n");
11804a000883SChandler Carruth     return true;
11814a000883SChandler Carruth   };
11824a000883SChandler Carruth 
11834a000883SChandler Carruth   // Walk the exit blocks directly rather than building up a data structure for
11844a000883SChandler Carruth   // them, but only visit each one once.
11854a000883SChandler Carruth   SmallPtrSet<BasicBlock *, 4> Visited;
11864a000883SChandler Carruth   for (auto *BB : L->blocks())
11874a000883SChandler Carruth     for (auto *SuccBB : successors(BB)) {
11884a000883SChandler Carruth       // We're looking for exit blocks so skip in-loop successors.
11894a000883SChandler Carruth       if (L->contains(SuccBB))
11904a000883SChandler Carruth         continue;
11914a000883SChandler Carruth 
11924a000883SChandler Carruth       // Visit each exit block exactly once.
11934a000883SChandler Carruth       if (!Visited.insert(SuccBB).second)
11944a000883SChandler Carruth         continue;
11954a000883SChandler Carruth 
11964a000883SChandler Carruth       Changed |= RewriteExit(SuccBB);
11974a000883SChandler Carruth     }
11984a000883SChandler Carruth 
11994a000883SChandler Carruth   return Changed;
12004a000883SChandler Carruth }
12014a000883SChandler Carruth 
1202c5b7b555SAshutosh Nema /// \brief Returns the instructions that use values defined in the loop.
1203c5b7b555SAshutosh Nema SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
1204c5b7b555SAshutosh Nema   SmallVector<Instruction *, 8> UsedOutside;
1205c5b7b555SAshutosh Nema 
1206c5b7b555SAshutosh Nema   for (auto *Block : L->getBlocks())
1207c5b7b555SAshutosh Nema     // FIXME: I believe that this could use copy_if if the Inst reference could
1208c5b7b555SAshutosh Nema     // be adapted into a pointer.
1209c5b7b555SAshutosh Nema     for (auto &Inst : *Block) {
1210c5b7b555SAshutosh Nema       auto Users = Inst.users();
12110a16c228SDavid Majnemer       if (any_of(Users, [&](User *U) {
1212c5b7b555SAshutosh Nema             auto *Use = cast<Instruction>(U);
1213c5b7b555SAshutosh Nema             return !L->contains(Use->getParent());
1214c5b7b555SAshutosh Nema           }))
1215c5b7b555SAshutosh Nema         UsedOutside.push_back(&Inst);
1216c5b7b555SAshutosh Nema     }
1217c5b7b555SAshutosh Nema 
1218c5b7b555SAshutosh Nema   return UsedOutside;
1219c5b7b555SAshutosh Nema }
122031088a9dSChandler Carruth 
122131088a9dSChandler Carruth void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
122231088a9dSChandler Carruth   // By definition, all loop passes need the LoopInfo analysis and the
122331088a9dSChandler Carruth   // Dominator tree it depends on. Because they all participate in the loop
122431088a9dSChandler Carruth   // pass manager, they must also preserve these.
122531088a9dSChandler Carruth   AU.addRequired<DominatorTreeWrapperPass>();
122631088a9dSChandler Carruth   AU.addPreserved<DominatorTreeWrapperPass>();
122731088a9dSChandler Carruth   AU.addRequired<LoopInfoWrapperPass>();
122831088a9dSChandler Carruth   AU.addPreserved<LoopInfoWrapperPass>();
122931088a9dSChandler Carruth 
123031088a9dSChandler Carruth   // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
123131088a9dSChandler Carruth   // here because users shouldn't directly get them from this header.
123231088a9dSChandler Carruth   extern char &LoopSimplifyID;
123331088a9dSChandler Carruth   extern char &LCSSAID;
123431088a9dSChandler Carruth   AU.addRequiredID(LoopSimplifyID);
123531088a9dSChandler Carruth   AU.addPreservedID(LoopSimplifyID);
123631088a9dSChandler Carruth   AU.addRequiredID(LCSSAID);
123731088a9dSChandler Carruth   AU.addPreservedID(LCSSAID);
1238c3ccf5d7SIgor Laevsky   // This is used in the LPPassManager to perform LCSSA verification on passes
1239c3ccf5d7SIgor Laevsky   // which preserve lcssa form
1240c3ccf5d7SIgor Laevsky   AU.addRequired<LCSSAVerificationPass>();
1241c3ccf5d7SIgor Laevsky   AU.addPreserved<LCSSAVerificationPass>();
124231088a9dSChandler Carruth 
124331088a9dSChandler Carruth   // Loop passes are designed to run inside of a loop pass manager which means
124431088a9dSChandler Carruth   // that any function analyses they require must be required by the first loop
124531088a9dSChandler Carruth   // pass in the manager (so that it is computed before the loop pass manager
124631088a9dSChandler Carruth   // runs) and preserved by all loop pasess in the manager. To make this
124731088a9dSChandler Carruth   // reasonably robust, the set needed for most loop passes is maintained here.
124831088a9dSChandler Carruth   // If your loop pass requires an analysis not listed here, you will need to
124931088a9dSChandler Carruth   // carefully audit the loop pass manager nesting structure that results.
125031088a9dSChandler Carruth   AU.addRequired<AAResultsWrapperPass>();
125131088a9dSChandler Carruth   AU.addPreserved<AAResultsWrapperPass>();
125231088a9dSChandler Carruth   AU.addPreserved<BasicAAWrapperPass>();
125331088a9dSChandler Carruth   AU.addPreserved<GlobalsAAWrapperPass>();
125431088a9dSChandler Carruth   AU.addPreserved<SCEVAAWrapperPass>();
125531088a9dSChandler Carruth   AU.addRequired<ScalarEvolutionWrapperPass>();
125631088a9dSChandler Carruth   AU.addPreserved<ScalarEvolutionWrapperPass>();
125731088a9dSChandler Carruth }
125831088a9dSChandler Carruth 
125931088a9dSChandler Carruth /// Manually defined generic "LoopPass" dependency initialization. This is used
126031088a9dSChandler Carruth /// to initialize the exact set of passes from above in \c
126131088a9dSChandler Carruth /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
126231088a9dSChandler Carruth /// with:
126331088a9dSChandler Carruth ///
126431088a9dSChandler Carruth ///   INITIALIZE_PASS_DEPENDENCY(LoopPass)
126531088a9dSChandler Carruth ///
126631088a9dSChandler Carruth /// As-if "LoopPass" were a pass.
126731088a9dSChandler Carruth void llvm::initializeLoopPassPass(PassRegistry &Registry) {
126831088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
126931088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
127031088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
1271e12c487bSEaswaran Raman   INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
127231088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
127331088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
127431088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
127531088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
127631088a9dSChandler Carruth   INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
127731088a9dSChandler Carruth }
1278963341c8SAdam Nemet 
1279fe3def7cSAdam Nemet /// \brief Find string metadata for loop
1280fe3def7cSAdam Nemet ///
1281fe3def7cSAdam Nemet /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
1282fe3def7cSAdam Nemet /// operand or null otherwise.  If the string metadata is not found return
1283fe3def7cSAdam Nemet /// Optional's not-a-value.
1284fe3def7cSAdam Nemet Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
1285fe3def7cSAdam Nemet                                                             StringRef Name) {
1286963341c8SAdam Nemet   MDNode *LoopID = TheLoop->getLoopID();
1287fe3def7cSAdam Nemet   // Return none if LoopID is false.
1288963341c8SAdam Nemet   if (!LoopID)
1289fe3def7cSAdam Nemet     return None;
1290293be666SAdam Nemet 
1291293be666SAdam Nemet   // First operand should refer to the loop id itself.
1292293be666SAdam Nemet   assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
1293293be666SAdam Nemet   assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
1294293be666SAdam Nemet 
1295963341c8SAdam Nemet   // Iterate over LoopID operands and look for MDString Metadata
1296963341c8SAdam Nemet   for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
1297963341c8SAdam Nemet     MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
1298963341c8SAdam Nemet     if (!MD)
1299963341c8SAdam Nemet       continue;
1300963341c8SAdam Nemet     MDString *S = dyn_cast<MDString>(MD->getOperand(0));
1301963341c8SAdam Nemet     if (!S)
1302963341c8SAdam Nemet       continue;
1303963341c8SAdam Nemet     // Return true if MDString holds expected MetaData.
1304963341c8SAdam Nemet     if (Name.equals(S->getString()))
1305fe3def7cSAdam Nemet       switch (MD->getNumOperands()) {
1306fe3def7cSAdam Nemet       case 1:
1307fe3def7cSAdam Nemet         return nullptr;
1308fe3def7cSAdam Nemet       case 2:
1309fe3def7cSAdam Nemet         return &MD->getOperand(1);
1310fe3def7cSAdam Nemet       default:
1311fe3def7cSAdam Nemet         llvm_unreachable("loop metadata has 0 or 1 operand");
1312963341c8SAdam Nemet       }
1313fe3def7cSAdam Nemet   }
1314fe3def7cSAdam Nemet   return None;
1315963341c8SAdam Nemet }
1316122f984aSEvgeniy Stepanov 
13177ed5856aSAlina Sbirlea /// Does a BFS from a given node to all of its children inside a given loop.
13187ed5856aSAlina Sbirlea /// The returned vector of nodes includes the starting point.
13197ed5856aSAlina Sbirlea SmallVector<DomTreeNode *, 16>
13207ed5856aSAlina Sbirlea llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
13217ed5856aSAlina Sbirlea   SmallVector<DomTreeNode *, 16> Worklist;
13227ed5856aSAlina Sbirlea   auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
13237ed5856aSAlina Sbirlea     // Only include subregions in the top level loop.
13247ed5856aSAlina Sbirlea     BasicBlock *BB = DTN->getBlock();
13257ed5856aSAlina Sbirlea     if (CurLoop->contains(BB))
13267ed5856aSAlina Sbirlea       Worklist.push_back(DTN);
13277ed5856aSAlina Sbirlea   };
13287ed5856aSAlina Sbirlea 
13297ed5856aSAlina Sbirlea   AddRegionToWorklist(N);
13307ed5856aSAlina Sbirlea 
13317ed5856aSAlina Sbirlea   for (size_t I = 0; I < Worklist.size(); I++)
13327ed5856aSAlina Sbirlea     for (DomTreeNode *Child : Worklist[I]->getChildren())
13337ed5856aSAlina Sbirlea       AddRegionToWorklist(Child);
13347ed5856aSAlina Sbirlea 
13357ed5856aSAlina Sbirlea   return Worklist;
13367ed5856aSAlina Sbirlea }
13377ed5856aSAlina Sbirlea 
1338df3e71e0SMarcello Maggioni void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
1339df3e71e0SMarcello Maggioni                           ScalarEvolution *SE = nullptr,
1340df3e71e0SMarcello Maggioni                           LoopInfo *LI = nullptr) {
1341899809d5SHans Wennborg   assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
1342df3e71e0SMarcello Maggioni   auto *Preheader = L->getLoopPreheader();
1343df3e71e0SMarcello Maggioni   assert(Preheader && "Preheader should exist!");
1344df3e71e0SMarcello Maggioni 
1345df3e71e0SMarcello Maggioni   // Now that we know the removal is safe, remove the loop by changing the
1346df3e71e0SMarcello Maggioni   // branch from the preheader to go to the single exit block.
1347df3e71e0SMarcello Maggioni   //
1348df3e71e0SMarcello Maggioni   // Because we're deleting a large chunk of code at once, the sequence in which
1349df3e71e0SMarcello Maggioni   // we remove things is very important to avoid invalidation issues.
1350df3e71e0SMarcello Maggioni 
1351df3e71e0SMarcello Maggioni   // Tell ScalarEvolution that the loop is deleted. Do this before
1352df3e71e0SMarcello Maggioni   // deleting the loop so that ScalarEvolution can look at the loop
1353df3e71e0SMarcello Maggioni   // to determine what it needs to clean up.
1354df3e71e0SMarcello Maggioni   if (SE)
1355df3e71e0SMarcello Maggioni     SE->forgetLoop(L);
1356df3e71e0SMarcello Maggioni 
1357df3e71e0SMarcello Maggioni   auto *ExitBlock = L->getUniqueExitBlock();
1358df3e71e0SMarcello Maggioni   assert(ExitBlock && "Should have a unique exit block!");
1359df3e71e0SMarcello Maggioni   assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
1360df3e71e0SMarcello Maggioni 
1361df3e71e0SMarcello Maggioni   auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
1362df3e71e0SMarcello Maggioni   assert(OldBr && "Preheader must end with a branch");
1363df3e71e0SMarcello Maggioni   assert(OldBr->isUnconditional() && "Preheader must have a single successor");
1364df3e71e0SMarcello Maggioni   // Connect the preheader to the exit block. Keep the old edge to the header
1365df3e71e0SMarcello Maggioni   // around to perform the dominator tree update in two separate steps
1366df3e71e0SMarcello Maggioni   // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
1367df3e71e0SMarcello Maggioni   // preheader -> header.
1368df3e71e0SMarcello Maggioni   //
1369df3e71e0SMarcello Maggioni   //
1370df3e71e0SMarcello Maggioni   // 0.  Preheader          1.  Preheader           2.  Preheader
1371df3e71e0SMarcello Maggioni   //        |                    |   |                   |
1372df3e71e0SMarcello Maggioni   //        V                    |   V                   |
1373df3e71e0SMarcello Maggioni   //      Header <--\            | Header <--\           | Header <--\
1374df3e71e0SMarcello Maggioni   //       |  |     |            |  |  |     |           |  |  |     |
1375df3e71e0SMarcello Maggioni   //       |  V     |            |  |  V     |           |  |  V     |
1376df3e71e0SMarcello Maggioni   //       | Body --/            |  | Body --/           |  | Body --/
1377df3e71e0SMarcello Maggioni   //       V                     V  V                    V  V
1378df3e71e0SMarcello Maggioni   //      Exit                   Exit                    Exit
1379df3e71e0SMarcello Maggioni   //
1380df3e71e0SMarcello Maggioni   // By doing this is two separate steps we can perform the dominator tree
1381df3e71e0SMarcello Maggioni   // update without using the batch update API.
1382df3e71e0SMarcello Maggioni   //
1383df3e71e0SMarcello Maggioni   // Even when the loop is never executed, we cannot remove the edge from the
1384df3e71e0SMarcello Maggioni   // source block to the exit block. Consider the case where the unexecuted loop
1385df3e71e0SMarcello Maggioni   // branches back to an outer loop. If we deleted the loop and removed the edge
1386df3e71e0SMarcello Maggioni   // coming to this inner loop, this will break the outer loop structure (by
1387df3e71e0SMarcello Maggioni   // deleting the backedge of the outer loop). If the outer loop is indeed a
1388df3e71e0SMarcello Maggioni   // non-loop, it will be deleted in a future iteration of loop deletion pass.
1389df3e71e0SMarcello Maggioni   IRBuilder<> Builder(OldBr);
1390df3e71e0SMarcello Maggioni   Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
1391df3e71e0SMarcello Maggioni   // Remove the old branch. The conditional branch becomes a new terminator.
1392df3e71e0SMarcello Maggioni   OldBr->eraseFromParent();
1393df3e71e0SMarcello Maggioni 
1394df3e71e0SMarcello Maggioni   // Rewrite phis in the exit block to get their inputs from the Preheader
1395df3e71e0SMarcello Maggioni   // instead of the exiting block.
1396c7fc81e6SBenjamin Kramer   for (PHINode &P : ExitBlock->phis()) {
1397df3e71e0SMarcello Maggioni     // Set the zero'th element of Phi to be from the preheader and remove all
1398df3e71e0SMarcello Maggioni     // other incoming values. Given the loop has dedicated exits, all other
1399df3e71e0SMarcello Maggioni     // incoming values must be from the exiting blocks.
1400df3e71e0SMarcello Maggioni     int PredIndex = 0;
1401c7fc81e6SBenjamin Kramer     P.setIncomingBlock(PredIndex, Preheader);
1402df3e71e0SMarcello Maggioni     // Removes all incoming values from all other exiting blocks (including
1403df3e71e0SMarcello Maggioni     // duplicate values from an exiting block).
1404df3e71e0SMarcello Maggioni     // Nuke all entries except the zero'th entry which is the preheader entry.
1405df3e71e0SMarcello Maggioni     // NOTE! We need to remove Incoming Values in the reverse order as done
1406df3e71e0SMarcello Maggioni     // below, to keep the indices valid for deletion (removeIncomingValues
1407df3e71e0SMarcello Maggioni     // updates getNumIncomingValues and shifts all values down into the operand
1408df3e71e0SMarcello Maggioni     // being deleted).
1409c7fc81e6SBenjamin Kramer     for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
1410c7fc81e6SBenjamin Kramer       P.removeIncomingValue(e - i, false);
1411df3e71e0SMarcello Maggioni 
1412c7fc81e6SBenjamin Kramer     assert((P.getNumIncomingValues() == 1 &&
1413c7fc81e6SBenjamin Kramer             P.getIncomingBlock(PredIndex) == Preheader) &&
1414df3e71e0SMarcello Maggioni            "Should have exactly one value and that's from the preheader!");
1415df3e71e0SMarcello Maggioni   }
1416df3e71e0SMarcello Maggioni 
1417df3e71e0SMarcello Maggioni   // Disconnect the loop body by branching directly to its exit.
1418df3e71e0SMarcello Maggioni   Builder.SetInsertPoint(Preheader->getTerminator());
1419df3e71e0SMarcello Maggioni   Builder.CreateBr(ExitBlock);
1420df3e71e0SMarcello Maggioni   // Remove the old branch.
1421df3e71e0SMarcello Maggioni   Preheader->getTerminator()->eraseFromParent();
1422df3e71e0SMarcello Maggioni 
1423df3e71e0SMarcello Maggioni   if (DT) {
1424df3e71e0SMarcello Maggioni     // Update the dominator tree by informing it about the new edge from the
1425df3e71e0SMarcello Maggioni     // preheader to the exit.
1426df3e71e0SMarcello Maggioni     DT->insertEdge(Preheader, ExitBlock);
1427df3e71e0SMarcello Maggioni     // Inform the dominator tree about the removed edge.
1428df3e71e0SMarcello Maggioni     DT->deleteEdge(Preheader, L->getHeader());
1429df3e71e0SMarcello Maggioni   }
1430df3e71e0SMarcello Maggioni 
1431a757d65cSSerguei Katkov   // Given LCSSA form is satisfied, we should not have users of instructions
1432a757d65cSSerguei Katkov   // within the dead loop outside of the loop. However, LCSSA doesn't take
1433a757d65cSSerguei Katkov   // unreachable uses into account. We handle them here.
1434a757d65cSSerguei Katkov   // We could do it after drop all references (in this case all users in the
1435a757d65cSSerguei Katkov   // loop will be already eliminated and we have less work to do but according
1436a757d65cSSerguei Katkov   // to API doc of User::dropAllReferences only valid operation after dropping
1437a757d65cSSerguei Katkov   // references, is deletion. So let's substitute all usages of
1438a757d65cSSerguei Katkov   // instruction from the loop with undef value of corresponding type first.
1439a757d65cSSerguei Katkov   for (auto *Block : L->blocks())
1440a757d65cSSerguei Katkov     for (Instruction &I : *Block) {
1441a757d65cSSerguei Katkov       auto *Undef = UndefValue::get(I.getType());
1442a757d65cSSerguei Katkov       for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
1443a757d65cSSerguei Katkov         Use &U = *UI;
1444a757d65cSSerguei Katkov         ++UI;
1445a757d65cSSerguei Katkov         if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
1446a757d65cSSerguei Katkov           if (L->contains(Usr->getParent()))
1447a757d65cSSerguei Katkov             continue;
1448a757d65cSSerguei Katkov         // If we have a DT then we can check that uses outside a loop only in
1449a757d65cSSerguei Katkov         // unreachable block.
1450a757d65cSSerguei Katkov         if (DT)
1451a757d65cSSerguei Katkov           assert(!DT->isReachableFromEntry(U) &&
1452a757d65cSSerguei Katkov                  "Unexpected user in reachable block");
1453a757d65cSSerguei Katkov         U.set(Undef);
1454a757d65cSSerguei Katkov       }
1455a757d65cSSerguei Katkov     }
1456a757d65cSSerguei Katkov 
1457df3e71e0SMarcello Maggioni   // Remove the block from the reference counting scheme, so that we can
1458df3e71e0SMarcello Maggioni   // delete it freely later.
1459df3e71e0SMarcello Maggioni   for (auto *Block : L->blocks())
1460df3e71e0SMarcello Maggioni     Block->dropAllReferences();
1461df3e71e0SMarcello Maggioni 
1462df3e71e0SMarcello Maggioni   if (LI) {
1463df3e71e0SMarcello Maggioni     // Erase the instructions and the blocks without having to worry
1464df3e71e0SMarcello Maggioni     // about ordering because we already dropped the references.
1465df3e71e0SMarcello Maggioni     // NOTE: This iteration is safe because erasing the block does not remove
1466df3e71e0SMarcello Maggioni     // its entry from the loop's block list.  We do that in the next section.
1467df3e71e0SMarcello Maggioni     for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
1468df3e71e0SMarcello Maggioni          LpI != LpE; ++LpI)
1469df3e71e0SMarcello Maggioni       (*LpI)->eraseFromParent();
1470df3e71e0SMarcello Maggioni 
1471df3e71e0SMarcello Maggioni     // Finally, the blocks from loopinfo.  This has to happen late because
1472df3e71e0SMarcello Maggioni     // otherwise our loop iterators won't work.
1473df3e71e0SMarcello Maggioni 
1474df3e71e0SMarcello Maggioni     SmallPtrSet<BasicBlock *, 8> blocks;
1475df3e71e0SMarcello Maggioni     blocks.insert(L->block_begin(), L->block_end());
1476df3e71e0SMarcello Maggioni     for (BasicBlock *BB : blocks)
1477df3e71e0SMarcello Maggioni       LI->removeBlock(BB);
1478df3e71e0SMarcello Maggioni 
1479df3e71e0SMarcello Maggioni     // The last step is to update LoopInfo now that we've eliminated this loop.
1480df3e71e0SMarcello Maggioni     LI->erase(L);
1481df3e71e0SMarcello Maggioni   }
1482df3e71e0SMarcello Maggioni }
1483df3e71e0SMarcello Maggioni 
1484122f984aSEvgeniy Stepanov /// Returns true if the instruction in a loop is guaranteed to execute at least
1485122f984aSEvgeniy Stepanov /// once.
1486122f984aSEvgeniy Stepanov bool llvm::isGuaranteedToExecute(const Instruction &Inst,
1487122f984aSEvgeniy Stepanov                                  const DominatorTree *DT, const Loop *CurLoop,
1488122f984aSEvgeniy Stepanov                                  const LoopSafetyInfo *SafetyInfo) {
1489122f984aSEvgeniy Stepanov   // We have to check to make sure that the instruction dominates all
149058ccc094SEvgeniy Stepanov   // of the exit blocks.  If it doesn't, then there is a path out of the loop
149158ccc094SEvgeniy Stepanov   // which does not execute this instruction, so we can't hoist it.
149258ccc094SEvgeniy Stepanov 
149358ccc094SEvgeniy Stepanov   // If the instruction is in the header block for the loop (which is very
149458ccc094SEvgeniy Stepanov   // common), it is always guaranteed to dominate the exit blocks.  Since this
149558ccc094SEvgeniy Stepanov   // is a common case, and can save some work, check it now.
149658ccc094SEvgeniy Stepanov   if (Inst.getParent() == CurLoop->getHeader())
149758ccc094SEvgeniy Stepanov     // If there's a throw in the header block, we can't guarantee we'll reach
149858ccc094SEvgeniy Stepanov     // Inst.
149958ccc094SEvgeniy Stepanov     return !SafetyInfo->HeaderMayThrow;
150058ccc094SEvgeniy Stepanov 
150158ccc094SEvgeniy Stepanov   // Somewhere in this loop there is an instruction which may throw and make us
150258ccc094SEvgeniy Stepanov   // exit the loop.
150358ccc094SEvgeniy Stepanov   if (SafetyInfo->MayThrow)
1504122f984aSEvgeniy Stepanov     return false;
1505122f984aSEvgeniy Stepanov 
1506122f984aSEvgeniy Stepanov   // Get the exit blocks for the current loop.
1507122f984aSEvgeniy Stepanov   SmallVector<BasicBlock *, 8> ExitBlocks;
1508122f984aSEvgeniy Stepanov   CurLoop->getExitBlocks(ExitBlocks);
1509122f984aSEvgeniy Stepanov 
1510122f984aSEvgeniy Stepanov   // Verify that the block dominates each of the exit blocks of the loop.
1511122f984aSEvgeniy Stepanov   for (BasicBlock *ExitBlock : ExitBlocks)
1512122f984aSEvgeniy Stepanov     if (!DT->dominates(Inst.getParent(), ExitBlock))
1513122f984aSEvgeniy Stepanov       return false;
1514122f984aSEvgeniy Stepanov 
1515122f984aSEvgeniy Stepanov   // As a degenerate case, if the loop is statically infinite then we haven't
1516122f984aSEvgeniy Stepanov   // proven anything since there are no exit blocks.
151758ccc094SEvgeniy Stepanov   if (ExitBlocks.empty())
1518122f984aSEvgeniy Stepanov     return false;
1519122f984aSEvgeniy Stepanov 
1520f1da33e4SEli Friedman   // FIXME: In general, we have to prove that the loop isn't an infinite loop.
1521f1da33e4SEli Friedman   // See http::llvm.org/PR24078 .  (The "ExitBlocks.empty()" check above is
1522f1da33e4SEli Friedman   // just a special case of this.)
1523122f984aSEvgeniy Stepanov   return true;
1524122f984aSEvgeniy Stepanov }
152541d72a86SDehao Chen 
152641d72a86SDehao Chen Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
152741d72a86SDehao Chen   // Only support loops with a unique exiting block, and a latch.
152841d72a86SDehao Chen   if (!L->getExitingBlock())
152941d72a86SDehao Chen     return None;
153041d72a86SDehao Chen 
1531d24ddcd6SHiroshi Inoue   // Get the branch weights for the loop's backedge.
153241d72a86SDehao Chen   BranchInst *LatchBR =
153341d72a86SDehao Chen       dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
153441d72a86SDehao Chen   if (!LatchBR || LatchBR->getNumSuccessors() != 2)
153541d72a86SDehao Chen     return None;
153641d72a86SDehao Chen 
153741d72a86SDehao Chen   assert((LatchBR->getSuccessor(0) == L->getHeader() ||
153841d72a86SDehao Chen           LatchBR->getSuccessor(1) == L->getHeader()) &&
153941d72a86SDehao Chen          "At least one edge out of the latch must go to the header");
154041d72a86SDehao Chen 
154141d72a86SDehao Chen   // To estimate the number of times the loop body was executed, we want to
154241d72a86SDehao Chen   // know the number of times the backedge was taken, vs. the number of times
154341d72a86SDehao Chen   // we exited the loop.
154441d72a86SDehao Chen   uint64_t TrueVal, FalseVal;
1545b151a641SMichael Kuperstein   if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
154641d72a86SDehao Chen     return None;
154741d72a86SDehao Chen 
1548b151a641SMichael Kuperstein   if (!TrueVal || !FalseVal)
1549b151a641SMichael Kuperstein     return 0;
155041d72a86SDehao Chen 
1551b151a641SMichael Kuperstein   // Divide the count of the backedge by the count of the edge exiting the loop,
1552b151a641SMichael Kuperstein   // rounding to nearest.
155341d72a86SDehao Chen   if (LatchBR->getSuccessor(0) == L->getHeader())
1554b151a641SMichael Kuperstein     return (TrueVal + (FalseVal / 2)) / FalseVal;
155541d72a86SDehao Chen   else
1556b151a641SMichael Kuperstein     return (FalseVal + (TrueVal / 2)) / TrueVal;
155741d72a86SDehao Chen }
1558cf9daa33SAmara Emerson 
1559cf9daa33SAmara Emerson /// \brief Adds a 'fast' flag to floating point operations.
1560cf9daa33SAmara Emerson static Value *addFastMathFlag(Value *V) {
1561cf9daa33SAmara Emerson   if (isa<FPMathOperator>(V)) {
1562cf9daa33SAmara Emerson     FastMathFlags Flags;
1563629c4115SSanjay Patel     Flags.setFast();
1564cf9daa33SAmara Emerson     cast<Instruction>(V)->setFastMathFlags(Flags);
1565cf9daa33SAmara Emerson   }
1566cf9daa33SAmara Emerson   return V;
1567cf9daa33SAmara Emerson }
1568cf9daa33SAmara Emerson 
1569cf9daa33SAmara Emerson // Helper to generate a log2 shuffle reduction.
1570836b0f48SAmara Emerson Value *
1571836b0f48SAmara Emerson llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
1572836b0f48SAmara Emerson                           RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
1573836b0f48SAmara Emerson                           ArrayRef<Value *> RedOps) {
1574cf9daa33SAmara Emerson   unsigned VF = Src->getType()->getVectorNumElements();
1575cf9daa33SAmara Emerson   // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
1576cf9daa33SAmara Emerson   // and vector ops, reducing the set of values being computed by half each
1577cf9daa33SAmara Emerson   // round.
1578cf9daa33SAmara Emerson   assert(isPowerOf2_32(VF) &&
1579cf9daa33SAmara Emerson          "Reduction emission only supported for pow2 vectors!");
1580cf9daa33SAmara Emerson   Value *TmpVec = Src;
1581cf9daa33SAmara Emerson   SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
1582cf9daa33SAmara Emerson   for (unsigned i = VF; i != 1; i >>= 1) {
1583cf9daa33SAmara Emerson     // Move the upper half of the vector to the lower half.
1584cf9daa33SAmara Emerson     for (unsigned j = 0; j != i / 2; ++j)
1585cf9daa33SAmara Emerson       ShuffleMask[j] = Builder.getInt32(i / 2 + j);
1586cf9daa33SAmara Emerson 
1587cf9daa33SAmara Emerson     // Fill the rest of the mask with undef.
1588cf9daa33SAmara Emerson     std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
1589cf9daa33SAmara Emerson               UndefValue::get(Builder.getInt32Ty()));
1590cf9daa33SAmara Emerson 
1591cf9daa33SAmara Emerson     Value *Shuf = Builder.CreateShuffleVector(
1592cf9daa33SAmara Emerson         TmpVec, UndefValue::get(TmpVec->getType()),
1593cf9daa33SAmara Emerson         ConstantVector::get(ShuffleMask), "rdx.shuf");
1594cf9daa33SAmara Emerson 
1595cf9daa33SAmara Emerson     if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
1596cf9daa33SAmara Emerson       // Floating point operations had to be 'fast' to enable the reduction.
1597cf9daa33SAmara Emerson       TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
1598cf9daa33SAmara Emerson                                                    TmpVec, Shuf, "bin.rdx"));
1599cf9daa33SAmara Emerson     } else {
1600cf9daa33SAmara Emerson       assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
1601cf9daa33SAmara Emerson              "Invalid min/max");
1602cf9daa33SAmara Emerson       TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind, TmpVec,
1603cf9daa33SAmara Emerson                                                     Shuf);
1604cf9daa33SAmara Emerson     }
1605cf9daa33SAmara Emerson     if (!RedOps.empty())
1606cf9daa33SAmara Emerson       propagateIRFlags(TmpVec, RedOps);
1607cf9daa33SAmara Emerson   }
1608cf9daa33SAmara Emerson   // The result is in the first element of the vector.
1609cf9daa33SAmara Emerson   return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
1610cf9daa33SAmara Emerson }
1611cf9daa33SAmara Emerson 
1612cf9daa33SAmara Emerson /// Create a simple vector reduction specified by an opcode and some
1613cf9daa33SAmara Emerson /// flags (if generating min/max reductions).
1614cf9daa33SAmara Emerson Value *llvm::createSimpleTargetReduction(
1615cf9daa33SAmara Emerson     IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
1616cf9daa33SAmara Emerson     Value *Src, TargetTransformInfo::ReductionFlags Flags,
1617cf9daa33SAmara Emerson     ArrayRef<Value *> RedOps) {
1618cf9daa33SAmara Emerson   assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
1619cf9daa33SAmara Emerson 
1620cf9daa33SAmara Emerson   Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
1621cf9daa33SAmara Emerson   std::function<Value*()> BuildFunc;
1622cf9daa33SAmara Emerson   using RD = RecurrenceDescriptor;
1623cf9daa33SAmara Emerson   RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
1624cf9daa33SAmara Emerson   // TODO: Support creating ordered reductions.
16251ea7b6f7SSanjay Patel   FastMathFlags FMFFast;
16261ea7b6f7SSanjay Patel   FMFFast.setFast();
1627cf9daa33SAmara Emerson 
1628cf9daa33SAmara Emerson   switch (Opcode) {
1629cf9daa33SAmara Emerson   case Instruction::Add:
1630cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
1631cf9daa33SAmara Emerson     break;
1632cf9daa33SAmara Emerson   case Instruction::Mul:
1633cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
1634cf9daa33SAmara Emerson     break;
1635cf9daa33SAmara Emerson   case Instruction::And:
1636cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
1637cf9daa33SAmara Emerson     break;
1638cf9daa33SAmara Emerson   case Instruction::Or:
1639cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
1640cf9daa33SAmara Emerson     break;
1641cf9daa33SAmara Emerson   case Instruction::Xor:
1642cf9daa33SAmara Emerson     BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
1643cf9daa33SAmara Emerson     break;
1644cf9daa33SAmara Emerson   case Instruction::FAdd:
1645cf9daa33SAmara Emerson     BuildFunc = [&]() {
1646cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
16471ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1648cf9daa33SAmara Emerson       return Rdx;
1649cf9daa33SAmara Emerson     };
1650cf9daa33SAmara Emerson     break;
1651cf9daa33SAmara Emerson   case Instruction::FMul:
1652cf9daa33SAmara Emerson     BuildFunc = [&]() {
1653cf9daa33SAmara Emerson       auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
16541ea7b6f7SSanjay Patel       cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
1655cf9daa33SAmara Emerson       return Rdx;
1656cf9daa33SAmara Emerson     };
1657cf9daa33SAmara Emerson     break;
1658cf9daa33SAmara Emerson   case Instruction::ICmp:
1659cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1660cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
1661cf9daa33SAmara Emerson       BuildFunc = [&]() {
1662cf9daa33SAmara Emerson         return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
1663cf9daa33SAmara Emerson       };
1664cf9daa33SAmara Emerson     } else {
1665cf9daa33SAmara Emerson       MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
1666cf9daa33SAmara Emerson       BuildFunc = [&]() {
1667cf9daa33SAmara Emerson         return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
1668cf9daa33SAmara Emerson       };
1669cf9daa33SAmara Emerson     }
1670cf9daa33SAmara Emerson     break;
1671cf9daa33SAmara Emerson   case Instruction::FCmp:
1672cf9daa33SAmara Emerson     if (Flags.IsMaxOp) {
1673cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMax;
1674cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
1675cf9daa33SAmara Emerson     } else {
1676cf9daa33SAmara Emerson       MinMaxKind = RD::MRK_FloatMin;
1677cf9daa33SAmara Emerson       BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
1678cf9daa33SAmara Emerson     }
1679cf9daa33SAmara Emerson     break;
1680cf9daa33SAmara Emerson   default:
1681cf9daa33SAmara Emerson     llvm_unreachable("Unhandled opcode");
1682cf9daa33SAmara Emerson     break;
1683cf9daa33SAmara Emerson   }
1684cf9daa33SAmara Emerson   if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
1685cf9daa33SAmara Emerson     return BuildFunc();
1686cf9daa33SAmara Emerson   return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
1687cf9daa33SAmara Emerson }
1688cf9daa33SAmara Emerson 
1689cf9daa33SAmara Emerson /// Create a vector reduction using a given recurrence descriptor.
16903e069f57SSanjay Patel Value *llvm::createTargetReduction(IRBuilder<> &B,
1691cf9daa33SAmara Emerson                                    const TargetTransformInfo *TTI,
1692cf9daa33SAmara Emerson                                    RecurrenceDescriptor &Desc, Value *Src,
1693cf9daa33SAmara Emerson                                    bool NoNaN) {
1694cf9daa33SAmara Emerson   // TODO: Support in-order reductions based on the recurrence descriptor.
16953e069f57SSanjay Patel   using RD = RecurrenceDescriptor;
16963e069f57SSanjay Patel   RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
1697cf9daa33SAmara Emerson   TargetTransformInfo::ReductionFlags Flags;
1698cf9daa33SAmara Emerson   Flags.NoNaN = NoNaN;
1699cf9daa33SAmara Emerson   switch (RecKind) {
17003e069f57SSanjay Patel   case RD::RK_FloatAdd:
17013e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
17023e069f57SSanjay Patel   case RD::RK_FloatMult:
17033e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
17043e069f57SSanjay Patel   case RD::RK_IntegerAdd:
17053e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
17063e069f57SSanjay Patel   case RD::RK_IntegerMult:
17073e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
17083e069f57SSanjay Patel   case RD::RK_IntegerAnd:
17093e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
17103e069f57SSanjay Patel   case RD::RK_IntegerOr:
17113e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
17123e069f57SSanjay Patel   case RD::RK_IntegerXor:
17133e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
17143e069f57SSanjay Patel   case RD::RK_IntegerMinMax: {
17153e069f57SSanjay Patel     RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
17163e069f57SSanjay Patel     Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
17173e069f57SSanjay Patel     Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
17183e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
1719cf9daa33SAmara Emerson   }
17203e069f57SSanjay Patel   case RD::RK_FloatMinMax: {
17213e069f57SSanjay Patel     Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
17223e069f57SSanjay Patel     return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
1723cf9daa33SAmara Emerson   }
1724cf9daa33SAmara Emerson   default:
1725cf9daa33SAmara Emerson     llvm_unreachable("Unhandled RecKind");
1726cf9daa33SAmara Emerson   }
1727cf9daa33SAmara Emerson }
1728cf9daa33SAmara Emerson 
1729a61f4b89SDinar Temirbulatov void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
1730a61f4b89SDinar Temirbulatov   auto *VecOp = dyn_cast<Instruction>(I);
1731a61f4b89SDinar Temirbulatov   if (!VecOp)
1732a61f4b89SDinar Temirbulatov     return;
1733a61f4b89SDinar Temirbulatov   auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
1734a61f4b89SDinar Temirbulatov                                             : dyn_cast<Instruction>(OpValue);
1735a61f4b89SDinar Temirbulatov   if (!Intersection)
1736a61f4b89SDinar Temirbulatov     return;
1737a61f4b89SDinar Temirbulatov   const unsigned Opcode = Intersection->getOpcode();
1738a61f4b89SDinar Temirbulatov   VecOp->copyIRFlags(Intersection);
1739a61f4b89SDinar Temirbulatov   for (auto *V : VL) {
1740a61f4b89SDinar Temirbulatov     auto *Instr = dyn_cast<Instruction>(V);
1741a61f4b89SDinar Temirbulatov     if (!Instr)
1742a61f4b89SDinar Temirbulatov       continue;
1743a61f4b89SDinar Temirbulatov     if (OpValue == nullptr || Opcode == Instr->getOpcode())
1744a61f4b89SDinar Temirbulatov       VecOp->andIRFlags(V);
1745cf9daa33SAmara Emerson   }
1746cf9daa33SAmara Emerson }
1747