17e98d698SVikram TV //===- llvm/Analysis/IVDescriptors.cpp - IndVar Descriptors -----*- C++ -*-===//
27e98d698SVikram TV //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67e98d698SVikram TV //
77e98d698SVikram TV //===----------------------------------------------------------------------===//
87e98d698SVikram TV //
97e98d698SVikram TV // This file "describes" induction and recurrence variables.
107e98d698SVikram TV //
117e98d698SVikram TV //===----------------------------------------------------------------------===//
127e98d698SVikram TV 
137e98d698SVikram TV #include "llvm/Analysis/IVDescriptors.h"
14a5eb1236SNikita Popov #include "llvm/Analysis/DemandedBits.h"
157e98d698SVikram TV #include "llvm/Analysis/LoopInfo.h"
167e98d698SVikram TV #include "llvm/Analysis/ScalarEvolution.h"
177e98d698SVikram TV #include "llvm/Analysis/ScalarEvolutionExpressions.h"
187e98d698SVikram TV #include "llvm/Analysis/ValueTracking.h"
197e98d698SVikram TV #include "llvm/IR/Dominators.h"
207e98d698SVikram TV #include "llvm/IR/Instructions.h"
217e98d698SVikram TV #include "llvm/IR/Module.h"
227e98d698SVikram TV #include "llvm/IR/PatternMatch.h"
237e98d698SVikram TV #include "llvm/IR/ValueHandle.h"
247e98d698SVikram TV #include "llvm/Support/Debug.h"
257e98d698SVikram TV #include "llvm/Support/KnownBits.h"
267e98d698SVikram TV 
27aa00b1d7SFlorian Hahn #include <set>
28aa00b1d7SFlorian Hahn 
297e98d698SVikram TV using namespace llvm;
307e98d698SVikram TV using namespace llvm::PatternMatch;
317e98d698SVikram TV 
327e98d698SVikram TV #define DEBUG_TYPE "iv-descriptors"
337e98d698SVikram TV 
areAllUsesIn(Instruction * I,SmallPtrSetImpl<Instruction * > & Set)347e98d698SVikram TV bool RecurrenceDescriptor::areAllUsesIn(Instruction *I,
357e98d698SVikram TV                                         SmallPtrSetImpl<Instruction *> &Set) {
3673797367SKazu Hirata   for (const Use &Use : I->operands())
3773797367SKazu Hirata     if (!Set.count(dyn_cast<Instruction>(Use)))
387e98d698SVikram TV       return false;
397e98d698SVikram TV   return true;
407e98d698SVikram TV }
417e98d698SVikram TV 
isIntegerRecurrenceKind(RecurKind Kind)42c74e8539SSanjay Patel bool RecurrenceDescriptor::isIntegerRecurrenceKind(RecurKind Kind) {
437e98d698SVikram TV   switch (Kind) {
447e98d698SVikram TV   default:
457e98d698SVikram TV     break;
46c74e8539SSanjay Patel   case RecurKind::Add:
47c74e8539SSanjay Patel   case RecurKind::Mul:
48c74e8539SSanjay Patel   case RecurKind::Or:
49c74e8539SSanjay Patel   case RecurKind::And:
50c74e8539SSanjay Patel   case RecurKind::Xor:
51c74e8539SSanjay Patel   case RecurKind::SMax:
52c74e8539SSanjay Patel   case RecurKind::SMin:
53c74e8539SSanjay Patel   case RecurKind::UMax:
54c74e8539SSanjay Patel   case RecurKind::UMin:
5526b7d9d6SDavid Sherwood   case RecurKind::SelectICmp:
5626b7d9d6SDavid Sherwood   case RecurKind::SelectFCmp:
577e98d698SVikram TV     return true;
587e98d698SVikram TV   }
597e98d698SVikram TV   return false;
607e98d698SVikram TV }
617e98d698SVikram TV 
isFloatingPointRecurrenceKind(RecurKind Kind)62c74e8539SSanjay Patel bool RecurrenceDescriptor::isFloatingPointRecurrenceKind(RecurKind Kind) {
63c74e8539SSanjay Patel   return (Kind != RecurKind::None) && !isIntegerRecurrenceKind(Kind);
647e98d698SVikram TV }
657e98d698SVikram TV 
667e98d698SVikram TV /// Determines if Phi may have been type-promoted. If Phi has a single user
677e98d698SVikram TV /// that ANDs the Phi with a type mask, return the user. RT is updated to
687e98d698SVikram TV /// account for the narrower bit width represented by the mask, and the AND
697e98d698SVikram TV /// instruction is added to CI.
lookThroughAnd(PHINode * Phi,Type * & RT,SmallPtrSetImpl<Instruction * > & Visited,SmallPtrSetImpl<Instruction * > & CI)707e98d698SVikram TV static Instruction *lookThroughAnd(PHINode *Phi, Type *&RT,
717e98d698SVikram TV                                    SmallPtrSetImpl<Instruction *> &Visited,
727e98d698SVikram TV                                    SmallPtrSetImpl<Instruction *> &CI) {
737e98d698SVikram TV   if (!Phi->hasOneUse())
747e98d698SVikram TV     return Phi;
757e98d698SVikram TV 
767e98d698SVikram TV   const APInt *M = nullptr;
777e98d698SVikram TV   Instruction *I, *J = cast<Instruction>(Phi->use_begin()->getUser());
787e98d698SVikram TV 
797e98d698SVikram TV   // Matches either I & 2^x-1 or 2^x-1 & I. If we find a match, we update RT
807e98d698SVikram TV   // with a new integer type of the corresponding bit width.
817e98d698SVikram TV   if (match(J, m_c_And(m_Instruction(I), m_APInt(M)))) {
827e98d698SVikram TV     int32_t Bits = (*M + 1).exactLogBase2();
837e98d698SVikram TV     if (Bits > 0) {
847e98d698SVikram TV       RT = IntegerType::get(Phi->getContext(), Bits);
857e98d698SVikram TV       Visited.insert(Phi);
867e98d698SVikram TV       CI.insert(J);
877e98d698SVikram TV       return J;
887e98d698SVikram TV     }
897e98d698SVikram TV   }
907e98d698SVikram TV   return Phi;
917e98d698SVikram TV }
927e98d698SVikram TV 
937e98d698SVikram TV /// Compute the minimal bit width needed to represent a reduction whose exit
947e98d698SVikram TV /// instruction is given by Exit.
computeRecurrenceType(Instruction * Exit,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT)957e98d698SVikram TV static std::pair<Type *, bool> computeRecurrenceType(Instruction *Exit,
967e98d698SVikram TV                                                      DemandedBits *DB,
977e98d698SVikram TV                                                      AssumptionCache *AC,
987e98d698SVikram TV                                                      DominatorTree *DT) {
997e98d698SVikram TV   bool IsSigned = false;
1007e98d698SVikram TV   const DataLayout &DL = Exit->getModule()->getDataLayout();
1017e98d698SVikram TV   uint64_t MaxBitWidth = DL.getTypeSizeInBits(Exit->getType());
1027e98d698SVikram TV 
1037e98d698SVikram TV   if (DB) {
1047e98d698SVikram TV     // Use the demanded bits analysis to determine the bits that are live out
1057e98d698SVikram TV     // of the exit instruction, rounding up to the nearest power of two. If the
1067e98d698SVikram TV     // use of demanded bits results in a smaller bit width, we know the value
1077e98d698SVikram TV     // must be positive (i.e., IsSigned = false), because if this were not the
1087e98d698SVikram TV     // case, the sign bit would have been demanded.
1097e98d698SVikram TV     auto Mask = DB->getDemandedBits(Exit);
1107e98d698SVikram TV     MaxBitWidth = Mask.getBitWidth() - Mask.countLeadingZeros();
1117e98d698SVikram TV   }
1127e98d698SVikram TV 
1137e98d698SVikram TV   if (MaxBitWidth == DL.getTypeSizeInBits(Exit->getType()) && AC && DT) {
1147e98d698SVikram TV     // If demanded bits wasn't able to limit the bit width, we can try to use
1157e98d698SVikram TV     // value tracking instead. This can be the case, for example, if the value
1167e98d698SVikram TV     // may be negative.
1177e98d698SVikram TV     auto NumSignBits = ComputeNumSignBits(Exit, DL, 0, AC, nullptr, DT);
1187e98d698SVikram TV     auto NumTypeBits = DL.getTypeSizeInBits(Exit->getType());
1197e98d698SVikram TV     MaxBitWidth = NumTypeBits - NumSignBits;
1207e98d698SVikram TV     KnownBits Bits = computeKnownBits(Exit, DL);
1217e98d698SVikram TV     if (!Bits.isNonNegative()) {
1227e98d698SVikram TV       // If the value is not known to be non-negative, we set IsSigned to true,
1237e98d698SVikram TV       // meaning that we will use sext instructions instead of zext
1247e98d698SVikram TV       // instructions to restore the original type.
1257e98d698SVikram TV       IsSigned = true;
126112c1c34SFlorian Hahn       // Make sure at at least one sign bit is included in the result, so it
127112c1c34SFlorian Hahn       // will get properly sign-extended.
1287e98d698SVikram TV       ++MaxBitWidth;
1297e98d698SVikram TV     }
1307e98d698SVikram TV   }
1317e98d698SVikram TV   if (!isPowerOf2_64(MaxBitWidth))
1327e98d698SVikram TV     MaxBitWidth = NextPowerOf2(MaxBitWidth);
1337e98d698SVikram TV 
1347e98d698SVikram TV   return std::make_pair(Type::getIntNTy(Exit->getContext(), MaxBitWidth),
1357e98d698SVikram TV                         IsSigned);
1367e98d698SVikram TV }
1377e98d698SVikram TV 
1387e98d698SVikram TV /// Collect cast instructions that can be ignored in the vectorizer's cost
1397e98d698SVikram TV /// model, given a reduction exit value and the minimal type in which the
140961f51fdSRosie Sumpter // reduction can be represented. Also search casts to the recurrence type
141961f51fdSRosie Sumpter // to find the minimum width used by the recurrence.
collectCastInstrs(Loop * TheLoop,Instruction * Exit,Type * RecurrenceType,SmallPtrSetImpl<Instruction * > & Casts,unsigned & MinWidthCastToRecurTy)142961f51fdSRosie Sumpter static void collectCastInstrs(Loop *TheLoop, Instruction *Exit,
1437e98d698SVikram TV                               Type *RecurrenceType,
144961f51fdSRosie Sumpter                               SmallPtrSetImpl<Instruction *> &Casts,
145961f51fdSRosie Sumpter                               unsigned &MinWidthCastToRecurTy) {
1467e98d698SVikram TV 
1477e98d698SVikram TV   SmallVector<Instruction *, 8> Worklist;
1487e98d698SVikram TV   SmallPtrSet<Instruction *, 8> Visited;
1497e98d698SVikram TV   Worklist.push_back(Exit);
150961f51fdSRosie Sumpter   MinWidthCastToRecurTy = -1U;
1517e98d698SVikram TV 
1527e98d698SVikram TV   while (!Worklist.empty()) {
1537e98d698SVikram TV     Instruction *Val = Worklist.pop_back_val();
1547e98d698SVikram TV     Visited.insert(Val);
155961f51fdSRosie Sumpter     if (auto *Cast = dyn_cast<CastInst>(Val)) {
1567e98d698SVikram TV       if (Cast->getSrcTy() == RecurrenceType) {
1577e98d698SVikram TV         // If the source type of a cast instruction is equal to the recurrence
1587e98d698SVikram TV         // type, it will be eliminated, and should be ignored in the vectorizer
1597e98d698SVikram TV         // cost model.
1607e98d698SVikram TV         Casts.insert(Cast);
1617e98d698SVikram TV         continue;
1627e98d698SVikram TV       }
163961f51fdSRosie Sumpter       if (Cast->getDestTy() == RecurrenceType) {
164961f51fdSRosie Sumpter         // The minimum width used by the recurrence is found by checking for
165961f51fdSRosie Sumpter         // casts on its operands. The minimum width is used by the vectorizer
166961f51fdSRosie Sumpter         // when finding the widest type for in-loop reductions without any
167961f51fdSRosie Sumpter         // loads/stores.
168961f51fdSRosie Sumpter         MinWidthCastToRecurTy = std::min<unsigned>(
169961f51fdSRosie Sumpter             MinWidthCastToRecurTy, Cast->getSrcTy()->getScalarSizeInBits());
170961f51fdSRosie Sumpter         continue;
171961f51fdSRosie Sumpter       }
172961f51fdSRosie Sumpter     }
1737e98d698SVikram TV     // Add all operands to the work list if they are loop-varying values that
1747e98d698SVikram TV     // we haven't yet visited.
1757e98d698SVikram TV     for (Value *O : cast<User>(Val)->operands())
1767e98d698SVikram TV       if (auto *I = dyn_cast<Instruction>(O))
1777e98d698SVikram TV         if (TheLoop->contains(I) && !Visited.count(I))
1787e98d698SVikram TV           Worklist.push_back(I);
1797e98d698SVikram TV   }
1807e98d698SVikram TV }
1817e98d698SVikram TV 
1827344f3d3SKerry McLaughlin // Check if a given Phi node can be recognized as an ordered reduction for
1837344f3d3SKerry McLaughlin // vectorizing floating point operations without unsafe math.
checkOrderedReduction(RecurKind Kind,Instruction * ExactFPMathInst,Instruction * Exit,PHINode * Phi)1847344f3d3SKerry McLaughlin static bool checkOrderedReduction(RecurKind Kind, Instruction *ExactFPMathInst,
1857344f3d3SKerry McLaughlin                                   Instruction *Exit, PHINode *Phi) {
186c2441b6bSRosie Sumpter   // Currently only FAdd and FMulAdd are supported.
187c2441b6bSRosie Sumpter   if (Kind != RecurKind::FAdd && Kind != RecurKind::FMulAdd)
1887344f3d3SKerry McLaughlin     return false;
1897344f3d3SKerry McLaughlin 
190c2441b6bSRosie Sumpter   if (Kind == RecurKind::FAdd && Exit->getOpcode() != Instruction::FAdd)
191c2441b6bSRosie Sumpter     return false;
192c2441b6bSRosie Sumpter 
193c2441b6bSRosie Sumpter   if (Kind == RecurKind::FMulAdd &&
194c2441b6bSRosie Sumpter       !RecurrenceDescriptor::isFMulAddIntrinsic(Exit))
195c2441b6bSRosie Sumpter     return false;
196c2441b6bSRosie Sumpter 
197c2441b6bSRosie Sumpter   // Ensure the exit instruction has only one user other than the reduction PHI
198c2441b6bSRosie Sumpter   if (Exit != ExactFPMathInst || Exit->hasNUsesOrMore(3))
19968ffed12SAnna Thomas     return false;
2007344f3d3SKerry McLaughlin 
2017344f3d3SKerry McLaughlin   // The only pattern accepted is the one in which the reduction PHI
2027344f3d3SKerry McLaughlin   // is used as one of the operands of the exit instruction
203c2441b6bSRosie Sumpter   auto *Op0 = Exit->getOperand(0);
204c2441b6bSRosie Sumpter   auto *Op1 = Exit->getOperand(1);
205c2441b6bSRosie Sumpter   if (Kind == RecurKind::FAdd && Op0 != Phi && Op1 != Phi)
206c2441b6bSRosie Sumpter     return false;
207c2441b6bSRosie Sumpter   if (Kind == RecurKind::FMulAdd && Exit->getOperand(2) != Phi)
2087344f3d3SKerry McLaughlin     return false;
2097344f3d3SKerry McLaughlin 
2107344f3d3SKerry McLaughlin   LLVM_DEBUG(dbgs() << "LV: Found an ordered reduction: Phi: " << *Phi
2117344f3d3SKerry McLaughlin                     << ", ExitInst: " << *Exit << "\n");
2127344f3d3SKerry McLaughlin 
2137344f3d3SKerry McLaughlin   return true;
2147344f3d3SKerry McLaughlin }
2157344f3d3SKerry McLaughlin 
AddReductionVar(PHINode * Phi,RecurKind Kind,Loop * TheLoop,FastMathFlags FuncFMF,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE)2164e5e042dSIgor Kirillov bool RecurrenceDescriptor::AddReductionVar(
2174e5e042dSIgor Kirillov     PHINode *Phi, RecurKind Kind, Loop *TheLoop, FastMathFlags FuncFMF,
2184e5e042dSIgor Kirillov     RecurrenceDescriptor &RedDes, DemandedBits *DB, AssumptionCache *AC,
2194e5e042dSIgor Kirillov     DominatorTree *DT, ScalarEvolution *SE) {
2207e98d698SVikram TV   if (Phi->getNumIncomingValues() != 2)
2217e98d698SVikram TV     return false;
2227e98d698SVikram TV 
2237e98d698SVikram TV   // Reduction variables are only found in the loop header block.
2247e98d698SVikram TV   if (Phi->getParent() != TheLoop->getHeader())
2257e98d698SVikram TV     return false;
2267e98d698SVikram TV 
2277e98d698SVikram TV   // Obtain the reduction start value from the value that comes from the loop
2287e98d698SVikram TV   // preheader.
2297e98d698SVikram TV   Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
2307e98d698SVikram TV 
2317e98d698SVikram TV   // ExitInstruction is the single value which is used outside the loop.
2327e98d698SVikram TV   // We only allow for a single reduction value to be used outside the loop.
2337e98d698SVikram TV   // This includes users of the reduction, variables (which form a cycle
2347e98d698SVikram TV   // which ends in the phi node).
2357e98d698SVikram TV   Instruction *ExitInstruction = nullptr;
2364e5e042dSIgor Kirillov 
2374e5e042dSIgor Kirillov   // Variable to keep last visited store instruction. By the end of the
2384e5e042dSIgor Kirillov   // algorithm this variable will be either empty or having intermediate
2394e5e042dSIgor Kirillov   // reduction value stored in invariant address.
2404e5e042dSIgor Kirillov   StoreInst *IntermediateStore = nullptr;
2414e5e042dSIgor Kirillov 
2427e98d698SVikram TV   // Indicates that we found a reduction operation in our scan.
2437e98d698SVikram TV   bool FoundReduxOp = false;
2447e98d698SVikram TV 
2457e98d698SVikram TV   // We start with the PHI node and scan for all of the users of this
2467e98d698SVikram TV   // instruction. All users must be instructions that can be used as reduction
2477e98d698SVikram TV   // variables (such as ADD). We must have a single out-of-block user. The cycle
2487e98d698SVikram TV   // must include the original PHI.
2497e98d698SVikram TV   bool FoundStartPHI = false;
2507e98d698SVikram TV 
2517e98d698SVikram TV   // To recognize min/max patterns formed by a icmp select sequence, we store
2527e98d698SVikram TV   // the number of instruction we saw from the recognized min/max pattern,
2537e98d698SVikram TV   //  to make sure we only see exactly the two instructions.
2547e98d698SVikram TV   unsigned NumCmpSelectPatternInst = 0;
2557e98d698SVikram TV   InstDesc ReduxDesc(false, nullptr);
2567e98d698SVikram TV 
2577e98d698SVikram TV   // Data used for determining if the recurrence has been type-promoted.
2587e98d698SVikram TV   Type *RecurrenceType = Phi->getType();
2597e98d698SVikram TV   SmallPtrSet<Instruction *, 4> CastInsts;
260961f51fdSRosie Sumpter   unsigned MinWidthCastToRecurrenceType;
2617e98d698SVikram TV   Instruction *Start = Phi;
2627e98d698SVikram TV   bool IsSigned = false;
2637e98d698SVikram TV 
2647e98d698SVikram TV   SmallPtrSet<Instruction *, 8> VisitedInsts;
2657e98d698SVikram TV   SmallVector<Instruction *, 8> Worklist;
2667e98d698SVikram TV 
2677e98d698SVikram TV   // Return early if the recurrence kind does not match the type of Phi. If the
2687e98d698SVikram TV   // recurrence kind is arithmetic, we attempt to look through AND operations
2697e98d698SVikram TV   // resulting from the type promotion performed by InstCombine.  Vector
2707e98d698SVikram TV   // operations are not limited to the legal integer widths, so we may be able
2717e98d698SVikram TV   // to evaluate the reduction in the narrower width.
2727e98d698SVikram TV   if (RecurrenceType->isFloatingPointTy()) {
2737e98d698SVikram TV     if (!isFloatingPointRecurrenceKind(Kind))
2747e98d698SVikram TV       return false;
2755b250a27SSanjay Patel   } else if (RecurrenceType->isIntegerTy()) {
2767e98d698SVikram TV     if (!isIntegerRecurrenceKind(Kind))
2777e98d698SVikram TV       return false;
2789d355949SKerry McLaughlin     if (!isMinMaxRecurrenceKind(Kind))
2797e98d698SVikram TV       Start = lookThroughAnd(Phi, RecurrenceType, VisitedInsts, CastInsts);
2805b250a27SSanjay Patel   } else {
2815b250a27SSanjay Patel     // Pointer min/max may exist, but it is not supported as a reduction op.
2825b250a27SSanjay Patel     return false;
2837e98d698SVikram TV   }
2847e98d698SVikram TV 
2857e98d698SVikram TV   Worklist.push_back(Start);
2867e98d698SVikram TV   VisitedInsts.insert(Start);
2877e98d698SVikram TV 
2883f5ce186SSanjoy Das   // Start with all flags set because we will intersect this with the reduction
2893f5ce186SSanjoy Das   // flags from all the reduction operations.
2903f5ce186SSanjoy Das   FastMathFlags FMF = FastMathFlags::getFast();
2913f5ce186SSanjoy Das 
292f3e1f443SCongzhe Cao   // The first instruction in the use-def chain of the Phi node that requires
293f3e1f443SCongzhe Cao   // exact floating point operations.
294f3e1f443SCongzhe Cao   Instruction *ExactFPMathInst = nullptr;
295f3e1f443SCongzhe Cao 
2967e98d698SVikram TV   // A value in the reduction can be used:
2977e98d698SVikram TV   //  - By the reduction:
2987e98d698SVikram TV   //      - Reduction operation:
2997e98d698SVikram TV   //        - One use of reduction value (safe).
3007e98d698SVikram TV   //        - Multiple use of reduction value (not safe).
3017e98d698SVikram TV   //      - PHI:
3027e98d698SVikram TV   //        - All uses of the PHI must be the reduction (safe).
3037e98d698SVikram TV   //        - Otherwise, not safe.
3047e98d698SVikram TV   //  - By instructions outside of the loop (safe).
3057e98d698SVikram TV   //      * One value may have several outside users, but all outside
3067e98d698SVikram TV   //        uses must be of the same value.
3074e5e042dSIgor Kirillov   //  - By store instructions with a loop invariant address (safe with
3084e5e042dSIgor Kirillov   //    the following restrictions):
3094e5e042dSIgor Kirillov   //      * If there are several stores, all must have the same address.
3104e5e042dSIgor Kirillov   //      * Final value should be stored in that loop invariant address.
3117e98d698SVikram TV   //  - By an instruction that is not part of the reduction (not safe).
3127e98d698SVikram TV   //    This is either:
3137e98d698SVikram TV   //      * An instruction type other than PHI or the reduction operation.
3147e98d698SVikram TV   //      * A PHI in the header other than the initial PHI.
3157e98d698SVikram TV   while (!Worklist.empty()) {
31616baad8fSKazu Hirata     Instruction *Cur = Worklist.pop_back_val();
3177e98d698SVikram TV 
3184e5e042dSIgor Kirillov     // Store instructions are allowed iff it is the store of the reduction
3194e5e042dSIgor Kirillov     // value to the same loop invariant memory location.
3204e5e042dSIgor Kirillov     if (auto *SI = dyn_cast<StoreInst>(Cur)) {
3214e5e042dSIgor Kirillov       if (!SE) {
3224e5e042dSIgor Kirillov         LLVM_DEBUG(dbgs() << "Store instructions are not processed without "
3234e5e042dSIgor Kirillov                           << "Scalar Evolution Analysis\n");
3244e5e042dSIgor Kirillov         return false;
3254e5e042dSIgor Kirillov       }
3264e5e042dSIgor Kirillov 
3274e5e042dSIgor Kirillov       const SCEV *PtrScev = SE->getSCEV(SI->getPointerOperand());
3284e5e042dSIgor Kirillov       // Check it is the same address as previous stores
3294e5e042dSIgor Kirillov       if (IntermediateStore) {
3304e5e042dSIgor Kirillov         const SCEV *OtherScev =
3314e5e042dSIgor Kirillov             SE->getSCEV(IntermediateStore->getPointerOperand());
3324e5e042dSIgor Kirillov 
3334e5e042dSIgor Kirillov         if (OtherScev != PtrScev) {
3344e5e042dSIgor Kirillov           LLVM_DEBUG(dbgs() << "Storing reduction value to different addresses "
3354e5e042dSIgor Kirillov                             << "inside the loop: " << *SI->getPointerOperand()
3364e5e042dSIgor Kirillov                             << " and "
3374e5e042dSIgor Kirillov                             << *IntermediateStore->getPointerOperand() << '\n');
3384e5e042dSIgor Kirillov           return false;
3394e5e042dSIgor Kirillov         }
3404e5e042dSIgor Kirillov       }
3414e5e042dSIgor Kirillov 
3424e5e042dSIgor Kirillov       // Check the pointer is loop invariant
3434e5e042dSIgor Kirillov       if (!SE->isLoopInvariant(PtrScev, TheLoop)) {
3444e5e042dSIgor Kirillov         LLVM_DEBUG(dbgs() << "Storing reduction value to non-uniform address "
3454e5e042dSIgor Kirillov                           << "inside the loop: " << *SI->getPointerOperand()
3464e5e042dSIgor Kirillov                           << '\n');
3474e5e042dSIgor Kirillov         return false;
3484e5e042dSIgor Kirillov       }
3494e5e042dSIgor Kirillov 
3504e5e042dSIgor Kirillov       // IntermediateStore is always the last store in the loop.
3514e5e042dSIgor Kirillov       IntermediateStore = SI;
3524e5e042dSIgor Kirillov       continue;
3534e5e042dSIgor Kirillov     }
3544e5e042dSIgor Kirillov 
3557e98d698SVikram TV     // No Users.
3567e98d698SVikram TV     // If the instruction has no users then this is a broken chain and can't be
3577e98d698SVikram TV     // a reduction variable.
3587e98d698SVikram TV     if (Cur->use_empty())
3597e98d698SVikram TV       return false;
3607e98d698SVikram TV 
3617e98d698SVikram TV     bool IsAPhi = isa<PHINode>(Cur);
3627e98d698SVikram TV 
3637e98d698SVikram TV     // A header PHI use other than the original PHI.
3647e98d698SVikram TV     if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
3657e98d698SVikram TV       return false;
3667e98d698SVikram TV 
3677e98d698SVikram TV     // Reductions of instructions such as Div, and Sub is only possible if the
3687e98d698SVikram TV     // LHS is the reduction variable.
3697e98d698SVikram TV     if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
3707e98d698SVikram TV         !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
3717e98d698SVikram TV         !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
3727e98d698SVikram TV       return false;
3737e98d698SVikram TV 
3747e98d698SVikram TV     // Any reduction instruction must be of one of the allowed kinds. We ignore
3757e98d698SVikram TV     // the starting value (the Phi or an AND instruction if the Phi has been
3767e98d698SVikram TV     // type-promoted).
3777e98d698SVikram TV     if (Cur != Start) {
37826b7d9d6SDavid Sherwood       ReduxDesc =
37926b7d9d6SDavid Sherwood           isRecurrenceInstr(TheLoop, Phi, Cur, Kind, ReduxDesc, FuncFMF);
380f3e1f443SCongzhe Cao       ExactFPMathInst = ExactFPMathInst == nullptr
381f3e1f443SCongzhe Cao                             ? ReduxDesc.getExactFPMathInst()
382f3e1f443SCongzhe Cao                             : ExactFPMathInst;
3837e98d698SVikram TV       if (!ReduxDesc.isRecurrence())
3847e98d698SVikram TV         return false;
3856d4ea22eSSanjay Patel       // FIXME: FMF is allowed on phi, but propagation is not handled correctly.
386bbed5f2fSSanjay Patel       if (isa<FPMathOperator>(ReduxDesc.getPatternInst()) && !IsAPhi) {
387bbed5f2fSSanjay Patel         FastMathFlags CurFMF = ReduxDesc.getPatternInst()->getFastMathFlags();
388bbed5f2fSSanjay Patel         if (auto *Sel = dyn_cast<SelectInst>(ReduxDesc.getPatternInst())) {
389bbed5f2fSSanjay Patel           // Accept FMF on either fcmp or select of a min/max idiom.
390bbed5f2fSSanjay Patel           // TODO: This is a hack to work-around the fact that FMF may not be
391bbed5f2fSSanjay Patel           //       assigned/propagated correctly. If that problem is fixed or we
392bbed5f2fSSanjay Patel           //       standardize on fmin/fmax via intrinsics, this can be removed.
3930fa61304SFangrui Song           if (auto *FCmp = dyn_cast<FCmpInst>(Sel->getCondition()))
3940fa61304SFangrui Song             CurFMF |= FCmp->getFastMathFlags();
395bbed5f2fSSanjay Patel         }
396bbed5f2fSSanjay Patel         FMF &= CurFMF;
397bbed5f2fSSanjay Patel       }
398c74e8539SSanjay Patel       // Update this reduction kind if we matched a new instruction.
399c74e8539SSanjay Patel       // TODO: Can we eliminate the need for a 2nd InstDesc by keeping 'Kind'
400c74e8539SSanjay Patel       //       state accurate while processing the worklist?
401c74e8539SSanjay Patel       if (ReduxDesc.getRecKind() != RecurKind::None)
402c74e8539SSanjay Patel         Kind = ReduxDesc.getRecKind();
4037e98d698SVikram TV     }
4047e98d698SVikram TV 
405135e72e1SRenato Golin     bool IsASelect = isa<SelectInst>(Cur);
406135e72e1SRenato Golin 
407135e72e1SRenato Golin     // A conditional reduction operation must only have 2 or less uses in
408135e72e1SRenato Golin     // VisitedInsts.
409c74e8539SSanjay Patel     if (IsASelect && (Kind == RecurKind::FAdd || Kind == RecurKind::FMul) &&
410135e72e1SRenato Golin         hasMultipleUsesOf(Cur, VisitedInsts, 2))
411135e72e1SRenato Golin       return false;
412135e72e1SRenato Golin 
4137e98d698SVikram TV     // A reduction operation must only have one use of the reduction value.
414c74e8539SSanjay Patel     if (!IsAPhi && !IsASelect && !isMinMaxRecurrenceKind(Kind) &&
41526b7d9d6SDavid Sherwood         !isSelectCmpRecurrenceKind(Kind) &&
416c74e8539SSanjay Patel         hasMultipleUsesOf(Cur, VisitedInsts, 1))
4177e98d698SVikram TV       return false;
4187e98d698SVikram TV 
4197e98d698SVikram TV     // All inputs to a PHI node must be a reduction value.
4207e98d698SVikram TV     if (IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
4217e98d698SVikram TV       return false;
4227e98d698SVikram TV 
42326b7d9d6SDavid Sherwood     if ((isIntMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectICmp) &&
4247e98d698SVikram TV         (isa<ICmpInst>(Cur) || isa<SelectInst>(Cur)))
4257e98d698SVikram TV       ++NumCmpSelectPatternInst;
42626b7d9d6SDavid Sherwood     if ((isFPMinMaxRecurrenceKind(Kind) || Kind == RecurKind::SelectFCmp) &&
427c74e8539SSanjay Patel         (isa<FCmpInst>(Cur) || isa<SelectInst>(Cur)))
4287e98d698SVikram TV       ++NumCmpSelectPatternInst;
4297e98d698SVikram TV 
4307e98d698SVikram TV     // Check  whether we found a reduction operator.
4317e98d698SVikram TV     FoundReduxOp |= !IsAPhi && Cur != Start;
4327e98d698SVikram TV 
4337e98d698SVikram TV     // Process users of current instruction. Push non-PHI nodes after PHI nodes
4347e98d698SVikram TV     // onto the stack. This way we are going to have seen all inputs to PHI
4357e98d698SVikram TV     // nodes once we get to them.
4367e98d698SVikram TV     SmallVector<Instruction *, 8> NonPHIs;
4377e98d698SVikram TV     SmallVector<Instruction *, 8> PHIs;
4387e98d698SVikram TV     for (User *U : Cur->users()) {
4397e98d698SVikram TV       Instruction *UI = cast<Instruction>(U);
4407e98d698SVikram TV 
441c2441b6bSRosie Sumpter       // If the user is a call to llvm.fmuladd then the instruction can only be
442c2441b6bSRosie Sumpter       // the final operand.
443c2441b6bSRosie Sumpter       if (isFMulAddIntrinsic(UI))
444c2441b6bSRosie Sumpter         if (Cur == UI->getOperand(0) || Cur == UI->getOperand(1))
445c2441b6bSRosie Sumpter           return false;
446c2441b6bSRosie Sumpter 
4477e98d698SVikram TV       // Check if we found the exit user.
4487e98d698SVikram TV       BasicBlock *Parent = UI->getParent();
4497e98d698SVikram TV       if (!TheLoop->contains(Parent)) {
4507e98d698SVikram TV         // If we already know this instruction is used externally, move on to
4517e98d698SVikram TV         // the next user.
4527e98d698SVikram TV         if (ExitInstruction == Cur)
4537e98d698SVikram TV           continue;
4547e98d698SVikram TV 
4557e98d698SVikram TV         // Exit if you find multiple values used outside or if the header phi
4567e98d698SVikram TV         // node is being used. In this case the user uses the value of the
4577e98d698SVikram TV         // previous iteration, in which case we would loose "VF-1" iterations of
4587e98d698SVikram TV         // the reduction operation if we vectorize.
4597e98d698SVikram TV         if (ExitInstruction != nullptr || Cur == Phi)
4607e98d698SVikram TV           return false;
4617e98d698SVikram TV 
4627e98d698SVikram TV         // The instruction used by an outside user must be the last instruction
4637e98d698SVikram TV         // before we feed back to the reduction phi. Otherwise, we loose VF-1
4647e98d698SVikram TV         // operations on the value.
4657e98d698SVikram TV         if (!is_contained(Phi->operands(), Cur))
4667e98d698SVikram TV           return false;
4677e98d698SVikram TV 
4687e98d698SVikram TV         ExitInstruction = Cur;
4697e98d698SVikram TV         continue;
4707e98d698SVikram TV       }
4717e98d698SVikram TV 
4727e98d698SVikram TV       // Process instructions only once (termination). Each reduction cycle
4737e98d698SVikram TV       // value must only be used once, except by phi nodes and min/max
4747e98d698SVikram TV       // reductions which are represented as a cmp followed by a select.
4757e98d698SVikram TV       InstDesc IgnoredVal(false, nullptr);
4767e98d698SVikram TV       if (VisitedInsts.insert(UI).second) {
4774e5e042dSIgor Kirillov         if (isa<PHINode>(UI)) {
4787e98d698SVikram TV           PHIs.push_back(UI);
4794e5e042dSIgor Kirillov         } else {
4804e5e042dSIgor Kirillov           StoreInst *SI = dyn_cast<StoreInst>(UI);
4814e5e042dSIgor Kirillov           if (SI && SI->getPointerOperand() == Cur) {
4824e5e042dSIgor Kirillov             // Reduction variable chain can only be stored somewhere but it
4834e5e042dSIgor Kirillov             // can't be used as an address.
4844e5e042dSIgor Kirillov             return false;
4854e5e042dSIgor Kirillov           }
4867e98d698SVikram TV           NonPHIs.push_back(UI);
4874e5e042dSIgor Kirillov         }
4887e98d698SVikram TV       } else if (!isa<PHINode>(UI) &&
4897e98d698SVikram TV                  ((!isa<FCmpInst>(UI) && !isa<ICmpInst>(UI) &&
4907e98d698SVikram TV                    !isa<SelectInst>(UI)) ||
491135e72e1SRenato Golin                   (!isConditionalRdxPattern(Kind, UI).isRecurrence() &&
49226b7d9d6SDavid Sherwood                    !isSelectCmpPattern(TheLoop, Phi, UI, IgnoredVal)
49326b7d9d6SDavid Sherwood                         .isRecurrence() &&
49426b7d9d6SDavid Sherwood                    !isMinMaxPattern(UI, Kind, IgnoredVal).isRecurrence())))
4957e98d698SVikram TV         return false;
4967e98d698SVikram TV 
4977e98d698SVikram TV       // Remember that we completed the cycle.
4987e98d698SVikram TV       if (UI == Phi)
4997e98d698SVikram TV         FoundStartPHI = true;
5007e98d698SVikram TV     }
5017e98d698SVikram TV     Worklist.append(PHIs.begin(), PHIs.end());
5027e98d698SVikram TV     Worklist.append(NonPHIs.begin(), NonPHIs.end());
5037e98d698SVikram TV   }
5047e98d698SVikram TV 
5057e98d698SVikram TV   // This means we have seen one but not the other instruction of the
50661cc873aSDavid Green   // pattern or more than just a select and cmp. Zero implies that we saw a
5079727c77dSDavid Green   // llvm.min/max intrinsic, which is always OK.
50861cc873aSDavid Green   if (isMinMaxRecurrenceKind(Kind) && NumCmpSelectPatternInst != 2 &&
50961cc873aSDavid Green       NumCmpSelectPatternInst != 0)
5107e98d698SVikram TV     return false;
5117e98d698SVikram TV 
51226b7d9d6SDavid Sherwood   if (isSelectCmpRecurrenceKind(Kind) && NumCmpSelectPatternInst != 1)
51326b7d9d6SDavid Sherwood     return false;
51426b7d9d6SDavid Sherwood 
5154e5e042dSIgor Kirillov   if (IntermediateStore) {
5164e5e042dSIgor Kirillov     // Check that stored value goes to the phi node again. This way we make sure
5174e5e042dSIgor Kirillov     // that the value stored in IntermediateStore is indeed the final reduction
5184e5e042dSIgor Kirillov     // value.
5194e5e042dSIgor Kirillov     if (!is_contained(Phi->operands(), IntermediateStore->getValueOperand())) {
5204e5e042dSIgor Kirillov       LLVM_DEBUG(dbgs() << "Not a final reduction value stored: "
5214e5e042dSIgor Kirillov                         << *IntermediateStore << '\n');
5224e5e042dSIgor Kirillov       return false;
5234e5e042dSIgor Kirillov     }
5244e5e042dSIgor Kirillov 
5254e5e042dSIgor Kirillov     // If there is an exit instruction it's value should be stored in
5264e5e042dSIgor Kirillov     // IntermediateStore
5274e5e042dSIgor Kirillov     if (ExitInstruction &&
5284e5e042dSIgor Kirillov         IntermediateStore->getValueOperand() != ExitInstruction) {
5294e5e042dSIgor Kirillov       LLVM_DEBUG(dbgs() << "Last store Instruction of reduction value does not "
5304e5e042dSIgor Kirillov                            "store last calculated value of the reduction: "
5314e5e042dSIgor Kirillov                         << *IntermediateStore << '\n');
5324e5e042dSIgor Kirillov       return false;
5334e5e042dSIgor Kirillov     }
5344e5e042dSIgor Kirillov 
5354e5e042dSIgor Kirillov     // If all uses are inside the loop (intermediate stores), then the
5364e5e042dSIgor Kirillov     // reduction value after the loop will be the one used in the last store.
5374e5e042dSIgor Kirillov     if (!ExitInstruction)
5384e5e042dSIgor Kirillov       ExitInstruction = cast<Instruction>(IntermediateStore->getValueOperand());
5394e5e042dSIgor Kirillov   }
5404e5e042dSIgor Kirillov 
5417e98d698SVikram TV   if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
5427e98d698SVikram TV     return false;
5437e98d698SVikram TV 
544f3e1f443SCongzhe Cao   const bool IsOrdered =
545f3e1f443SCongzhe Cao       checkOrderedReduction(Kind, ExactFPMathInst, ExitInstruction, Phi);
5467344f3d3SKerry McLaughlin 
5477e98d698SVikram TV   if (Start != Phi) {
5487e98d698SVikram TV     // If the starting value is not the same as the phi node, we speculatively
5497e98d698SVikram TV     // looked through an 'and' instruction when evaluating a potential
5507e98d698SVikram TV     // arithmetic reduction to determine if it may have been type-promoted.
5517e98d698SVikram TV     //
5527e98d698SVikram TV     // We now compute the minimal bit width that is required to represent the
5537e98d698SVikram TV     // reduction. If this is the same width that was indicated by the 'and', we
5547e98d698SVikram TV     // can represent the reduction in the smaller type. The 'and' instruction
5557e98d698SVikram TV     // will be eliminated since it will essentially be a cast instruction that
5567e98d698SVikram TV     // can be ignore in the cost model. If we compute a different type than we
5577e98d698SVikram TV     // did when evaluating the 'and', the 'and' will not be eliminated, and we
5587e98d698SVikram TV     // will end up with different kinds of operations in the recurrence
559c74e8539SSanjay Patel     // expression (e.g., IntegerAND, IntegerADD). We give up if this is
5607e98d698SVikram TV     // the case.
5617e98d698SVikram TV     //
5627e98d698SVikram TV     // The vectorizer relies on InstCombine to perform the actual
5637e98d698SVikram TV     // type-shrinking. It does this by inserting instructions to truncate the
5647e98d698SVikram TV     // exit value of the reduction to the width indicated by RecurrenceType and
5657e98d698SVikram TV     // then extend this value back to the original width. If IsSigned is false,
5667e98d698SVikram TV     // a 'zext' instruction will be generated; otherwise, a 'sext' will be
5677e98d698SVikram TV     // used.
5687e98d698SVikram TV     //
5697e98d698SVikram TV     // TODO: We should not rely on InstCombine to rewrite the reduction in the
5707e98d698SVikram TV     //       smaller type. We should just generate a correctly typed expression
5717e98d698SVikram TV     //       to begin with.
5727e98d698SVikram TV     Type *ComputedType;
5737e98d698SVikram TV     std::tie(ComputedType, IsSigned) =
5747e98d698SVikram TV         computeRecurrenceType(ExitInstruction, DB, AC, DT);
5757e98d698SVikram TV     if (ComputedType != RecurrenceType)
5767e98d698SVikram TV       return false;
577961f51fdSRosie Sumpter   }
5787e98d698SVikram TV 
579961f51fdSRosie Sumpter   // Collect cast instructions and the minimum width used by the recurrence.
580961f51fdSRosie Sumpter   // If the starting value is not the same as the phi node and the computed
581961f51fdSRosie Sumpter   // recurrence type is equal to the recurrence type, the recurrence expression
582961f51fdSRosie Sumpter   // will be represented in a narrower or wider type. If there are any cast
583961f51fdSRosie Sumpter   // instructions that will be unnecessary, collect them in CastsFromRecurTy.
584961f51fdSRosie Sumpter   // Note that the 'and' instruction was already included in this list.
5857e98d698SVikram TV   //
5867e98d698SVikram TV   // TODO: A better way to represent this may be to tag in some way all the
5877e98d698SVikram TV   //       instructions that are a part of the reduction. The vectorizer cost
5887e98d698SVikram TV   //       model could then apply the recurrence type to these instructions,
5897e98d698SVikram TV   //       without needing a white list of instructions to ignore.
590745bf6cfSDavid Green   //       This may also be useful for the inloop reductions, if it can be
591745bf6cfSDavid Green   //       kept simple enough.
592961f51fdSRosie Sumpter   collectCastInstrs(TheLoop, ExitInstruction, RecurrenceType, CastInsts,
593961f51fdSRosie Sumpter                     MinWidthCastToRecurrenceType);
5947e98d698SVikram TV 
5957e98d698SVikram TV   // We found a reduction var if we have reached the original phi node and we
5967e98d698SVikram TV   // only have a single instruction with out-of-loop users.
5977e98d698SVikram TV 
5987e98d698SVikram TV   // The ExitInstruction(Instruction which is allowed to have out-of-loop users)
5997e98d698SVikram TV   // is saved as part of the RecurrenceDescriptor.
6007e98d698SVikram TV 
6017e98d698SVikram TV   // Save the description of this reduction variable.
6024e5e042dSIgor Kirillov   RecurrenceDescriptor RD(RdxStart, ExitInstruction, IntermediateStore, Kind,
6034e5e042dSIgor Kirillov                           FMF, ExactFPMathInst, RecurrenceType, IsSigned,
6044e5e042dSIgor Kirillov                           IsOrdered, CastInsts, MinWidthCastToRecurrenceType);
6057e98d698SVikram TV   RedDes = RD;
6067e98d698SVikram TV 
6077e98d698SVikram TV   return true;
6087e98d698SVikram TV }
6097e98d698SVikram TV 
61026b7d9d6SDavid Sherwood // We are looking for loops that do something like this:
61126b7d9d6SDavid Sherwood //   int r = 0;
61226b7d9d6SDavid Sherwood //   for (int i = 0; i < n; i++) {
61326b7d9d6SDavid Sherwood //     if (src[i] > 3)
61426b7d9d6SDavid Sherwood //       r = 3;
61526b7d9d6SDavid Sherwood //   }
61626b7d9d6SDavid Sherwood // where the reduction value (r) only has two states, in this example 0 or 3.
61726b7d9d6SDavid Sherwood // The generated LLVM IR for this type of loop will be like this:
61826b7d9d6SDavid Sherwood //   for.body:
61926b7d9d6SDavid Sherwood //     %r = phi i32 [ %spec.select, %for.body ], [ 0, %entry ]
62026b7d9d6SDavid Sherwood //     ...
62126b7d9d6SDavid Sherwood //     %cmp = icmp sgt i32 %5, 3
62226b7d9d6SDavid Sherwood //     %spec.select = select i1 %cmp, i32 3, i32 %r
62326b7d9d6SDavid Sherwood //     ...
62426b7d9d6SDavid Sherwood // In general we can support vectorization of loops where 'r' flips between
62526b7d9d6SDavid Sherwood // any two non-constants, provided they are loop invariant. The only thing
62626b7d9d6SDavid Sherwood // we actually care about at the end of the loop is whether or not any lane
62726b7d9d6SDavid Sherwood // in the selected vector is different from the start value. The final
62826b7d9d6SDavid Sherwood // across-vector reduction after the loop simply involves choosing the start
62926b7d9d6SDavid Sherwood // value if nothing changed (0 in the example above) or the other selected
63026b7d9d6SDavid Sherwood // value (3 in the example above).
63126b7d9d6SDavid Sherwood RecurrenceDescriptor::InstDesc
isSelectCmpPattern(Loop * Loop,PHINode * OrigPhi,Instruction * I,InstDesc & Prev)63226b7d9d6SDavid Sherwood RecurrenceDescriptor::isSelectCmpPattern(Loop *Loop, PHINode *OrigPhi,
63326b7d9d6SDavid Sherwood                                          Instruction *I, InstDesc &Prev) {
63426b7d9d6SDavid Sherwood   // We must handle the select(cmp(),x,y) as a single instruction. Advance to
63526b7d9d6SDavid Sherwood   // the select.
63626b7d9d6SDavid Sherwood   CmpInst::Predicate Pred;
63726b7d9d6SDavid Sherwood   if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
63826b7d9d6SDavid Sherwood     if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
63926b7d9d6SDavid Sherwood       return InstDesc(Select, Prev.getRecKind());
64026b7d9d6SDavid Sherwood   }
64126b7d9d6SDavid Sherwood 
64226b7d9d6SDavid Sherwood   // Only match select with single use cmp condition.
64326b7d9d6SDavid Sherwood   if (!match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
64426b7d9d6SDavid Sherwood                          m_Value())))
64526b7d9d6SDavid Sherwood     return InstDesc(false, I);
64626b7d9d6SDavid Sherwood 
64726b7d9d6SDavid Sherwood   SelectInst *SI = cast<SelectInst>(I);
64826b7d9d6SDavid Sherwood   Value *NonPhi = nullptr;
64926b7d9d6SDavid Sherwood 
65026b7d9d6SDavid Sherwood   if (OrigPhi == dyn_cast<PHINode>(SI->getTrueValue()))
65126b7d9d6SDavid Sherwood     NonPhi = SI->getFalseValue();
65226b7d9d6SDavid Sherwood   else if (OrigPhi == dyn_cast<PHINode>(SI->getFalseValue()))
65326b7d9d6SDavid Sherwood     NonPhi = SI->getTrueValue();
65426b7d9d6SDavid Sherwood   else
65526b7d9d6SDavid Sherwood     return InstDesc(false, I);
65626b7d9d6SDavid Sherwood 
65726b7d9d6SDavid Sherwood   // We are looking for selects of the form:
65826b7d9d6SDavid Sherwood   //   select(cmp(), phi, loop_invariant) or
65926b7d9d6SDavid Sherwood   //   select(cmp(), loop_invariant, phi)
66026b7d9d6SDavid Sherwood   if (!Loop->isLoopInvariant(NonPhi))
66126b7d9d6SDavid Sherwood     return InstDesc(false, I);
66226b7d9d6SDavid Sherwood 
66326b7d9d6SDavid Sherwood   return InstDesc(I, isa<ICmpInst>(I->getOperand(0)) ? RecurKind::SelectICmp
66426b7d9d6SDavid Sherwood                                                      : RecurKind::SelectFCmp);
66526b7d9d6SDavid Sherwood }
66626b7d9d6SDavid Sherwood 
6677e98d698SVikram TV RecurrenceDescriptor::InstDesc
isMinMaxPattern(Instruction * I,RecurKind Kind,const InstDesc & Prev)66861cc873aSDavid Green RecurrenceDescriptor::isMinMaxPattern(Instruction *I, RecurKind Kind,
669eaab7110SSanjay Patel                                       const InstDesc &Prev) {
67061cc873aSDavid Green   assert((isa<CmpInst>(I) || isa<SelectInst>(I) || isa<CallInst>(I)) &&
67161cc873aSDavid Green          "Expected a cmp or select or call instruction");
67261cc873aSDavid Green   if (!isMinMaxRecurrenceKind(Kind))
67361cc873aSDavid Green     return InstDesc(false, I);
6747e98d698SVikram TV 
6757e98d698SVikram TV   // We must handle the select(cmp()) as a single instruction. Advance to the
6767e98d698SVikram TV   // select.
677eaab7110SSanjay Patel   CmpInst::Predicate Pred;
678eaab7110SSanjay Patel   if (match(I, m_OneUse(m_Cmp(Pred, m_Value(), m_Value())))) {
679eaab7110SSanjay Patel     if (auto *Select = dyn_cast<SelectInst>(*I->user_begin()))
680c74e8539SSanjay Patel       return InstDesc(Select, Prev.getRecKind());
6817e98d698SVikram TV   }
6827e98d698SVikram TV 
68361cc873aSDavid Green   // Only match select with single use cmp condition, or a min/max intrinsic.
68461cc873aSDavid Green   if (!isa<IntrinsicInst>(I) &&
68561cc873aSDavid Green       !match(I, m_Select(m_OneUse(m_Cmp(Pred, m_Value(), m_Value())), m_Value(),
686eaab7110SSanjay Patel                          m_Value())))
6877e98d698SVikram TV     return InstDesc(false, I);
6887e98d698SVikram TV 
6897e98d698SVikram TV   // Look for a min/max pattern.
690eaab7110SSanjay Patel   if (match(I, m_UMin(m_Value(), m_Value())))
69161cc873aSDavid Green     return InstDesc(Kind == RecurKind::UMin, I);
692eaab7110SSanjay Patel   if (match(I, m_UMax(m_Value(), m_Value())))
69361cc873aSDavid Green     return InstDesc(Kind == RecurKind::UMax, I);
694eaab7110SSanjay Patel   if (match(I, m_SMax(m_Value(), m_Value())))
69561cc873aSDavid Green     return InstDesc(Kind == RecurKind::SMax, I);
696eaab7110SSanjay Patel   if (match(I, m_SMin(m_Value(), m_Value())))
69761cc873aSDavid Green     return InstDesc(Kind == RecurKind::SMin, I);
698eaab7110SSanjay Patel   if (match(I, m_OrdFMin(m_Value(), m_Value())))
69961cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMin, I);
700eaab7110SSanjay Patel   if (match(I, m_OrdFMax(m_Value(), m_Value())))
70161cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMax, I);
702eaab7110SSanjay Patel   if (match(I, m_UnordFMin(m_Value(), m_Value())))
70361cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMin, I);
704eaab7110SSanjay Patel   if (match(I, m_UnordFMax(m_Value(), m_Value())))
70561cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMax, I);
70661cc873aSDavid Green   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
70761cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMin, I);
70861cc873aSDavid Green   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
70961cc873aSDavid Green     return InstDesc(Kind == RecurKind::FMax, I);
7107e98d698SVikram TV 
7117e98d698SVikram TV   return InstDesc(false, I);
7127e98d698SVikram TV }
7137e98d698SVikram TV 
714135e72e1SRenato Golin /// Returns true if the select instruction has users in the compare-and-add
715135e72e1SRenato Golin /// reduction pattern below. The select instruction argument is the last one
716135e72e1SRenato Golin /// in the sequence.
717135e72e1SRenato Golin ///
718135e72e1SRenato Golin /// %sum.1 = phi ...
719135e72e1SRenato Golin /// ...
720135e72e1SRenato Golin /// %cmp = fcmp pred %0, %CFP
721135e72e1SRenato Golin /// %add = fadd %0, %sum.1
722135e72e1SRenato Golin /// %sum.2 = select %cmp, %add, %sum.1
723135e72e1SRenato Golin RecurrenceDescriptor::InstDesc
isConditionalRdxPattern(RecurKind Kind,Instruction * I)724c74e8539SSanjay Patel RecurrenceDescriptor::isConditionalRdxPattern(RecurKind Kind, Instruction *I) {
725135e72e1SRenato Golin   SelectInst *SI = dyn_cast<SelectInst>(I);
726135e72e1SRenato Golin   if (!SI)
727135e72e1SRenato Golin     return InstDesc(false, I);
728135e72e1SRenato Golin 
729135e72e1SRenato Golin   CmpInst *CI = dyn_cast<CmpInst>(SI->getCondition());
730135e72e1SRenato Golin   // Only handle single use cases for now.
731135e72e1SRenato Golin   if (!CI || !CI->hasOneUse())
732135e72e1SRenato Golin     return InstDesc(false, I);
733135e72e1SRenato Golin 
734135e72e1SRenato Golin   Value *TrueVal = SI->getTrueValue();
735135e72e1SRenato Golin   Value *FalseVal = SI->getFalseValue();
736135e72e1SRenato Golin   // Handle only when either of operands of select instruction is a PHI
737135e72e1SRenato Golin   // node for now.
738135e72e1SRenato Golin   if ((isa<PHINode>(*TrueVal) && isa<PHINode>(*FalseVal)) ||
739135e72e1SRenato Golin       (!isa<PHINode>(*TrueVal) && !isa<PHINode>(*FalseVal)))
740135e72e1SRenato Golin     return InstDesc(false, I);
741135e72e1SRenato Golin 
742135e72e1SRenato Golin   Instruction *I1 =
743135e72e1SRenato Golin       isa<PHINode>(*TrueVal) ? dyn_cast<Instruction>(FalseVal)
744135e72e1SRenato Golin                              : dyn_cast<Instruction>(TrueVal);
745135e72e1SRenato Golin   if (!I1 || !I1->isBinaryOp())
746135e72e1SRenato Golin     return InstDesc(false, I);
747135e72e1SRenato Golin 
748135e72e1SRenato Golin   Value *Op1, *Op2;
749de4b88e5SRenato Golin   if ((m_FAdd(m_Value(Op1), m_Value(Op2)).match(I1)  ||
750de4b88e5SRenato Golin        m_FSub(m_Value(Op1), m_Value(Op2)).match(I1)) &&
751de4b88e5SRenato Golin       I1->isFast())
752c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::FAdd, SI);
753135e72e1SRenato Golin 
754135e72e1SRenato Golin   if (m_FMul(m_Value(Op1), m_Value(Op2)).match(I1) && (I1->isFast()))
755c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::FMul, SI);
756135e72e1SRenato Golin 
757135e72e1SRenato Golin   return InstDesc(false, I);
758135e72e1SRenato Golin }
759135e72e1SRenato Golin 
7607e98d698SVikram TV RecurrenceDescriptor::InstDesc
isRecurrenceInstr(Loop * L,PHINode * OrigPhi,Instruction * I,RecurKind Kind,InstDesc & Prev,FastMathFlags FuncFMF)76126b7d9d6SDavid Sherwood RecurrenceDescriptor::isRecurrenceInstr(Loop *L, PHINode *OrigPhi,
76226b7d9d6SDavid Sherwood                                         Instruction *I, RecurKind Kind,
76361cc873aSDavid Green                                         InstDesc &Prev, FastMathFlags FuncFMF) {
76461cc873aSDavid Green   assert(Prev.getRecKind() == RecurKind::None || Prev.getRecKind() == Kind);
7657e98d698SVikram TV   switch (I->getOpcode()) {
7667e98d698SVikram TV   default:
7677e98d698SVikram TV     return InstDesc(false, I);
7687e98d698SVikram TV   case Instruction::PHI:
769b3a33553SSanjay Patel     return InstDesc(I, Prev.getRecKind(), Prev.getExactFPMathInst());
7707e98d698SVikram TV   case Instruction::Sub:
7717e98d698SVikram TV   case Instruction::Add:
772c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::Add, I);
7737e98d698SVikram TV   case Instruction::Mul:
774c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::Mul, I);
7757e98d698SVikram TV   case Instruction::And:
776c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::And, I);
7777e98d698SVikram TV   case Instruction::Or:
778c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::Or, I);
7797e98d698SVikram TV   case Instruction::Xor:
780c74e8539SSanjay Patel     return InstDesc(Kind == RecurKind::Xor, I);
7814bc88a0eSYichao Yu   case Instruction::FDiv:
7827e98d698SVikram TV   case Instruction::FMul:
783b3f0c265SSanjay Patel     return InstDesc(Kind == RecurKind::FMul, I,
784b3f0c265SSanjay Patel                     I->hasAllowReassoc() ? nullptr : I);
7857e98d698SVikram TV   case Instruction::FSub:
7867e98d698SVikram TV   case Instruction::FAdd:
787b3f0c265SSanjay Patel     return InstDesc(Kind == RecurKind::FAdd, I,
788b3f0c265SSanjay Patel                     I->hasAllowReassoc() ? nullptr : I);
789135e72e1SRenato Golin   case Instruction::Select:
790c74e8539SSanjay Patel     if (Kind == RecurKind::FAdd || Kind == RecurKind::FMul)
791135e72e1SRenato Golin       return isConditionalRdxPattern(Kind, I);
792135e72e1SRenato Golin     LLVM_FALLTHROUGH;
7937e98d698SVikram TV   case Instruction::FCmp:
7947e98d698SVikram TV   case Instruction::ICmp:
79561cc873aSDavid Green   case Instruction::Call:
79626b7d9d6SDavid Sherwood     if (isSelectCmpRecurrenceKind(Kind))
79726b7d9d6SDavid Sherwood       return isSelectCmpPattern(L, OrigPhi, I, Prev);
7985fe15934SKerry McLaughlin     if (isIntMinMaxRecurrenceKind(Kind) ||
79961cc873aSDavid Green         (((FuncFMF.noNaNs() && FuncFMF.noSignedZeros()) ||
80061cc873aSDavid Green           (isa<FPMathOperator>(I) && I->hasNoNaNs() &&
80161cc873aSDavid Green            I->hasNoSignedZeros())) &&
80261cc873aSDavid Green          isFPMinMaxRecurrenceKind(Kind)))
80361cc873aSDavid Green       return isMinMaxPattern(I, Kind, Prev);
804c2441b6bSRosie Sumpter     else if (isFMulAddIntrinsic(I))
805c2441b6bSRosie Sumpter       return InstDesc(Kind == RecurKind::FMulAdd, I,
806c2441b6bSRosie Sumpter                       I->hasAllowReassoc() ? nullptr : I);
8075fe15934SKerry McLaughlin     return InstDesc(false, I);
8087e98d698SVikram TV   }
8097e98d698SVikram TV }
8107e98d698SVikram TV 
hasMultipleUsesOf(Instruction * I,SmallPtrSetImpl<Instruction * > & Insts,unsigned MaxNumUses)8117e98d698SVikram TV bool RecurrenceDescriptor::hasMultipleUsesOf(
812135e72e1SRenato Golin     Instruction *I, SmallPtrSetImpl<Instruction *> &Insts,
813135e72e1SRenato Golin     unsigned MaxNumUses) {
8147e98d698SVikram TV   unsigned NumUses = 0;
815896d0e1aSKazu Hirata   for (const Use &U : I->operands()) {
816896d0e1aSKazu Hirata     if (Insts.count(dyn_cast<Instruction>(U)))
8177e98d698SVikram TV       ++NumUses;
818135e72e1SRenato Golin     if (NumUses > MaxNumUses)
8197e98d698SVikram TV       return true;
8207e98d698SVikram TV   }
8217e98d698SVikram TV 
8227e98d698SVikram TV   return false;
8237e98d698SVikram TV }
824287d39ddSPaul Walker 
isReductionPHI(PHINode * Phi,Loop * TheLoop,RecurrenceDescriptor & RedDes,DemandedBits * DB,AssumptionCache * AC,DominatorTree * DT,ScalarEvolution * SE)8257e98d698SVikram TV bool RecurrenceDescriptor::isReductionPHI(PHINode *Phi, Loop *TheLoop,
8267e98d698SVikram TV                                           RecurrenceDescriptor &RedDes,
8277e98d698SVikram TV                                           DemandedBits *DB, AssumptionCache *AC,
8284e5e042dSIgor Kirillov                                           DominatorTree *DT,
8294e5e042dSIgor Kirillov                                           ScalarEvolution *SE) {
8307e98d698SVikram TV   BasicBlock *Header = TheLoop->getHeader();
8317e98d698SVikram TV   Function &F = *Header->getParent();
8325fe15934SKerry McLaughlin   FastMathFlags FMF;
8335fe15934SKerry McLaughlin   FMF.setNoNaNs(
834d6de1e1aSSerge Guelton       F.getFnAttribute("no-nans-fp-math").getValueAsBool());
8355fe15934SKerry McLaughlin   FMF.setNoSignedZeros(
836d6de1e1aSSerge Guelton       F.getFnAttribute("no-signed-zeros-fp-math").getValueAsBool());
8377e98d698SVikram TV 
8384e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::Add, TheLoop, FMF, RedDes, DB, AC, DT,
8394e5e042dSIgor Kirillov                       SE)) {
8407e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found an ADD reduction PHI." << *Phi << "\n");
8417e98d698SVikram TV     return true;
8427e98d698SVikram TV   }
8434e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::Mul, TheLoop, FMF, RedDes, DB, AC, DT,
8444e5e042dSIgor Kirillov                       SE)) {
8457e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found a MUL reduction PHI." << *Phi << "\n");
8467e98d698SVikram TV     return true;
8477e98d698SVikram TV   }
8484e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::Or, TheLoop, FMF, RedDes, DB, AC, DT,
8494e5e042dSIgor Kirillov                       SE)) {
8507e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found an OR reduction PHI." << *Phi << "\n");
8517e98d698SVikram TV     return true;
8527e98d698SVikram TV   }
8534e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::And, TheLoop, FMF, RedDes, DB, AC, DT,
8544e5e042dSIgor Kirillov                       SE)) {
8557e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found an AND reduction PHI." << *Phi << "\n");
8567e98d698SVikram TV     return true;
8577e98d698SVikram TV   }
8584e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::Xor, TheLoop, FMF, RedDes, DB, AC, DT,
8594e5e042dSIgor Kirillov                       SE)) {
8607e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found a XOR reduction PHI." << *Phi << "\n");
8617e98d698SVikram TV     return true;
8627e98d698SVikram TV   }
8634e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::SMax, TheLoop, FMF, RedDes, DB, AC, DT,
8644e5e042dSIgor Kirillov                       SE)) {
865c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a SMAX reduction PHI." << *Phi << "\n");
8667e98d698SVikram TV     return true;
8677e98d698SVikram TV   }
8684e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::SMin, TheLoop, FMF, RedDes, DB, AC, DT,
8694e5e042dSIgor Kirillov                       SE)) {
870c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a SMIN reduction PHI." << *Phi << "\n");
871c74e8539SSanjay Patel     return true;
872c74e8539SSanjay Patel   }
8734e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::UMax, TheLoop, FMF, RedDes, DB, AC, DT,
8744e5e042dSIgor Kirillov                       SE)) {
875c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a UMAX reduction PHI." << *Phi << "\n");
876c74e8539SSanjay Patel     return true;
877c74e8539SSanjay Patel   }
8784e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::UMin, TheLoop, FMF, RedDes, DB, AC, DT,
8794e5e042dSIgor Kirillov                       SE)) {
880c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a UMIN reduction PHI." << *Phi << "\n");
881c74e8539SSanjay Patel     return true;
882c74e8539SSanjay Patel   }
88326b7d9d6SDavid Sherwood   if (AddReductionVar(Phi, RecurKind::SelectICmp, TheLoop, FMF, RedDes, DB, AC,
8844e5e042dSIgor Kirillov                       DT, SE)) {
88526b7d9d6SDavid Sherwood     LLVM_DEBUG(dbgs() << "Found an integer conditional select reduction PHI."
88626b7d9d6SDavid Sherwood                       << *Phi << "\n");
88726b7d9d6SDavid Sherwood     return true;
88826b7d9d6SDavid Sherwood   }
8894e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::FMul, TheLoop, FMF, RedDes, DB, AC, DT,
8904e5e042dSIgor Kirillov                       SE)) {
8917e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found an FMult reduction PHI." << *Phi << "\n");
8927e98d698SVikram TV     return true;
8937e98d698SVikram TV   }
8944e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::FAdd, TheLoop, FMF, RedDes, DB, AC, DT,
8954e5e042dSIgor Kirillov                       SE)) {
8967e98d698SVikram TV     LLVM_DEBUG(dbgs() << "Found an FAdd reduction PHI." << *Phi << "\n");
8977e98d698SVikram TV     return true;
8987e98d698SVikram TV   }
8994e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::FMax, TheLoop, FMF, RedDes, DB, AC, DT,
9004e5e042dSIgor Kirillov                       SE)) {
901c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a float MAX reduction PHI." << *Phi << "\n");
902c74e8539SSanjay Patel     return true;
903c74e8539SSanjay Patel   }
9044e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::FMin, TheLoop, FMF, RedDes, DB, AC, DT,
9054e5e042dSIgor Kirillov                       SE)) {
906c74e8539SSanjay Patel     LLVM_DEBUG(dbgs() << "Found a float MIN reduction PHI." << *Phi << "\n");
9077e98d698SVikram TV     return true;
9087e98d698SVikram TV   }
90926b7d9d6SDavid Sherwood   if (AddReductionVar(Phi, RecurKind::SelectFCmp, TheLoop, FMF, RedDes, DB, AC,
9104e5e042dSIgor Kirillov                       DT, SE)) {
91126b7d9d6SDavid Sherwood     LLVM_DEBUG(dbgs() << "Found a float conditional select reduction PHI."
91226b7d9d6SDavid Sherwood                       << " PHI." << *Phi << "\n");
91326b7d9d6SDavid Sherwood     return true;
91426b7d9d6SDavid Sherwood   }
9154e5e042dSIgor Kirillov   if (AddReductionVar(Phi, RecurKind::FMulAdd, TheLoop, FMF, RedDes, DB, AC, DT,
9164e5e042dSIgor Kirillov                       SE)) {
917c2441b6bSRosie Sumpter     LLVM_DEBUG(dbgs() << "Found an FMulAdd reduction PHI." << *Phi << "\n");
918c2441b6bSRosie Sumpter     return true;
919c2441b6bSRosie Sumpter   }
9207e98d698SVikram TV   // Not a reduction of known type.
9217e98d698SVikram TV   return false;
9227e98d698SVikram TV }
9237e98d698SVikram TV 
isFirstOrderRecurrence(PHINode * Phi,Loop * TheLoop,MapVector<Instruction *,Instruction * > & SinkAfter,DominatorTree * DT)9247e98d698SVikram TV bool RecurrenceDescriptor::isFirstOrderRecurrence(
9257e98d698SVikram TV     PHINode *Phi, Loop *TheLoop,
926aa00b1d7SFlorian Hahn     MapVector<Instruction *, Instruction *> &SinkAfter, DominatorTree *DT) {
9277e98d698SVikram TV 
9287e98d698SVikram TV   // Ensure the phi node is in the loop header and has two incoming values.
9297e98d698SVikram TV   if (Phi->getParent() != TheLoop->getHeader() ||
9307e98d698SVikram TV       Phi->getNumIncomingValues() != 2)
9317e98d698SVikram TV     return false;
9327e98d698SVikram TV 
9337e98d698SVikram TV   // Ensure the loop has a preheader and a single latch block. The loop
9347e98d698SVikram TV   // vectorizer will need the latch to set up the next iteration of the loop.
9357e98d698SVikram TV   auto *Preheader = TheLoop->getLoopPreheader();
9367e98d698SVikram TV   auto *Latch = TheLoop->getLoopLatch();
9377e98d698SVikram TV   if (!Preheader || !Latch)
9387e98d698SVikram TV     return false;
9397e98d698SVikram TV 
9407e98d698SVikram TV   // Ensure the phi node's incoming blocks are the loop preheader and latch.
9417e98d698SVikram TV   if (Phi->getBasicBlockIndex(Preheader) < 0 ||
9427e98d698SVikram TV       Phi->getBasicBlockIndex(Latch) < 0)
9437e98d698SVikram TV     return false;
9447e98d698SVikram TV 
9457e98d698SVikram TV   // Get the previous value. The previous value comes from the latch edge while
9467e98d698SVikram TV   // the initial value comes form the preheader edge.
9477e98d698SVikram TV   auto *Previous = dyn_cast<Instruction>(Phi->getIncomingValueForBlock(Latch));
9487e98d698SVikram TV   if (!Previous || !TheLoop->contains(Previous) || isa<PHINode>(Previous) ||
9497e98d698SVikram TV       SinkAfter.count(Previous)) // Cannot rely on dominance due to motion.
9507e98d698SVikram TV     return false;
9517e98d698SVikram TV 
952aa00b1d7SFlorian Hahn   // Ensure every user of the phi node (recursively) is dominated by the
953aa00b1d7SFlorian Hahn   // previous value. The dominance requirement ensures the loop vectorizer will
954aa00b1d7SFlorian Hahn   // not need to vectorize the initial value prior to the first iteration of the
955aa00b1d7SFlorian Hahn   // loop.
956aa00b1d7SFlorian Hahn   // TODO: Consider extending this sinking to handle memory instructions.
9579d24933fSFlorian Hahn 
958aa00b1d7SFlorian Hahn   // We optimistically assume we can sink all users after Previous. Keep a set
959aa00b1d7SFlorian Hahn   // of instructions to sink after Previous ordered by dominance in the common
960aa00b1d7SFlorian Hahn   // basic block. It will be applied to SinkAfter if all users can be sunk.
961aa00b1d7SFlorian Hahn   auto CompareByComesBefore = [](const Instruction *A, const Instruction *B) {
962aa00b1d7SFlorian Hahn     return A->comesBefore(B);
9639d24933fSFlorian Hahn   };
964aa00b1d7SFlorian Hahn   std::set<Instruction *, decltype(CompareByComesBefore)> InstrsToSink(
965aa00b1d7SFlorian Hahn       CompareByComesBefore);
9669d24933fSFlorian Hahn 
967aa00b1d7SFlorian Hahn   BasicBlock *PhiBB = Phi->getParent();
968aa00b1d7SFlorian Hahn   SmallVector<Instruction *, 8> WorkList;
969aa00b1d7SFlorian Hahn   auto TryToPushSinkCandidate = [&](Instruction *SinkCandidate) {
970aa00b1d7SFlorian Hahn     // Already sunk SinkCandidate.
971aa00b1d7SFlorian Hahn     if (SinkCandidate->getParent() == PhiBB &&
972aa00b1d7SFlorian Hahn         InstrsToSink.find(SinkCandidate) != InstrsToSink.end())
973aa00b1d7SFlorian Hahn       return true;
9749d24933fSFlorian Hahn 
975aa00b1d7SFlorian Hahn     // Cyclic dependence.
976aa00b1d7SFlorian Hahn     if (Previous == SinkCandidate)
9779d24933fSFlorian Hahn       return false;
9789d24933fSFlorian Hahn 
979aa00b1d7SFlorian Hahn     if (DT->dominates(Previous,
980aa00b1d7SFlorian Hahn                       SinkCandidate)) // We already are good w/o sinking.
981aa00b1d7SFlorian Hahn       return true;
982aa00b1d7SFlorian Hahn 
983aa00b1d7SFlorian Hahn     if (SinkCandidate->getParent() != PhiBB ||
984aa00b1d7SFlorian Hahn         SinkCandidate->mayHaveSideEffects() ||
985aa00b1d7SFlorian Hahn         SinkCandidate->mayReadFromMemory() || SinkCandidate->isTerminator())
9869d24933fSFlorian Hahn       return false;
9879d24933fSFlorian Hahn 
988139215afSFlorian Hahn     // Avoid sinking an instruction multiple times (if multiple operands are
989139215afSFlorian Hahn     // first order recurrences) by sinking once - after the latest 'previous'
990139215afSFlorian Hahn     // instruction.
991b2f5164dSzhongyunde     auto It = SinkAfter.find(SinkCandidate);
992b2f5164dSzhongyunde     if (It != SinkAfter.end()) {
993139215afSFlorian Hahn       auto *OtherPrev = It->second;
994139215afSFlorian Hahn       // Find the earliest entry in the 'sink-after' chain. The last entry in
995139215afSFlorian Hahn       // the chain is the original 'Previous' for a recurrence handled earlier.
996139215afSFlorian Hahn       auto EarlierIt = SinkAfter.find(OtherPrev);
997139215afSFlorian Hahn       while (EarlierIt != SinkAfter.end()) {
998139215afSFlorian Hahn         Instruction *EarlierInst = EarlierIt->second;
999139215afSFlorian Hahn         EarlierIt = SinkAfter.find(EarlierInst);
1000a2979c83SFlorian Hahn         // Bail out if order has not been preserved.
1001a2979c83SFlorian Hahn         if (EarlierIt != SinkAfter.end() &&
1002a2979c83SFlorian Hahn             !DT->dominates(EarlierInst, OtherPrev))
1003a2979c83SFlorian Hahn           return false;
1004139215afSFlorian Hahn         OtherPrev = EarlierInst;
1005139215afSFlorian Hahn       }
1006a2979c83SFlorian Hahn       // Bail out if order has not been preserved.
1007a2979c83SFlorian Hahn       if (OtherPrev != It->second && !DT->dominates(It->second, OtherPrev))
1008a2979c83SFlorian Hahn         return false;
1009ec3efcf1SFlorian Hahn 
1010139215afSFlorian Hahn       // SinkCandidate is already being sunk after an instruction after
1011139215afSFlorian Hahn       // Previous. Nothing left to do.
10125a60260eSFlorian Hahn       if (DT->dominates(Previous, OtherPrev) || Previous == OtherPrev)
1013139215afSFlorian Hahn         return true;
1014139215afSFlorian Hahn       // Otherwise, Previous comes after OtherPrev and SinkCandidate needs to be
1015de8ac485SFlorian Hahn       // re-sunk to Previous, instead of sinking to OtherPrev. Remove
1016de8ac485SFlorian Hahn       // SinkCandidate from SinkAfter to ensure it's insert position is updated.
1017de8ac485SFlorian Hahn       SinkAfter.erase(SinkCandidate);
1018b2f5164dSzhongyunde     }
1019b2f5164dSzhongyunde 
1020aa00b1d7SFlorian Hahn     // If we reach a PHI node that is not dominated by Previous, we reached a
1021aa00b1d7SFlorian Hahn     // header PHI. No need for sinking.
1022aa00b1d7SFlorian Hahn     if (isa<PHINode>(SinkCandidate))
10239d24933fSFlorian Hahn       return true;
10249d24933fSFlorian Hahn 
1025aa00b1d7SFlorian Hahn     // Sink User tentatively and check its users
1026aa00b1d7SFlorian Hahn     InstrsToSink.insert(SinkCandidate);
1027aa00b1d7SFlorian Hahn     WorkList.push_back(SinkCandidate);
1028aa00b1d7SFlorian Hahn     return true;
1029aa00b1d7SFlorian Hahn   };
1030aa00b1d7SFlorian Hahn 
1031aa00b1d7SFlorian Hahn   WorkList.push_back(Phi);
1032aa00b1d7SFlorian Hahn   // Try to recursively sink instructions and their users after Previous.
1033aa00b1d7SFlorian Hahn   while (!WorkList.empty()) {
1034aa00b1d7SFlorian Hahn     Instruction *Current = WorkList.pop_back_val();
1035aa00b1d7SFlorian Hahn     for (User *User : Current->users()) {
1036aa00b1d7SFlorian Hahn       if (!TryToPushSinkCandidate(cast<Instruction>(User)))
1037aa00b1d7SFlorian Hahn         return false;
1038aa00b1d7SFlorian Hahn     }
1039aa00b1d7SFlorian Hahn   }
1040aa00b1d7SFlorian Hahn 
1041aa00b1d7SFlorian Hahn   // We can sink all users of Phi. Update the mapping.
1042aa00b1d7SFlorian Hahn   for (Instruction *I : InstrsToSink) {
10437e98d698SVikram TV     SinkAfter[I] = Previous;
1044aa00b1d7SFlorian Hahn     Previous = I;
1045aa00b1d7SFlorian Hahn   }
10467e98d698SVikram TV   return true;
10477e98d698SVikram TV }
10487e98d698SVikram TV 
10497e98d698SVikram TV /// This function returns the identity element (or neutral element) for
10507e98d698SVikram TV /// the operation K.
getRecurrenceIdentity(RecurKind K,Type * Tp,FastMathFlags FMF) const105126b7d9d6SDavid Sherwood Value *RecurrenceDescriptor::getRecurrenceIdentity(RecurKind K, Type *Tp,
1052d74a8a78SFlorian Hahn                                                    FastMathFlags FMF) const {
10537e98d698SVikram TV   switch (K) {
1054c74e8539SSanjay Patel   case RecurKind::Xor:
1055c74e8539SSanjay Patel   case RecurKind::Add:
1056c74e8539SSanjay Patel   case RecurKind::Or:
10577e98d698SVikram TV     // Adding, Xoring, Oring zero to a number does not change it.
10587e98d698SVikram TV     return ConstantInt::get(Tp, 0);
1059c74e8539SSanjay Patel   case RecurKind::Mul:
10607e98d698SVikram TV     // Multiplying a number by 1 does not change it.
10617e98d698SVikram TV     return ConstantInt::get(Tp, 1);
1062c74e8539SSanjay Patel   case RecurKind::And:
10637e98d698SVikram TV     // AND-ing a number with an all-1 value does not change it.
10647e98d698SVikram TV     return ConstantInt::get(Tp, -1, true);
1065c74e8539SSanjay Patel   case RecurKind::FMul:
10667e98d698SVikram TV     // Multiplying a number by 1 does not change it.
10677e98d698SVikram TV     return ConstantFP::get(Tp, 1.0L);
1068c2441b6bSRosie Sumpter   case RecurKind::FMulAdd:
1069c74e8539SSanjay Patel   case RecurKind::FAdd:
10707e98d698SVikram TV     // Adding zero to a number does not change it.
1071857b8a73SKerry McLaughlin     // FIXME: Ideally we should not need to check FMF for FAdd and should always
1072857b8a73SKerry McLaughlin     // use -0.0. However, this will currently result in mixed vectors of 0.0/-0.0.
1073857b8a73SKerry McLaughlin     // Instead, we should ensure that 1) the FMF from FAdd are propagated to the PHI
1074857b8a73SKerry McLaughlin     // nodes where possible, and 2) PHIs with the nsz flag + -0.0 use 0.0. This would
1075857b8a73SKerry McLaughlin     // mean we can then remove the check for noSignedZeros() below (see D98963).
1076857b8a73SKerry McLaughlin     if (FMF.noSignedZeros())
10777e98d698SVikram TV       return ConstantFP::get(Tp, 0.0L);
1078857b8a73SKerry McLaughlin     return ConstantFP::get(Tp, -0.0L);
1079c74e8539SSanjay Patel   case RecurKind::UMin:
1080be6e8e50SDavid Green     return ConstantInt::get(Tp, -1);
1081c74e8539SSanjay Patel   case RecurKind::UMax:
1082be6e8e50SDavid Green     return ConstantInt::get(Tp, 0);
1083c74e8539SSanjay Patel   case RecurKind::SMin:
1084c74e8539SSanjay Patel     return ConstantInt::get(Tp,
1085c74e8539SSanjay Patel                             APInt::getSignedMaxValue(Tp->getIntegerBitWidth()));
1086c74e8539SSanjay Patel   case RecurKind::SMax:
1087c74e8539SSanjay Patel     return ConstantInt::get(Tp,
1088c74e8539SSanjay Patel                             APInt::getSignedMinValue(Tp->getIntegerBitWidth()));
1089c74e8539SSanjay Patel   case RecurKind::FMin:
1090be6e8e50SDavid Green     return ConstantFP::getInfinity(Tp, true);
1091c74e8539SSanjay Patel   case RecurKind::FMax:
1092be6e8e50SDavid Green     return ConstantFP::getInfinity(Tp, false);
109326b7d9d6SDavid Sherwood   case RecurKind::SelectICmp:
109426b7d9d6SDavid Sherwood   case RecurKind::SelectFCmp:
109526b7d9d6SDavid Sherwood     return getRecurrenceStartValue();
109626b7d9d6SDavid Sherwood     break;
1097be6e8e50SDavid Green   default:
1098be6e8e50SDavid Green     llvm_unreachable("Unknown recurrence kind");
1099be6e8e50SDavid Green   }
11007e98d698SVikram TV }
11017e98d698SVikram TV 
getOpcode(RecurKind Kind)110236263a7cSSanjay Patel unsigned RecurrenceDescriptor::getOpcode(RecurKind Kind) {
11037e98d698SVikram TV   switch (Kind) {
1104c74e8539SSanjay Patel   case RecurKind::Add:
11057e98d698SVikram TV     return Instruction::Add;
1106c74e8539SSanjay Patel   case RecurKind::Mul:
11077e98d698SVikram TV     return Instruction::Mul;
1108c74e8539SSanjay Patel   case RecurKind::Or:
11097e98d698SVikram TV     return Instruction::Or;
1110c74e8539SSanjay Patel   case RecurKind::And:
11117e98d698SVikram TV     return Instruction::And;
1112c74e8539SSanjay Patel   case RecurKind::Xor:
11137e98d698SVikram TV     return Instruction::Xor;
1114c74e8539SSanjay Patel   case RecurKind::FMul:
11157e98d698SVikram TV     return Instruction::FMul;
1116c2441b6bSRosie Sumpter   case RecurKind::FMulAdd:
1117c74e8539SSanjay Patel   case RecurKind::FAdd:
11187e98d698SVikram TV     return Instruction::FAdd;
1119c74e8539SSanjay Patel   case RecurKind::SMax:
1120c74e8539SSanjay Patel   case RecurKind::SMin:
1121c74e8539SSanjay Patel   case RecurKind::UMax:
1122c74e8539SSanjay Patel   case RecurKind::UMin:
112326b7d9d6SDavid Sherwood   case RecurKind::SelectICmp:
11247e98d698SVikram TV     return Instruction::ICmp;
1125c74e8539SSanjay Patel   case RecurKind::FMax:
1126c74e8539SSanjay Patel   case RecurKind::FMin:
112726b7d9d6SDavid Sherwood   case RecurKind::SelectFCmp:
11287e98d698SVikram TV     return Instruction::FCmp;
11297e98d698SVikram TV   default:
11307e98d698SVikram TV     llvm_unreachable("Unknown recurrence operation");
11317e98d698SVikram TV   }
11327e98d698SVikram TV }
11337e98d698SVikram TV 
1134745bf6cfSDavid Green SmallVector<Instruction *, 4>
getReductionOpChain(PHINode * Phi,Loop * L) const1135745bf6cfSDavid Green RecurrenceDescriptor::getReductionOpChain(PHINode *Phi, Loop *L) const {
1136745bf6cfSDavid Green   SmallVector<Instruction *, 4> ReductionOperations;
113736263a7cSSanjay Patel   unsigned RedOp = getOpcode(Kind);
1138745bf6cfSDavid Green 
1139745bf6cfSDavid Green   // Search down from the Phi to the LoopExitInstr, looking for instructions
1140745bf6cfSDavid Green   // with a single user of the correct type for the reduction.
1141745bf6cfSDavid Green 
1142745bf6cfSDavid Green   // Note that we check that the type of the operand is correct for each item in
1143745bf6cfSDavid Green   // the chain, including the last (the loop exit value). This can come up from
1144745bf6cfSDavid Green   // sub, which would otherwise be treated as an add reduction. MinMax also need
1145745bf6cfSDavid Green   // to check for a pair of icmp/select, for which we use getNextInstruction and
1146745bf6cfSDavid Green   // isCorrectOpcode functions to step the right number of instruction, and
1147745bf6cfSDavid Green   // check the icmp/select pair.
114812fb133eSKerry McLaughlin   // FIXME: We also do not attempt to look through Select's yet, which might
1149745bf6cfSDavid Green   // be part of the reduction chain, or attempt to looks through And's to find a
1150745bf6cfSDavid Green   // smaller bitwidth. Subs are also currently not allowed (which are usually
1151745bf6cfSDavid Green   // treated as part of a add reduction) as they are expected to generally be
1152745bf6cfSDavid Green   // more expensive than out-of-loop reductions, and need to be costed more
1153745bf6cfSDavid Green   // carefully.
1154745bf6cfSDavid Green   unsigned ExpectedUses = 1;
1155745bf6cfSDavid Green   if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp)
1156745bf6cfSDavid Green     ExpectedUses = 2;
1157745bf6cfSDavid Green 
115812fb133eSKerry McLaughlin   auto getNextInstruction = [&](Instruction *Cur) -> Instruction * {
1159*601b3a13SKazu Hirata     for (auto *User : Cur->users()) {
116012fb133eSKerry McLaughlin       Instruction *UI = cast<Instruction>(User);
116112fb133eSKerry McLaughlin       if (isa<PHINode>(UI))
116212fb133eSKerry McLaughlin         continue;
1163745bf6cfSDavid Green       if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
1164745bf6cfSDavid Green         // We are expecting a icmp/select pair, which we go to the next select
1165745bf6cfSDavid Green         // instruction if we can. We already know that Cur has 2 uses.
116612fb133eSKerry McLaughlin         if (isa<SelectInst>(UI))
116712fb133eSKerry McLaughlin           return UI;
116812fb133eSKerry McLaughlin         continue;
1169745bf6cfSDavid Green       }
117012fb133eSKerry McLaughlin       return UI;
117112fb133eSKerry McLaughlin     }
117212fb133eSKerry McLaughlin     return nullptr;
1173745bf6cfSDavid Green   };
1174745bf6cfSDavid Green   auto isCorrectOpcode = [&](Instruction *Cur) {
1175745bf6cfSDavid Green     if (RedOp == Instruction::ICmp || RedOp == Instruction::FCmp) {
1176745bf6cfSDavid Green       Value *LHS, *RHS;
1177745bf6cfSDavid Green       return SelectPatternResult::isMinOrMax(
1178745bf6cfSDavid Green           matchSelectPattern(Cur, LHS, RHS).Flavor);
1179745bf6cfSDavid Green     }
1180c2441b6bSRosie Sumpter     // Recognize a call to the llvm.fmuladd intrinsic.
1181c2441b6bSRosie Sumpter     if (isFMulAddIntrinsic(Cur))
1182c2441b6bSRosie Sumpter       return true;
1183c2441b6bSRosie Sumpter 
1184745bf6cfSDavid Green     return Cur->getOpcode() == RedOp;
1185745bf6cfSDavid Green   };
1186745bf6cfSDavid Green 
118712fb133eSKerry McLaughlin   // Attempt to look through Phis which are part of the reduction chain
118812fb133eSKerry McLaughlin   unsigned ExtraPhiUses = 0;
118912fb133eSKerry McLaughlin   Instruction *RdxInstr = LoopExitInstr;
119012fb133eSKerry McLaughlin   if (auto ExitPhi = dyn_cast<PHINode>(LoopExitInstr)) {
119112fb133eSKerry McLaughlin     if (ExitPhi->getNumIncomingValues() != 2)
119212fb133eSKerry McLaughlin       return {};
119312fb133eSKerry McLaughlin 
119412fb133eSKerry McLaughlin     Instruction *Inc0 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(0));
119512fb133eSKerry McLaughlin     Instruction *Inc1 = dyn_cast<Instruction>(ExitPhi->getIncomingValue(1));
119612fb133eSKerry McLaughlin 
119712fb133eSKerry McLaughlin     Instruction *Chain = nullptr;
119812fb133eSKerry McLaughlin     if (Inc0 == Phi)
119912fb133eSKerry McLaughlin       Chain = Inc1;
120012fb133eSKerry McLaughlin     else if (Inc1 == Phi)
120112fb133eSKerry McLaughlin       Chain = Inc0;
120212fb133eSKerry McLaughlin     else
120312fb133eSKerry McLaughlin       return {};
120412fb133eSKerry McLaughlin 
120512fb133eSKerry McLaughlin     RdxInstr = Chain;
120612fb133eSKerry McLaughlin     ExtraPhiUses = 1;
120712fb133eSKerry McLaughlin   }
120812fb133eSKerry McLaughlin 
1209745bf6cfSDavid Green   // The loop exit instruction we check first (as a quick test) but add last. We
1210745bf6cfSDavid Green   // check the opcode is correct (and dont allow them to be Subs) and that they
1211745bf6cfSDavid Green   // have expected to have the expected number of uses. They will have one use
1212745bf6cfSDavid Green   // from the phi and one from a LCSSA value, no matter the type.
121312fb133eSKerry McLaughlin   if (!isCorrectOpcode(RdxInstr) || !LoopExitInstr->hasNUses(2))
1214745bf6cfSDavid Green     return {};
1215745bf6cfSDavid Green 
121612fb133eSKerry McLaughlin   // Check that the Phi has one (or two for min/max) uses, plus an extra use
121712fb133eSKerry McLaughlin   // for conditional reductions.
121812fb133eSKerry McLaughlin   if (!Phi->hasNUses(ExpectedUses + ExtraPhiUses))
1219745bf6cfSDavid Green     return {};
122012fb133eSKerry McLaughlin 
1221745bf6cfSDavid Green   Instruction *Cur = getNextInstruction(Phi);
1222745bf6cfSDavid Green 
1223745bf6cfSDavid Green   // Each other instruction in the chain should have the expected number of uses
1224745bf6cfSDavid Green   // and be the correct opcode.
122512fb133eSKerry McLaughlin   while (Cur != RdxInstr) {
122612fb133eSKerry McLaughlin     if (!Cur || !isCorrectOpcode(Cur) || !Cur->hasNUses(ExpectedUses))
1227745bf6cfSDavid Green       return {};
1228745bf6cfSDavid Green 
1229745bf6cfSDavid Green     ReductionOperations.push_back(Cur);
1230745bf6cfSDavid Green     Cur = getNextInstruction(Cur);
1231745bf6cfSDavid Green   }
1232745bf6cfSDavid Green 
1233745bf6cfSDavid Green   ReductionOperations.push_back(Cur);
1234745bf6cfSDavid Green   return ReductionOperations;
1235745bf6cfSDavid Green }
1236745bf6cfSDavid Green 
InductionDescriptor(Value * Start,InductionKind K,const SCEV * Step,BinaryOperator * BOp,Type * ElementType,SmallVectorImpl<Instruction * > * Casts)12377e98d698SVikram TV InductionDescriptor::InductionDescriptor(Value *Start, InductionKind K,
12387e98d698SVikram TV                                          const SCEV *Step, BinaryOperator *BOp,
123902f74eadSNikita Popov                                          Type *ElementType,
12407e98d698SVikram TV                                          SmallVectorImpl<Instruction *> *Casts)
124102f74eadSNikita Popov     : StartValue(Start), IK(K), Step(Step), InductionBinOp(BOp),
124202f74eadSNikita Popov       ElementType(ElementType) {
12437e98d698SVikram TV   assert(IK != IK_NoInduction && "Not an induction");
12447e98d698SVikram TV 
12457e98d698SVikram TV   // Start value type should match the induction kind and the value
12467e98d698SVikram TV   // itself should not be null.
12477e98d698SVikram TV   assert(StartValue && "StartValue is null");
12487e98d698SVikram TV   assert((IK != IK_PtrInduction || StartValue->getType()->isPointerTy()) &&
12497e98d698SVikram TV          "StartValue is not a pointer for pointer induction");
12507e98d698SVikram TV   assert((IK != IK_IntInduction || StartValue->getType()->isIntegerTy()) &&
12517e98d698SVikram TV          "StartValue is not an integer for integer induction");
12527e98d698SVikram TV 
12537e98d698SVikram TV   // Check the Step Value. It should be non-zero integer value.
12547e98d698SVikram TV   assert((!getConstIntStepValue() || !getConstIntStepValue()->isZero()) &&
12557e98d698SVikram TV          "Step value is zero");
12567e98d698SVikram TV 
12577e98d698SVikram TV   assert((IK != IK_PtrInduction || getConstIntStepValue()) &&
12587e98d698SVikram TV          "Step value should be constant for pointer induction");
12597e98d698SVikram TV   assert((IK == IK_FpInduction || Step->getType()->isIntegerTy()) &&
12607e98d698SVikram TV          "StepValue is not an integer");
12617e98d698SVikram TV 
12627e98d698SVikram TV   assert((IK != IK_FpInduction || Step->getType()->isFloatingPointTy()) &&
12637e98d698SVikram TV          "StepValue is not FP for FpInduction");
12647e98d698SVikram TV   assert((IK != IK_FpInduction ||
12657e98d698SVikram TV           (InductionBinOp &&
12667e98d698SVikram TV            (InductionBinOp->getOpcode() == Instruction::FAdd ||
12677e98d698SVikram TV             InductionBinOp->getOpcode() == Instruction::FSub))) &&
12687e98d698SVikram TV          "Binary opcode should be specified for FP induction");
12697e98d698SVikram TV 
127002f74eadSNikita Popov   if (IK == IK_PtrInduction)
127102f74eadSNikita Popov     assert(ElementType && "Pointer induction must have element type");
127202f74eadSNikita Popov   else
127302f74eadSNikita Popov     assert(!ElementType && "Non-pointer induction cannot have element type");
127402f74eadSNikita Popov 
12757e98d698SVikram TV   if (Casts) {
12767e98d698SVikram TV     for (auto &Inst : *Casts) {
12777e98d698SVikram TV       RedundantCasts.push_back(Inst);
12787e98d698SVikram TV     }
12797e98d698SVikram TV   }
12807e98d698SVikram TV }
12817e98d698SVikram TV 
getConstIntStepValue() const12827e98d698SVikram TV ConstantInt *InductionDescriptor::getConstIntStepValue() const {
12837e98d698SVikram TV   if (isa<SCEVConstant>(Step))
12847e98d698SVikram TV     return dyn_cast<ConstantInt>(cast<SCEVConstant>(Step)->getValue());
12857e98d698SVikram TV   return nullptr;
12867e98d698SVikram TV }
12877e98d698SVikram TV 
isFPInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D)12887e98d698SVikram TV bool InductionDescriptor::isFPInductionPHI(PHINode *Phi, const Loop *TheLoop,
12897e98d698SVikram TV                                            ScalarEvolution *SE,
12907e98d698SVikram TV                                            InductionDescriptor &D) {
12917e98d698SVikram TV 
12927e98d698SVikram TV   // Here we only handle FP induction variables.
12937e98d698SVikram TV   assert(Phi->getType()->isFloatingPointTy() && "Unexpected Phi type");
12947e98d698SVikram TV 
12957e98d698SVikram TV   if (TheLoop->getHeader() != Phi->getParent())
12967e98d698SVikram TV     return false;
12977e98d698SVikram TV 
12987e98d698SVikram TV   // The loop may have multiple entrances or multiple exits; we can analyze
12997e98d698SVikram TV   // this phi if it has a unique entry value and a unique backedge value.
13007e98d698SVikram TV   if (Phi->getNumIncomingValues() != 2)
13017e98d698SVikram TV     return false;
13027e98d698SVikram TV   Value *BEValue = nullptr, *StartValue = nullptr;
13037e98d698SVikram TV   if (TheLoop->contains(Phi->getIncomingBlock(0))) {
13047e98d698SVikram TV     BEValue = Phi->getIncomingValue(0);
13057e98d698SVikram TV     StartValue = Phi->getIncomingValue(1);
13067e98d698SVikram TV   } else {
13077e98d698SVikram TV     assert(TheLoop->contains(Phi->getIncomingBlock(1)) &&
13087e98d698SVikram TV            "Unexpected Phi node in the loop");
13097e98d698SVikram TV     BEValue = Phi->getIncomingValue(1);
13107e98d698SVikram TV     StartValue = Phi->getIncomingValue(0);
13117e98d698SVikram TV   }
13127e98d698SVikram TV 
13137e98d698SVikram TV   BinaryOperator *BOp = dyn_cast<BinaryOperator>(BEValue);
13147e98d698SVikram TV   if (!BOp)
13157e98d698SVikram TV     return false;
13167e98d698SVikram TV 
13177e98d698SVikram TV   Value *Addend = nullptr;
13187e98d698SVikram TV   if (BOp->getOpcode() == Instruction::FAdd) {
13197e98d698SVikram TV     if (BOp->getOperand(0) == Phi)
13207e98d698SVikram TV       Addend = BOp->getOperand(1);
13217e98d698SVikram TV     else if (BOp->getOperand(1) == Phi)
13227e98d698SVikram TV       Addend = BOp->getOperand(0);
13237e98d698SVikram TV   } else if (BOp->getOpcode() == Instruction::FSub)
13247e98d698SVikram TV     if (BOp->getOperand(0) == Phi)
13257e98d698SVikram TV       Addend = BOp->getOperand(1);
13267e98d698SVikram TV 
13277e98d698SVikram TV   if (!Addend)
13287e98d698SVikram TV     return false;
13297e98d698SVikram TV 
13307e98d698SVikram TV   // The addend should be loop invariant
13317e98d698SVikram TV   if (auto *I = dyn_cast<Instruction>(Addend))
13327e98d698SVikram TV     if (TheLoop->contains(I))
13337e98d698SVikram TV       return false;
13347e98d698SVikram TV 
13357e98d698SVikram TV   // FP Step has unknown SCEV
13367e98d698SVikram TV   const SCEV *Step = SE->getUnknown(Addend);
13377e98d698SVikram TV   D = InductionDescriptor(StartValue, IK_FpInduction, Step, BOp);
13387e98d698SVikram TV   return true;
13397e98d698SVikram TV }
13407e98d698SVikram TV 
13417e98d698SVikram TV /// This function is called when we suspect that the update-chain of a phi node
13427e98d698SVikram TV /// (whose symbolic SCEV expression sin \p PhiScev) contains redundant casts,
13437e98d698SVikram TV /// that can be ignored. (This can happen when the PSCEV rewriter adds a runtime
13447e98d698SVikram TV /// predicate P under which the SCEV expression for the phi can be the
13457e98d698SVikram TV /// AddRecurrence \p AR; See createAddRecFromPHIWithCast). We want to find the
13467e98d698SVikram TV /// cast instructions that are involved in the update-chain of this induction.
13477e98d698SVikram TV /// A caller that adds the required runtime predicate can be free to drop these
13487e98d698SVikram TV /// cast instructions, and compute the phi using \p AR (instead of some scev
13497e98d698SVikram TV /// expression with casts).
13507e98d698SVikram TV ///
13517e98d698SVikram TV /// For example, without a predicate the scev expression can take the following
13527e98d698SVikram TV /// form:
13537e98d698SVikram TV ///      (Ext ix (Trunc iy ( Start + i*Step ) to ix) to iy)
13547e98d698SVikram TV ///
13557e98d698SVikram TV /// It corresponds to the following IR sequence:
13567e98d698SVikram TV /// %for.body:
13577e98d698SVikram TV ///   %x = phi i64 [ 0, %ph ], [ %add, %for.body ]
13587e98d698SVikram TV ///   %casted_phi = "ExtTrunc i64 %x"
13597e98d698SVikram TV ///   %add = add i64 %casted_phi, %step
13607e98d698SVikram TV ///
13617e98d698SVikram TV /// where %x is given in \p PN,
13627e98d698SVikram TV /// PSE.getSCEV(%x) is equal to PSE.getSCEV(%casted_phi) under a predicate,
13637e98d698SVikram TV /// and the IR sequence that "ExtTrunc i64 %x" represents can take one of
13647e98d698SVikram TV /// several forms, for example, such as:
13657e98d698SVikram TV ///   ExtTrunc1:    %casted_phi = and  %x, 2^n-1
13667e98d698SVikram TV /// or:
13677e98d698SVikram TV ///   ExtTrunc2:    %t = shl %x, m
13687e98d698SVikram TV ///                 %casted_phi = ashr %t, m
13697e98d698SVikram TV ///
13707e98d698SVikram TV /// If we are able to find such sequence, we return the instructions
13717e98d698SVikram TV /// we found, namely %casted_phi and the instructions on its use-def chain up
13727e98d698SVikram TV /// to the phi (not including the phi).
getCastsForInductionPHI(PredicatedScalarEvolution & PSE,const SCEVUnknown * PhiScev,const SCEVAddRecExpr * AR,SmallVectorImpl<Instruction * > & CastInsts)13737e98d698SVikram TV static bool getCastsForInductionPHI(PredicatedScalarEvolution &PSE,
13747e98d698SVikram TV                                     const SCEVUnknown *PhiScev,
13757e98d698SVikram TV                                     const SCEVAddRecExpr *AR,
13767e98d698SVikram TV                                     SmallVectorImpl<Instruction *> &CastInsts) {
13777e98d698SVikram TV 
13787e98d698SVikram TV   assert(CastInsts.empty() && "CastInsts is expected to be empty.");
13797e98d698SVikram TV   auto *PN = cast<PHINode>(PhiScev->getValue());
13807e98d698SVikram TV   assert(PSE.getSCEV(PN) == AR && "Unexpected phi node SCEV expression");
13817e98d698SVikram TV   const Loop *L = AR->getLoop();
13827e98d698SVikram TV 
13837e98d698SVikram TV   // Find any cast instructions that participate in the def-use chain of
13847e98d698SVikram TV   // PhiScev in the loop.
13857e98d698SVikram TV   // FORNOW/TODO: We currently expect the def-use chain to include only
13867e98d698SVikram TV   // two-operand instructions, where one of the operands is an invariant.
13877e98d698SVikram TV   // createAddRecFromPHIWithCasts() currently does not support anything more
13887e98d698SVikram TV   // involved than that, so we keep the search simple. This can be
13897e98d698SVikram TV   // extended/generalized as needed.
13907e98d698SVikram TV 
13917e98d698SVikram TV   auto getDef = [&](const Value *Val) -> Value * {
13927e98d698SVikram TV     const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val);
13937e98d698SVikram TV     if (!BinOp)
13947e98d698SVikram TV       return nullptr;
13957e98d698SVikram TV     Value *Op0 = BinOp->getOperand(0);
13967e98d698SVikram TV     Value *Op1 = BinOp->getOperand(1);
13977e98d698SVikram TV     Value *Def = nullptr;
13987e98d698SVikram TV     if (L->isLoopInvariant(Op0))
13997e98d698SVikram TV       Def = Op1;
14007e98d698SVikram TV     else if (L->isLoopInvariant(Op1))
14017e98d698SVikram TV       Def = Op0;
14027e98d698SVikram TV     return Def;
14037e98d698SVikram TV   };
14047e98d698SVikram TV 
14057e98d698SVikram TV   // Look for the instruction that defines the induction via the
14067e98d698SVikram TV   // loop backedge.
14077e98d698SVikram TV   BasicBlock *Latch = L->getLoopLatch();
14087e98d698SVikram TV   if (!Latch)
14097e98d698SVikram TV     return false;
14107e98d698SVikram TV   Value *Val = PN->getIncomingValueForBlock(Latch);
14117e98d698SVikram TV   if (!Val)
14127e98d698SVikram TV     return false;
14137e98d698SVikram TV 
14147e98d698SVikram TV   // Follow the def-use chain until the induction phi is reached.
14157e98d698SVikram TV   // If on the way we encounter a Value that has the same SCEV Expr as the
14167e98d698SVikram TV   // phi node, we can consider the instructions we visit from that point
14177e98d698SVikram TV   // as part of the cast-sequence that can be ignored.
14187e98d698SVikram TV   bool InCastSequence = false;
14197e98d698SVikram TV   auto *Inst = dyn_cast<Instruction>(Val);
14207e98d698SVikram TV   while (Val != PN) {
14217e98d698SVikram TV     // If we encountered a phi node other than PN, or if we left the loop,
14227e98d698SVikram TV     // we bail out.
14237e98d698SVikram TV     if (!Inst || !L->contains(Inst)) {
14247e98d698SVikram TV       return false;
14257e98d698SVikram TV     }
14267e98d698SVikram TV     auto *AddRec = dyn_cast<SCEVAddRecExpr>(PSE.getSCEV(Val));
14277e98d698SVikram TV     if (AddRec && PSE.areAddRecsEqualWithPreds(AddRec, AR))
14287e98d698SVikram TV       InCastSequence = true;
14297e98d698SVikram TV     if (InCastSequence) {
14307e98d698SVikram TV       // Only the last instruction in the cast sequence is expected to have
14317e98d698SVikram TV       // uses outside the induction def-use chain.
14327e98d698SVikram TV       if (!CastInsts.empty())
14337e98d698SVikram TV         if (!Inst->hasOneUse())
14347e98d698SVikram TV           return false;
14357e98d698SVikram TV       CastInsts.push_back(Inst);
14367e98d698SVikram TV     }
14377e98d698SVikram TV     Val = getDef(Val);
14387e98d698SVikram TV     if (!Val)
14397e98d698SVikram TV       return false;
14407e98d698SVikram TV     Inst = dyn_cast<Instruction>(Val);
14417e98d698SVikram TV   }
14427e98d698SVikram TV 
14437e98d698SVikram TV   return InCastSequence;
14447e98d698SVikram TV }
14457e98d698SVikram TV 
isInductionPHI(PHINode * Phi,const Loop * TheLoop,PredicatedScalarEvolution & PSE,InductionDescriptor & D,bool Assume)14467e98d698SVikram TV bool InductionDescriptor::isInductionPHI(PHINode *Phi, const Loop *TheLoop,
14477e98d698SVikram TV                                          PredicatedScalarEvolution &PSE,
14487e98d698SVikram TV                                          InductionDescriptor &D, bool Assume) {
14497e98d698SVikram TV   Type *PhiTy = Phi->getType();
14507e98d698SVikram TV 
14517e98d698SVikram TV   // Handle integer and pointer inductions variables.
14527e98d698SVikram TV   // Now we handle also FP induction but not trying to make a
14537e98d698SVikram TV   // recurrent expression from the PHI node in-place.
14547e98d698SVikram TV 
14557e98d698SVikram TV   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy() && !PhiTy->isFloatTy() &&
14567e98d698SVikram TV       !PhiTy->isDoubleTy() && !PhiTy->isHalfTy())
14577e98d698SVikram TV     return false;
14587e98d698SVikram TV 
14597e98d698SVikram TV   if (PhiTy->isFloatingPointTy())
14607e98d698SVikram TV     return isFPInductionPHI(Phi, TheLoop, PSE.getSE(), D);
14617e98d698SVikram TV 
14627e98d698SVikram TV   const SCEV *PhiScev = PSE.getSCEV(Phi);
14637e98d698SVikram TV   const auto *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
14647e98d698SVikram TV 
14657e98d698SVikram TV   // We need this expression to be an AddRecExpr.
14667e98d698SVikram TV   if (Assume && !AR)
14677e98d698SVikram TV     AR = PSE.getAsAddRec(Phi);
14687e98d698SVikram TV 
14697e98d698SVikram TV   if (!AR) {
14707e98d698SVikram TV     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
14717e98d698SVikram TV     return false;
14727e98d698SVikram TV   }
14737e98d698SVikram TV 
14747e98d698SVikram TV   // Record any Cast instructions that participate in the induction update
14757e98d698SVikram TV   const auto *SymbolicPhi = dyn_cast<SCEVUnknown>(PhiScev);
14767e98d698SVikram TV   // If we started from an UnknownSCEV, and managed to build an addRecurrence
14777e98d698SVikram TV   // only after enabling Assume with PSCEV, this means we may have encountered
14787e98d698SVikram TV   // cast instructions that required adding a runtime check in order to
147902a2bb2fSHiroshi Inoue   // guarantee the correctness of the AddRecurrence respresentation of the
14807e98d698SVikram TV   // induction.
14817e98d698SVikram TV   if (PhiScev != AR && SymbolicPhi) {
14827e98d698SVikram TV     SmallVector<Instruction *, 2> Casts;
14837e98d698SVikram TV     if (getCastsForInductionPHI(PSE, SymbolicPhi, AR, Casts))
14847e98d698SVikram TV       return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR, &Casts);
14857e98d698SVikram TV   }
14867e98d698SVikram TV 
14877e98d698SVikram TV   return isInductionPHI(Phi, TheLoop, PSE.getSE(), D, AR);
14887e98d698SVikram TV }
14897e98d698SVikram TV 
isInductionPHI(PHINode * Phi,const Loop * TheLoop,ScalarEvolution * SE,InductionDescriptor & D,const SCEV * Expr,SmallVectorImpl<Instruction * > * CastsToIgnore)14907e98d698SVikram TV bool InductionDescriptor::isInductionPHI(
14917e98d698SVikram TV     PHINode *Phi, const Loop *TheLoop, ScalarEvolution *SE,
14927e98d698SVikram TV     InductionDescriptor &D, const SCEV *Expr,
14937e98d698SVikram TV     SmallVectorImpl<Instruction *> *CastsToIgnore) {
14947e98d698SVikram TV   Type *PhiTy = Phi->getType();
14957e98d698SVikram TV   // We only handle integer and pointer inductions variables.
14967e98d698SVikram TV   if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
14977e98d698SVikram TV     return false;
14987e98d698SVikram TV 
14997e98d698SVikram TV   // Check that the PHI is consecutive.
15007e98d698SVikram TV   const SCEV *PhiScev = Expr ? Expr : SE->getSCEV(Phi);
15017e98d698SVikram TV   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
15027e98d698SVikram TV 
15037e98d698SVikram TV   if (!AR) {
15047e98d698SVikram TV     LLVM_DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
15057e98d698SVikram TV     return false;
15067e98d698SVikram TV   }
15077e98d698SVikram TV 
15087e98d698SVikram TV   if (AR->getLoop() != TheLoop) {
15097e98d698SVikram TV     // FIXME: We should treat this as a uniform. Unfortunately, we
15107e98d698SVikram TV     // don't currently know how to handled uniform PHIs.
15117e98d698SVikram TV     LLVM_DEBUG(
15127e98d698SVikram TV         dbgs() << "LV: PHI is a recurrence with respect to an outer loop.\n");
15137e98d698SVikram TV     return false;
15147e98d698SVikram TV   }
15157e98d698SVikram TV 
15167e98d698SVikram TV   Value *StartValue =
15177e98d698SVikram TV       Phi->getIncomingValueForBlock(AR->getLoop()->getLoopPreheader());
151837b7922dSKit Barton 
151937b7922dSKit Barton   BasicBlock *Latch = AR->getLoop()->getLoopLatch();
152037b7922dSKit Barton   if (!Latch)
152137b7922dSKit Barton     return false;
152237b7922dSKit Barton 
15237e98d698SVikram TV   const SCEV *Step = AR->getStepRecurrence(*SE);
15247e98d698SVikram TV   // Calculate the pointer stride and check if it is consecutive.
15257e98d698SVikram TV   // The stride may be a constant or a loop invariant integer value.
15267e98d698SVikram TV   const SCEVConstant *ConstStep = dyn_cast<SCEVConstant>(Step);
15277e98d698SVikram TV   if (!ConstStep && !SE->isLoopInvariant(Step, TheLoop))
15287e98d698SVikram TV     return false;
15297e98d698SVikram TV 
15307e98d698SVikram TV   if (PhiTy->isIntegerTy()) {
153102f74eadSNikita Popov     BinaryOperator *BOp =
153202f74eadSNikita Popov         dyn_cast<BinaryOperator>(Phi->getIncomingValueForBlock(Latch));
153337b7922dSKit Barton     D = InductionDescriptor(StartValue, IK_IntInduction, Step, BOp,
153402f74eadSNikita Popov                             /* ElementType */ nullptr, CastsToIgnore);
15357e98d698SVikram TV     return true;
15367e98d698SVikram TV   }
15377e98d698SVikram TV 
15387e98d698SVikram TV   assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
15397e98d698SVikram TV   // Pointer induction should be a constant.
15407e98d698SVikram TV   if (!ConstStep)
15417e98d698SVikram TV     return false;
15427e98d698SVikram TV 
154302f74eadSNikita Popov   // Always use i8 element type for opaque pointer inductions.
154402f74eadSNikita Popov   PointerType *PtrTy = cast<PointerType>(PhiTy);
1545aa97bc11SNikita Popov   Type *ElementType = PtrTy->isOpaque()
1546aa97bc11SNikita Popov                           ? Type::getInt8Ty(PtrTy->getContext())
1547aa97bc11SNikita Popov                           : PtrTy->getNonOpaquePointerElementType();
154802f74eadSNikita Popov   if (!ElementType->isSized())
15497e98d698SVikram TV     return false;
15507e98d698SVikram TV 
155102f74eadSNikita Popov   ConstantInt *CV = ConstStep->getValue();
15527e98d698SVikram TV   const DataLayout &DL = Phi->getModule()->getDataLayout();
15531badfbb4SDavid Sherwood   TypeSize TySize = DL.getTypeAllocSize(ElementType);
15541badfbb4SDavid Sherwood   // TODO: We could potentially support this for scalable vectors if we can
15551badfbb4SDavid Sherwood   // prove at compile time that the constant step is always a multiple of
15561badfbb4SDavid Sherwood   // the scalable type.
15571badfbb4SDavid Sherwood   if (TySize.isZero() || TySize.isScalable())
15587e98d698SVikram TV     return false;
15597e98d698SVikram TV 
15601badfbb4SDavid Sherwood   int64_t Size = static_cast<int64_t>(TySize.getFixedSize());
15617e98d698SVikram TV   int64_t CVSize = CV->getSExtValue();
15627e98d698SVikram TV   if (CVSize % Size)
15637e98d698SVikram TV     return false;
15647e98d698SVikram TV   auto *StepValue =
15657e98d698SVikram TV       SE->getConstant(CV->getType(), CVSize / Size, true /* signed */);
156602f74eadSNikita Popov   D = InductionDescriptor(StartValue, IK_PtrInduction, StepValue,
156702f74eadSNikita Popov                           /* BinOp */ nullptr, ElementType);
15687e98d698SVikram TV   return true;
15697e98d698SVikram TV }
1570