1f2ec16ccSHideki Saito //===- LoopVectorizationLegality.cpp --------------------------------------===// 2f2ec16ccSHideki Saito // 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 6f2ec16ccSHideki Saito // 7f2ec16ccSHideki Saito //===----------------------------------------------------------------------===// 8f2ec16ccSHideki Saito // 9f2ec16ccSHideki Saito // This file provides loop vectorization legality analysis. Original code 10f2ec16ccSHideki Saito // resided in LoopVectorize.cpp for a long time. 11f2ec16ccSHideki Saito // 12f2ec16ccSHideki Saito // At this point, it is implemented as a utility class, not as an analysis 13f2ec16ccSHideki Saito // pass. It should be easy to create an analysis pass around it if there 14f2ec16ccSHideki Saito // is a need (but D45420 needs to happen first). 15f2ec16ccSHideki Saito // 16cc529285SSimon Pilgrim 17f2ec16ccSHideki Saito #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h" 187403569bSPhilip Reames #include "llvm/Analysis/Loads.h" 19a5f1f9c9SSimon Pilgrim #include "llvm/Analysis/LoopInfo.h" 20cc529285SSimon Pilgrim #include "llvm/Analysis/TargetLibraryInfo.h" 217403569bSPhilip Reames #include "llvm/Analysis/ValueTracking.h" 22f2ec16ccSHideki Saito #include "llvm/Analysis/VectorUtils.h" 23f2ec16ccSHideki Saito #include "llvm/IR/IntrinsicInst.h" 2423c11380SFlorian Hahn #include "llvm/IR/PatternMatch.h" 257bedae7dSHiroshi Yamauchi #include "llvm/Transforms/Utils/SizeOpts.h" 2623c11380SFlorian Hahn #include "llvm/Transforms/Vectorize/LoopVectorize.h" 27f2ec16ccSHideki Saito 28f2ec16ccSHideki Saito using namespace llvm; 2923c11380SFlorian Hahn using namespace PatternMatch; 30f2ec16ccSHideki Saito 31f2ec16ccSHideki Saito #define LV_NAME "loop-vectorize" 32f2ec16ccSHideki Saito #define DEBUG_TYPE LV_NAME 33f2ec16ccSHideki Saito 344e4ecae0SHideki Saito extern cl::opt<bool> EnableVPlanPredication; 354e4ecae0SHideki Saito 36f2ec16ccSHideki Saito static cl::opt<bool> 37f2ec16ccSHideki Saito EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 38f2ec16ccSHideki Saito cl::desc("Enable if-conversion during vectorization.")); 39f2ec16ccSHideki Saito 40c773d0f9SFlorian Hahn // TODO: Move size-based thresholds out of legality checking, make cost based 41c773d0f9SFlorian Hahn // decisions instead of hard thresholds. 42f2ec16ccSHideki Saito static cl::opt<unsigned> VectorizeSCEVCheckThreshold( 43f2ec16ccSHideki Saito "vectorize-scev-check-threshold", cl::init(16), cl::Hidden, 44f2ec16ccSHideki Saito cl::desc("The maximum number of SCEV checks allowed.")); 45f2ec16ccSHideki Saito 46f2ec16ccSHideki Saito static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold( 47f2ec16ccSHideki Saito "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, 48f2ec16ccSHideki Saito cl::desc("The maximum number of SCEV checks allowed with a " 49f2ec16ccSHideki Saito "vectorize(enable) pragma")); 50f2ec16ccSHideki Saito 51f2ec16ccSHideki Saito /// Maximum vectorization interleave count. 52f2ec16ccSHideki Saito static const unsigned MaxInterleaveFactor = 16; 53f2ec16ccSHideki Saito 54f2ec16ccSHideki Saito namespace llvm { 55f2ec16ccSHideki Saito 56f2ec16ccSHideki Saito bool LoopVectorizeHints::Hint::validate(unsigned Val) { 57f2ec16ccSHideki Saito switch (Kind) { 58f2ec16ccSHideki Saito case HK_WIDTH: 59f2ec16ccSHideki Saito return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth; 60ddb3b26aSBardia Mahjour case HK_INTERLEAVE: 61f2ec16ccSHideki Saito return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor; 62f2ec16ccSHideki Saito case HK_FORCE: 63f2ec16ccSHideki Saito return (Val <= 1); 64f2ec16ccSHideki Saito case HK_ISVECTORIZED: 6520b198ecSSjoerd Meijer case HK_PREDICATE: 6671bd59f0SDavid Sherwood case HK_SCALABLE: 67f2ec16ccSHideki Saito return (Val == 0 || Val == 1); 68f2ec16ccSHideki Saito } 69f2ec16ccSHideki Saito return false; 70f2ec16ccSHideki Saito } 71f2ec16ccSHideki Saito 72d4eb13c8SMichael Kruse LoopVectorizeHints::LoopVectorizeHints(const Loop *L, 73d4eb13c8SMichael Kruse bool InterleaveOnlyWhenForced, 74f2ec16ccSHideki Saito OptimizationRemarkEmitter &ORE) 75f2ec16ccSHideki Saito : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH), 76ddb3b26aSBardia Mahjour Interleave("interleave.count", InterleaveOnlyWhenForced, HK_INTERLEAVE), 77f2ec16ccSHideki Saito Force("vectorize.enable", FK_Undefined, HK_FORCE), 7820b198ecSSjoerd Meijer IsVectorized("isvectorized", 0, HK_ISVECTORIZED), 7971bd59f0SDavid Sherwood Predicate("vectorize.predicate.enable", FK_Undefined, HK_PREDICATE), 8071bd59f0SDavid Sherwood Scalable("vectorize.scalable.enable", false, HK_SCALABLE), TheLoop(L), 8120b198ecSSjoerd Meijer ORE(ORE) { 82f2ec16ccSHideki Saito // Populate values with existing loop metadata. 83f2ec16ccSHideki Saito getHintsFromMetadata(); 84f2ec16ccSHideki Saito 85f2ec16ccSHideki Saito // force-vector-interleave overrides DisableInterleaving. 86f2ec16ccSHideki Saito if (VectorizerParams::isInterleaveForced()) 87f2ec16ccSHideki Saito Interleave.Value = VectorizerParams::VectorizationInterleave; 88f2ec16ccSHideki Saito 89f2ec16ccSHideki Saito if (IsVectorized.Value != 1) 90f2ec16ccSHideki Saito // If the vectorization width and interleaving count are both 1 then 91f2ec16ccSHideki Saito // consider the loop to have been already vectorized because there's 92f2ec16ccSHideki Saito // nothing more that we can do. 9371bd59f0SDavid Sherwood IsVectorized.Value = 94ddb3b26aSBardia Mahjour getWidth() == ElementCount::getFixed(1) && getInterleave() == 1; 95ddb3b26aSBardia Mahjour LLVM_DEBUG(if (InterleaveOnlyWhenForced && getInterleave() == 1) dbgs() 96f2ec16ccSHideki Saito << "LV: Interleaving disabled by the pass manager\n"); 97f2ec16ccSHideki Saito } 98f2ec16ccSHideki Saito 9977a614a6SMichael Kruse void LoopVectorizeHints::setAlreadyVectorized() { 10077a614a6SMichael Kruse LLVMContext &Context = TheLoop->getHeader()->getContext(); 10177a614a6SMichael Kruse 10277a614a6SMichael Kruse MDNode *IsVectorizedMD = MDNode::get( 10377a614a6SMichael Kruse Context, 10477a614a6SMichael Kruse {MDString::get(Context, "llvm.loop.isvectorized"), 10577a614a6SMichael Kruse ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))}); 10677a614a6SMichael Kruse MDNode *LoopID = TheLoop->getLoopID(); 10777a614a6SMichael Kruse MDNode *NewLoopID = 10877a614a6SMichael Kruse makePostTransformationMetadata(Context, LoopID, 10977a614a6SMichael Kruse {Twine(Prefix(), "vectorize.").str(), 11077a614a6SMichael Kruse Twine(Prefix(), "interleave.").str()}, 11177a614a6SMichael Kruse {IsVectorizedMD}); 11277a614a6SMichael Kruse TheLoop->setLoopID(NewLoopID); 11377a614a6SMichael Kruse 11477a614a6SMichael Kruse // Update internal cache. 11577a614a6SMichael Kruse IsVectorized.Value = 1; 11677a614a6SMichael Kruse } 11777a614a6SMichael Kruse 118d4eb13c8SMichael Kruse bool LoopVectorizeHints::allowVectorization( 119d4eb13c8SMichael Kruse Function *F, Loop *L, bool VectorizeOnlyWhenForced) const { 120f2ec16ccSHideki Saito if (getForce() == LoopVectorizeHints::FK_Disabled) { 121d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 122f2ec16ccSHideki Saito emitRemarkWithHints(); 123f2ec16ccSHideki Saito return false; 124f2ec16ccSHideki Saito } 125f2ec16ccSHideki Saito 126d4eb13c8SMichael Kruse if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) { 127d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 128f2ec16ccSHideki Saito emitRemarkWithHints(); 129f2ec16ccSHideki Saito return false; 130f2ec16ccSHideki Saito } 131f2ec16ccSHideki Saito 132f2ec16ccSHideki Saito if (getIsVectorized() == 1) { 133d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 134f2ec16ccSHideki Saito // FIXME: Add interleave.disable metadata. This will allow 135f2ec16ccSHideki Saito // vectorize.disable to be used without disabling the pass and errors 136f2ec16ccSHideki Saito // to differentiate between disabled vectorization and a width of 1. 137f2ec16ccSHideki Saito ORE.emit([&]() { 138f2ec16ccSHideki Saito return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(), 139f2ec16ccSHideki Saito "AllDisabled", L->getStartLoc(), 140f2ec16ccSHideki Saito L->getHeader()) 141f2ec16ccSHideki Saito << "loop not vectorized: vectorization and interleaving are " 142f2ec16ccSHideki Saito "explicitly disabled, or the loop has already been " 143f2ec16ccSHideki Saito "vectorized"; 144f2ec16ccSHideki Saito }); 145f2ec16ccSHideki Saito return false; 146f2ec16ccSHideki Saito } 147f2ec16ccSHideki Saito 148f2ec16ccSHideki Saito return true; 149f2ec16ccSHideki Saito } 150f2ec16ccSHideki Saito 151f2ec16ccSHideki Saito void LoopVectorizeHints::emitRemarkWithHints() const { 152f2ec16ccSHideki Saito using namespace ore; 153f2ec16ccSHideki Saito 154f2ec16ccSHideki Saito ORE.emit([&]() { 155f2ec16ccSHideki Saito if (Force.Value == LoopVectorizeHints::FK_Disabled) 156f2ec16ccSHideki Saito return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled", 157f2ec16ccSHideki Saito TheLoop->getStartLoc(), 158f2ec16ccSHideki Saito TheLoop->getHeader()) 159f2ec16ccSHideki Saito << "loop not vectorized: vectorization is explicitly disabled"; 160f2ec16ccSHideki Saito else { 161f2ec16ccSHideki Saito OptimizationRemarkMissed R(LV_NAME, "MissedDetails", 162f2ec16ccSHideki Saito TheLoop->getStartLoc(), TheLoop->getHeader()); 163f2ec16ccSHideki Saito R << "loop not vectorized"; 164f2ec16ccSHideki Saito if (Force.Value == LoopVectorizeHints::FK_Enabled) { 165f2ec16ccSHideki Saito R << " (Force=" << NV("Force", true); 166f2ec16ccSHideki Saito if (Width.Value != 0) 16771bd59f0SDavid Sherwood R << ", Vector Width=" << NV("VectorWidth", getWidth()); 168ddb3b26aSBardia Mahjour if (getInterleave() != 0) 169ddb3b26aSBardia Mahjour R << ", Interleave Count=" << NV("InterleaveCount", getInterleave()); 170f2ec16ccSHideki Saito R << ")"; 171f2ec16ccSHideki Saito } 172f2ec16ccSHideki Saito return R; 173f2ec16ccSHideki Saito } 174f2ec16ccSHideki Saito }); 175f2ec16ccSHideki Saito } 176f2ec16ccSHideki Saito 177f2ec16ccSHideki Saito const char *LoopVectorizeHints::vectorizeAnalysisPassName() const { 17871bd59f0SDavid Sherwood if (getWidth() == ElementCount::getFixed(1)) 179f2ec16ccSHideki Saito return LV_NAME; 180f2ec16ccSHideki Saito if (getForce() == LoopVectorizeHints::FK_Disabled) 181f2ec16ccSHideki Saito return LV_NAME; 18271bd59f0SDavid Sherwood if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth().isZero()) 183f2ec16ccSHideki Saito return LV_NAME; 184f2ec16ccSHideki Saito return OptimizationRemarkAnalysis::AlwaysPrint; 185f2ec16ccSHideki Saito } 186f2ec16ccSHideki Saito 187f2ec16ccSHideki Saito void LoopVectorizeHints::getHintsFromMetadata() { 188f2ec16ccSHideki Saito MDNode *LoopID = TheLoop->getLoopID(); 189f2ec16ccSHideki Saito if (!LoopID) 190f2ec16ccSHideki Saito return; 191f2ec16ccSHideki Saito 192f2ec16ccSHideki Saito // First operand should refer to the loop id itself. 193f2ec16ccSHideki Saito assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 194f2ec16ccSHideki Saito assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 195f2ec16ccSHideki Saito 196f2ec16ccSHideki Saito for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 197f2ec16ccSHideki Saito const MDString *S = nullptr; 198f2ec16ccSHideki Saito SmallVector<Metadata *, 4> Args; 199f2ec16ccSHideki Saito 200f2ec16ccSHideki Saito // The expected hint is either a MDString or a MDNode with the first 201f2ec16ccSHideki Saito // operand a MDString. 202f2ec16ccSHideki Saito if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 203f2ec16ccSHideki Saito if (!MD || MD->getNumOperands() == 0) 204f2ec16ccSHideki Saito continue; 205f2ec16ccSHideki Saito S = dyn_cast<MDString>(MD->getOperand(0)); 206f2ec16ccSHideki Saito for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 207f2ec16ccSHideki Saito Args.push_back(MD->getOperand(i)); 208f2ec16ccSHideki Saito } else { 209f2ec16ccSHideki Saito S = dyn_cast<MDString>(LoopID->getOperand(i)); 210f2ec16ccSHideki Saito assert(Args.size() == 0 && "too many arguments for MDString"); 211f2ec16ccSHideki Saito } 212f2ec16ccSHideki Saito 213f2ec16ccSHideki Saito if (!S) 214f2ec16ccSHideki Saito continue; 215f2ec16ccSHideki Saito 216f2ec16ccSHideki Saito // Check if the hint starts with the loop metadata prefix. 217f2ec16ccSHideki Saito StringRef Name = S->getString(); 218f2ec16ccSHideki Saito if (Args.size() == 1) 219f2ec16ccSHideki Saito setHint(Name, Args[0]); 220f2ec16ccSHideki Saito } 221f2ec16ccSHideki Saito } 222f2ec16ccSHideki Saito 223f2ec16ccSHideki Saito void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) { 224f2ec16ccSHideki Saito if (!Name.startswith(Prefix())) 225f2ec16ccSHideki Saito return; 226f2ec16ccSHideki Saito Name = Name.substr(Prefix().size(), StringRef::npos); 227f2ec16ccSHideki Saito 228f2ec16ccSHideki Saito const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg); 229f2ec16ccSHideki Saito if (!C) 230f2ec16ccSHideki Saito return; 231f2ec16ccSHideki Saito unsigned Val = C->getZExtValue(); 232f2ec16ccSHideki Saito 23371bd59f0SDavid Sherwood Hint *Hints[] = {&Width, &Interleave, &Force, 23471bd59f0SDavid Sherwood &IsVectorized, &Predicate, &Scalable}; 235f2ec16ccSHideki Saito for (auto H : Hints) { 236f2ec16ccSHideki Saito if (Name == H->Name) { 237f2ec16ccSHideki Saito if (H->validate(Val)) 238f2ec16ccSHideki Saito H->Value = Val; 239f2ec16ccSHideki Saito else 240d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n"); 241f2ec16ccSHideki Saito break; 242f2ec16ccSHideki Saito } 243f2ec16ccSHideki Saito } 244f2ec16ccSHideki Saito } 245f2ec16ccSHideki Saito 246f2ec16ccSHideki Saito // Return true if the inner loop \p Lp is uniform with regard to the outer loop 247f2ec16ccSHideki Saito // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes 248f2ec16ccSHideki Saito // executing the inner loop will execute the same iterations). This check is 249f2ec16ccSHideki Saito // very constrained for now but it will be relaxed in the future. \p Lp is 250f2ec16ccSHideki Saito // considered uniform if it meets all the following conditions: 251f2ec16ccSHideki Saito // 1) it has a canonical IV (starting from 0 and with stride 1), 252f2ec16ccSHideki Saito // 2) its latch terminator is a conditional branch and, 253f2ec16ccSHideki Saito // 3) its latch condition is a compare instruction whose operands are the 254f2ec16ccSHideki Saito // canonical IV and an OuterLp invariant. 255f2ec16ccSHideki Saito // This check doesn't take into account the uniformity of other conditions not 256f2ec16ccSHideki Saito // related to the loop latch because they don't affect the loop uniformity. 257f2ec16ccSHideki Saito // 258f2ec16ccSHideki Saito // NOTE: We decided to keep all these checks and its associated documentation 259f2ec16ccSHideki Saito // together so that we can easily have a picture of the current supported loop 260f2ec16ccSHideki Saito // nests. However, some of the current checks don't depend on \p OuterLp and 261f2ec16ccSHideki Saito // would be redundantly executed for each \p Lp if we invoked this function for 262f2ec16ccSHideki Saito // different candidate outer loops. This is not the case for now because we 263f2ec16ccSHideki Saito // don't currently have the infrastructure to evaluate multiple candidate outer 264f2ec16ccSHideki Saito // loops and \p OuterLp will be a fixed parameter while we only support explicit 265f2ec16ccSHideki Saito // outer loop vectorization. It's also very likely that these checks go away 266f2ec16ccSHideki Saito // before introducing the aforementioned infrastructure. However, if this is not 267f2ec16ccSHideki Saito // the case, we should move the \p OuterLp independent checks to a separate 268f2ec16ccSHideki Saito // function that is only executed once for each \p Lp. 269f2ec16ccSHideki Saito static bool isUniformLoop(Loop *Lp, Loop *OuterLp) { 270f2ec16ccSHideki Saito assert(Lp->getLoopLatch() && "Expected loop with a single latch."); 271f2ec16ccSHideki Saito 272f2ec16ccSHideki Saito // If Lp is the outer loop, it's uniform by definition. 273f2ec16ccSHideki Saito if (Lp == OuterLp) 274f2ec16ccSHideki Saito return true; 275f2ec16ccSHideki Saito assert(OuterLp->contains(Lp) && "OuterLp must contain Lp."); 276f2ec16ccSHideki Saito 277f2ec16ccSHideki Saito // 1. 278f2ec16ccSHideki Saito PHINode *IV = Lp->getCanonicalInductionVariable(); 279f2ec16ccSHideki Saito if (!IV) { 280d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n"); 281f2ec16ccSHideki Saito return false; 282f2ec16ccSHideki Saito } 283f2ec16ccSHideki Saito 284f2ec16ccSHideki Saito // 2. 285f2ec16ccSHideki Saito BasicBlock *Latch = Lp->getLoopLatch(); 286f2ec16ccSHideki Saito auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); 287f2ec16ccSHideki Saito if (!LatchBr || LatchBr->isUnconditional()) { 288d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n"); 289f2ec16ccSHideki Saito return false; 290f2ec16ccSHideki Saito } 291f2ec16ccSHideki Saito 292f2ec16ccSHideki Saito // 3. 293f2ec16ccSHideki Saito auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition()); 294f2ec16ccSHideki Saito if (!LatchCmp) { 295d34e60caSNicola Zaghen LLVM_DEBUG( 296d34e60caSNicola Zaghen dbgs() << "LV: Loop latch condition is not a compare instruction.\n"); 297f2ec16ccSHideki Saito return false; 298f2ec16ccSHideki Saito } 299f2ec16ccSHideki Saito 300f2ec16ccSHideki Saito Value *CondOp0 = LatchCmp->getOperand(0); 301f2ec16ccSHideki Saito Value *CondOp1 = LatchCmp->getOperand(1); 302f2ec16ccSHideki Saito Value *IVUpdate = IV->getIncomingValueForBlock(Latch); 303f2ec16ccSHideki Saito if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) && 304f2ec16ccSHideki Saito !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) { 305d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n"); 306f2ec16ccSHideki Saito return false; 307f2ec16ccSHideki Saito } 308f2ec16ccSHideki Saito 309f2ec16ccSHideki Saito return true; 310f2ec16ccSHideki Saito } 311f2ec16ccSHideki Saito 312f2ec16ccSHideki Saito // Return true if \p Lp and all its nested loops are uniform with regard to \p 313f2ec16ccSHideki Saito // OuterLp. 314f2ec16ccSHideki Saito static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) { 315f2ec16ccSHideki Saito if (!isUniformLoop(Lp, OuterLp)) 316f2ec16ccSHideki Saito return false; 317f2ec16ccSHideki Saito 318f2ec16ccSHideki Saito // Check if nested loops are uniform. 319f2ec16ccSHideki Saito for (Loop *SubLp : *Lp) 320f2ec16ccSHideki Saito if (!isUniformLoopNest(SubLp, OuterLp)) 321f2ec16ccSHideki Saito return false; 322f2ec16ccSHideki Saito 323f2ec16ccSHideki Saito return true; 324f2ec16ccSHideki Saito } 325f2ec16ccSHideki Saito 3265f8f34e4SAdrian Prantl /// Check whether it is safe to if-convert this phi node. 327f2ec16ccSHideki Saito /// 328f2ec16ccSHideki Saito /// Phi nodes with constant expressions that can trap are not safe to if 329f2ec16ccSHideki Saito /// convert. 330f2ec16ccSHideki Saito static bool canIfConvertPHINodes(BasicBlock *BB) { 331f2ec16ccSHideki Saito for (PHINode &Phi : BB->phis()) { 332f2ec16ccSHideki Saito for (Value *V : Phi.incoming_values()) 333f2ec16ccSHideki Saito if (auto *C = dyn_cast<Constant>(V)) 334f2ec16ccSHideki Saito if (C->canTrap()) 335f2ec16ccSHideki Saito return false; 336f2ec16ccSHideki Saito } 337f2ec16ccSHideki Saito return true; 338f2ec16ccSHideki Saito } 339f2ec16ccSHideki Saito 340f2ec16ccSHideki Saito static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 341f2ec16ccSHideki Saito if (Ty->isPointerTy()) 342f2ec16ccSHideki Saito return DL.getIntPtrType(Ty); 343f2ec16ccSHideki Saito 344f2ec16ccSHideki Saito // It is possible that char's or short's overflow when we ask for the loop's 345f2ec16ccSHideki Saito // trip count, work around this by changing the type size. 346f2ec16ccSHideki Saito if (Ty->getScalarSizeInBits() < 32) 347f2ec16ccSHideki Saito return Type::getInt32Ty(Ty->getContext()); 348f2ec16ccSHideki Saito 349f2ec16ccSHideki Saito return Ty; 350f2ec16ccSHideki Saito } 351f2ec16ccSHideki Saito 352f2ec16ccSHideki Saito static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 353f2ec16ccSHideki Saito Ty0 = convertPointerToIntegerType(DL, Ty0); 354f2ec16ccSHideki Saito Ty1 = convertPointerToIntegerType(DL, Ty1); 355f2ec16ccSHideki Saito if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 356f2ec16ccSHideki Saito return Ty0; 357f2ec16ccSHideki Saito return Ty1; 358f2ec16ccSHideki Saito } 359f2ec16ccSHideki Saito 3605f8f34e4SAdrian Prantl /// Check that the instruction has outside loop users and is not an 361f2ec16ccSHideki Saito /// identified reduction variable. 362f2ec16ccSHideki Saito static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 363f2ec16ccSHideki Saito SmallPtrSetImpl<Value *> &AllowedExit) { 36460a1e4ddSAnna Thomas // Reductions, Inductions and non-header phis are allowed to have exit users. All 365f2ec16ccSHideki Saito // other instructions must not have external users. 366f2ec16ccSHideki Saito if (!AllowedExit.count(Inst)) 367f2ec16ccSHideki Saito // Check that all of the users of the loop are inside the BB. 368f2ec16ccSHideki Saito for (User *U : Inst->users()) { 369f2ec16ccSHideki Saito Instruction *UI = cast<Instruction>(U); 370f2ec16ccSHideki Saito // This user may be a reduction exit value. 371f2ec16ccSHideki Saito if (!TheLoop->contains(UI)) { 372d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 373f2ec16ccSHideki Saito return true; 374f2ec16ccSHideki Saito } 375f2ec16ccSHideki Saito } 376f2ec16ccSHideki Saito return false; 377f2ec16ccSHideki Saito } 378f2ec16ccSHideki Saito 379*f82966d1SSander de Smalen int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) const { 380f2ec16ccSHideki Saito const ValueToValueMap &Strides = 381f2ec16ccSHideki Saito getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap(); 382f2ec16ccSHideki Saito 3837bedae7dSHiroshi Yamauchi Function *F = TheLoop->getHeader()->getParent(); 3847bedae7dSHiroshi Yamauchi bool OptForSize = F->hasOptSize() || 3857bedae7dSHiroshi Yamauchi llvm::shouldOptimizeForSize(TheLoop->getHeader(), PSI, BFI, 3867bedae7dSHiroshi Yamauchi PGSOQueryType::IRPass); 3877bedae7dSHiroshi Yamauchi bool CanAddPredicate = !OptForSize; 388d1170dbeSSjoerd Meijer int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, CanAddPredicate, false); 389f2ec16ccSHideki Saito if (Stride == 1 || Stride == -1) 390f2ec16ccSHideki Saito return Stride; 391f2ec16ccSHideki Saito return 0; 392f2ec16ccSHideki Saito } 393f2ec16ccSHideki Saito 394f2ec16ccSHideki Saito bool LoopVectorizationLegality::isUniform(Value *V) { 395f2ec16ccSHideki Saito return LAI->isUniform(V); 396f2ec16ccSHideki Saito } 397f2ec16ccSHideki Saito 398f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeOuterLoop() { 39989c1e35fSStefanos Baziotis assert(!TheLoop->isInnermost() && "We are not vectorizing an outer loop."); 400f2ec16ccSHideki Saito // Store the result and return it at the end instead of exiting early, in case 401f2ec16ccSHideki Saito // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 402f2ec16ccSHideki Saito bool Result = true; 403f2ec16ccSHideki Saito bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 404f2ec16ccSHideki Saito 405f2ec16ccSHideki Saito for (BasicBlock *BB : TheLoop->blocks()) { 406f2ec16ccSHideki Saito // Check whether the BB terminator is a BranchInst. Any other terminator is 407f2ec16ccSHideki Saito // not supported yet. 408f2ec16ccSHideki Saito auto *Br = dyn_cast<BranchInst>(BB->getTerminator()); 409f2ec16ccSHideki Saito if (!Br) { 4109e97caf5SRenato Golin reportVectorizationFailure("Unsupported basic block terminator", 4119e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 412ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 413f2ec16ccSHideki Saito if (DoExtraAnalysis) 414f2ec16ccSHideki Saito Result = false; 415f2ec16ccSHideki Saito else 416f2ec16ccSHideki Saito return false; 417f2ec16ccSHideki Saito } 418f2ec16ccSHideki Saito 419f2ec16ccSHideki Saito // Check whether the BranchInst is a supported one. Only unconditional 420f2ec16ccSHideki Saito // branches, conditional branches with an outer loop invariant condition or 421f2ec16ccSHideki Saito // backedges are supported. 4224e4ecae0SHideki Saito // FIXME: We skip these checks when VPlan predication is enabled as we 4234e4ecae0SHideki Saito // want to allow divergent branches. This whole check will be removed 4244e4ecae0SHideki Saito // once VPlan predication is on by default. 4254e4ecae0SHideki Saito if (!EnableVPlanPredication && Br && Br->isConditional() && 426f2ec16ccSHideki Saito !TheLoop->isLoopInvariant(Br->getCondition()) && 427f2ec16ccSHideki Saito !LI->isLoopHeader(Br->getSuccessor(0)) && 428f2ec16ccSHideki Saito !LI->isLoopHeader(Br->getSuccessor(1))) { 4299e97caf5SRenato Golin reportVectorizationFailure("Unsupported conditional branch", 4309e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 431ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 432f2ec16ccSHideki Saito if (DoExtraAnalysis) 433f2ec16ccSHideki Saito Result = false; 434f2ec16ccSHideki Saito else 435f2ec16ccSHideki Saito return false; 436f2ec16ccSHideki Saito } 437f2ec16ccSHideki Saito } 438f2ec16ccSHideki Saito 439f2ec16ccSHideki Saito // Check whether inner loops are uniform. At this point, we only support 440f2ec16ccSHideki Saito // simple outer loops scenarios with uniform nested loops. 441f2ec16ccSHideki Saito if (!isUniformLoopNest(TheLoop /*loop nest*/, 442f2ec16ccSHideki Saito TheLoop /*context outer loop*/)) { 4439e97caf5SRenato Golin reportVectorizationFailure("Outer loop contains divergent loops", 4449e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 445ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 446f2ec16ccSHideki Saito if (DoExtraAnalysis) 447f2ec16ccSHideki Saito Result = false; 448f2ec16ccSHideki Saito else 449f2ec16ccSHideki Saito return false; 450f2ec16ccSHideki Saito } 451f2ec16ccSHideki Saito 452ea7f3035SHideki Saito // Check whether we are able to set up outer loop induction. 453ea7f3035SHideki Saito if (!setupOuterLoopInductions()) { 4549e97caf5SRenato Golin reportVectorizationFailure("Unsupported outer loop Phi(s)", 4559e97caf5SRenato Golin "Unsupported outer loop Phi(s)", 456ec818d7fSHideki Saito "UnsupportedPhi", ORE, TheLoop); 457ea7f3035SHideki Saito if (DoExtraAnalysis) 458ea7f3035SHideki Saito Result = false; 459ea7f3035SHideki Saito else 460ea7f3035SHideki Saito return false; 461ea7f3035SHideki Saito } 462ea7f3035SHideki Saito 463f2ec16ccSHideki Saito return Result; 464f2ec16ccSHideki Saito } 465f2ec16ccSHideki Saito 466f2ec16ccSHideki Saito void LoopVectorizationLegality::addInductionPhi( 467f2ec16ccSHideki Saito PHINode *Phi, const InductionDescriptor &ID, 468f2ec16ccSHideki Saito SmallPtrSetImpl<Value *> &AllowedExit) { 469f2ec16ccSHideki Saito Inductions[Phi] = ID; 470f2ec16ccSHideki Saito 471f2ec16ccSHideki Saito // In case this induction also comes with casts that we know we can ignore 472f2ec16ccSHideki Saito // in the vectorized loop body, record them here. All casts could be recorded 473f2ec16ccSHideki Saito // here for ignoring, but suffices to record only the first (as it is the 474f2ec16ccSHideki Saito // only one that may bw used outside the cast sequence). 475f2ec16ccSHideki Saito const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts(); 476f2ec16ccSHideki Saito if (!Casts.empty()) 477f2ec16ccSHideki Saito InductionCastsToIgnore.insert(*Casts.begin()); 478f2ec16ccSHideki Saito 479f2ec16ccSHideki Saito Type *PhiTy = Phi->getType(); 480f2ec16ccSHideki Saito const DataLayout &DL = Phi->getModule()->getDataLayout(); 481f2ec16ccSHideki Saito 482f2ec16ccSHideki Saito // Get the widest type. 483f2ec16ccSHideki Saito if (!PhiTy->isFloatingPointTy()) { 484f2ec16ccSHideki Saito if (!WidestIndTy) 485f2ec16ccSHideki Saito WidestIndTy = convertPointerToIntegerType(DL, PhiTy); 486f2ec16ccSHideki Saito else 487f2ec16ccSHideki Saito WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy); 488f2ec16ccSHideki Saito } 489f2ec16ccSHideki Saito 490f2ec16ccSHideki Saito // Int inductions are special because we only allow one IV. 491f2ec16ccSHideki Saito if (ID.getKind() == InductionDescriptor::IK_IntInduction && 492f2ec16ccSHideki Saito ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() && 493f2ec16ccSHideki Saito isa<Constant>(ID.getStartValue()) && 494f2ec16ccSHideki Saito cast<Constant>(ID.getStartValue())->isNullValue()) { 495f2ec16ccSHideki Saito 496f2ec16ccSHideki Saito // Use the phi node with the widest type as induction. Use the last 497f2ec16ccSHideki Saito // one if there are multiple (no good reason for doing this other 498f2ec16ccSHideki Saito // than it is expedient). We've checked that it begins at zero and 499f2ec16ccSHideki Saito // steps by one, so this is a canonical induction variable. 500f2ec16ccSHideki Saito if (!PrimaryInduction || PhiTy == WidestIndTy) 501f2ec16ccSHideki Saito PrimaryInduction = Phi; 502f2ec16ccSHideki Saito } 503f2ec16ccSHideki Saito 504f2ec16ccSHideki Saito // Both the PHI node itself, and the "post-increment" value feeding 505f2ec16ccSHideki Saito // back into the PHI node may have external users. 506f2ec16ccSHideki Saito // We can allow those uses, except if the SCEVs we have for them rely 507f2ec16ccSHideki Saito // on predicates that only hold within the loop, since allowing the exit 5086a1dd77fSAnna Thomas // currently means re-using this SCEV outside the loop (see PR33706 for more 5096a1dd77fSAnna Thomas // details). 510f2ec16ccSHideki Saito if (PSE.getUnionPredicate().isAlwaysTrue()) { 511f2ec16ccSHideki Saito AllowedExit.insert(Phi); 512f2ec16ccSHideki Saito AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch())); 513f2ec16ccSHideki Saito } 514f2ec16ccSHideki Saito 515d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n"); 516f2ec16ccSHideki Saito } 517f2ec16ccSHideki Saito 518ea7f3035SHideki Saito bool LoopVectorizationLegality::setupOuterLoopInductions() { 519ea7f3035SHideki Saito BasicBlock *Header = TheLoop->getHeader(); 520ea7f3035SHideki Saito 521ea7f3035SHideki Saito // Returns true if a given Phi is a supported induction. 522ea7f3035SHideki Saito auto isSupportedPhi = [&](PHINode &Phi) -> bool { 523ea7f3035SHideki Saito InductionDescriptor ID; 524ea7f3035SHideki Saito if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) && 525ea7f3035SHideki Saito ID.getKind() == InductionDescriptor::IK_IntInduction) { 526ea7f3035SHideki Saito addInductionPhi(&Phi, ID, AllowedExit); 527ea7f3035SHideki Saito return true; 528ea7f3035SHideki Saito } else { 529ea7f3035SHideki Saito // Bail out for any Phi in the outer loop header that is not a supported 530ea7f3035SHideki Saito // induction. 531ea7f3035SHideki Saito LLVM_DEBUG( 532ea7f3035SHideki Saito dbgs() 533ea7f3035SHideki Saito << "LV: Found unsupported PHI for outer loop vectorization.\n"); 534ea7f3035SHideki Saito return false; 535ea7f3035SHideki Saito } 536ea7f3035SHideki Saito }; 537ea7f3035SHideki Saito 538ea7f3035SHideki Saito if (llvm::all_of(Header->phis(), isSupportedPhi)) 539ea7f3035SHideki Saito return true; 540ea7f3035SHideki Saito else 541ea7f3035SHideki Saito return false; 542ea7f3035SHideki Saito } 543ea7f3035SHideki Saito 54466c120f0SFrancesco Petrogalli /// Checks if a function is scalarizable according to the TLI, in 54566c120f0SFrancesco Petrogalli /// the sense that it should be vectorized and then expanded in 54666c120f0SFrancesco Petrogalli /// multiple scalarcalls. This is represented in the 54766c120f0SFrancesco Petrogalli /// TLI via mappings that do not specify a vector name, as in the 54866c120f0SFrancesco Petrogalli /// following example: 54966c120f0SFrancesco Petrogalli /// 55066c120f0SFrancesco Petrogalli /// const VecDesc VecIntrinsics[] = { 55166c120f0SFrancesco Petrogalli /// {"llvm.phx.abs.i32", "", 4} 55266c120f0SFrancesco Petrogalli /// }; 55366c120f0SFrancesco Petrogalli static bool isTLIScalarize(const TargetLibraryInfo &TLI, const CallInst &CI) { 55466c120f0SFrancesco Petrogalli const StringRef ScalarName = CI.getCalledFunction()->getName(); 55566c120f0SFrancesco Petrogalli bool Scalarize = TLI.isFunctionVectorizable(ScalarName); 55666c120f0SFrancesco Petrogalli // Check that all known VFs are not associated to a vector 55766c120f0SFrancesco Petrogalli // function, i.e. the vector name is emty. 55801b87444SDavid Sherwood if (Scalarize) { 55901b87444SDavid Sherwood ElementCount WidestFixedVF, WidestScalableVF; 56001b87444SDavid Sherwood TLI.getWidestVF(ScalarName, WidestFixedVF, WidestScalableVF); 56101b87444SDavid Sherwood for (ElementCount VF = ElementCount::getFixed(2); 56201b87444SDavid Sherwood ElementCount::isKnownLE(VF, WidestFixedVF); VF *= 2) 56366c120f0SFrancesco Petrogalli Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF); 56401b87444SDavid Sherwood for (ElementCount VF = ElementCount::getScalable(1); 56501b87444SDavid Sherwood ElementCount::isKnownLE(VF, WidestScalableVF); VF *= 2) 56601b87444SDavid Sherwood Scalarize &= !TLI.isFunctionVectorizable(ScalarName, VF); 56701b87444SDavid Sherwood assert((WidestScalableVF.isZero() || !Scalarize) && 56801b87444SDavid Sherwood "Caller may decide to scalarize a variant using a scalable VF"); 56966c120f0SFrancesco Petrogalli } 57066c120f0SFrancesco Petrogalli return Scalarize; 57166c120f0SFrancesco Petrogalli } 57266c120f0SFrancesco Petrogalli 573f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeInstrs() { 574f2ec16ccSHideki Saito BasicBlock *Header = TheLoop->getHeader(); 575f2ec16ccSHideki Saito 576f2ec16ccSHideki Saito // For each block in the loop. 577f2ec16ccSHideki Saito for (BasicBlock *BB : TheLoop->blocks()) { 578f2ec16ccSHideki Saito // Scan the instructions in the block and look for hazards. 579f2ec16ccSHideki Saito for (Instruction &I : *BB) { 580f2ec16ccSHideki Saito if (auto *Phi = dyn_cast<PHINode>(&I)) { 581f2ec16ccSHideki Saito Type *PhiTy = Phi->getType(); 582f2ec16ccSHideki Saito // Check that this PHI type is allowed. 583f2ec16ccSHideki Saito if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 584f2ec16ccSHideki Saito !PhiTy->isPointerTy()) { 5859e97caf5SRenato Golin reportVectorizationFailure("Found a non-int non-pointer PHI", 5869e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 587ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 588f2ec16ccSHideki Saito return false; 589f2ec16ccSHideki Saito } 590f2ec16ccSHideki Saito 591f2ec16ccSHideki Saito // If this PHINode is not in the header block, then we know that we 592f2ec16ccSHideki Saito // can convert it to select during if-conversion. No need to check if 593f2ec16ccSHideki Saito // the PHIs in this block are induction or reduction variables. 594f2ec16ccSHideki Saito if (BB != Header) { 59560a1e4ddSAnna Thomas // Non-header phi nodes that have outside uses can be vectorized. Add 59660a1e4ddSAnna Thomas // them to the list of allowed exits. 59760a1e4ddSAnna Thomas // Unsafe cyclic dependencies with header phis are identified during 59860a1e4ddSAnna Thomas // legalization for reduction, induction and first order 59960a1e4ddSAnna Thomas // recurrences. 600dd18ce45SBjorn Pettersson AllowedExit.insert(&I); 601f2ec16ccSHideki Saito continue; 602f2ec16ccSHideki Saito } 603f2ec16ccSHideki Saito 604f2ec16ccSHideki Saito // We only allow if-converted PHIs with exactly two incoming values. 605f2ec16ccSHideki Saito if (Phi->getNumIncomingValues() != 2) { 6069e97caf5SRenato Golin reportVectorizationFailure("Found an invalid PHI", 6079e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 608ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop, Phi); 609f2ec16ccSHideki Saito return false; 610f2ec16ccSHideki Saito } 611f2ec16ccSHideki Saito 612f2ec16ccSHideki Saito RecurrenceDescriptor RedDes; 613f2ec16ccSHideki Saito if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, 614f2ec16ccSHideki Saito DT)) { 615b3a33553SSanjay Patel Requirements->addExactFPMathInst(RedDes.getExactFPMathInst()); 616f2ec16ccSHideki Saito AllowedExit.insert(RedDes.getLoopExitInstr()); 617f2ec16ccSHideki Saito Reductions[Phi] = RedDes; 618f2ec16ccSHideki Saito continue; 619f2ec16ccSHideki Saito } 620f2ec16ccSHideki Saito 621b02b0ad8SAnna Thomas // TODO: Instead of recording the AllowedExit, it would be good to record the 622b02b0ad8SAnna Thomas // complementary set: NotAllowedExit. These include (but may not be 623b02b0ad8SAnna Thomas // limited to): 624b02b0ad8SAnna Thomas // 1. Reduction phis as they represent the one-before-last value, which 625b02b0ad8SAnna Thomas // is not available when vectorized 626b02b0ad8SAnna Thomas // 2. Induction phis and increment when SCEV predicates cannot be used 627b02b0ad8SAnna Thomas // outside the loop - see addInductionPhi 628b02b0ad8SAnna Thomas // 3. Non-Phis with outside uses when SCEV predicates cannot be used 629b02b0ad8SAnna Thomas // outside the loop - see call to hasOutsideLoopUser in the non-phi 630b02b0ad8SAnna Thomas // handling below 631b02b0ad8SAnna Thomas // 4. FirstOrderRecurrence phis that can possibly be handled by 632b02b0ad8SAnna Thomas // extraction. 633b02b0ad8SAnna Thomas // By recording these, we can then reason about ways to vectorize each 634b02b0ad8SAnna Thomas // of these NotAllowedExit. 635f2ec16ccSHideki Saito InductionDescriptor ID; 636f2ec16ccSHideki Saito if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) { 637f2ec16ccSHideki Saito addInductionPhi(Phi, ID, AllowedExit); 63836a489d1SSanjay Patel Requirements->addExactFPMathInst(ID.getExactFPMathInst()); 639f2ec16ccSHideki Saito continue; 640f2ec16ccSHideki Saito } 641f2ec16ccSHideki Saito 642f2ec16ccSHideki Saito if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, 643f2ec16ccSHideki Saito SinkAfter, DT)) { 6448e0c5f72SAyal Zaks AllowedExit.insert(Phi); 645f2ec16ccSHideki Saito FirstOrderRecurrences.insert(Phi); 646f2ec16ccSHideki Saito continue; 647f2ec16ccSHideki Saito } 648f2ec16ccSHideki Saito 649f2ec16ccSHideki Saito // As a last resort, coerce the PHI to a AddRec expression 650f2ec16ccSHideki Saito // and re-try classifying it a an induction PHI. 651f2ec16ccSHideki Saito if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) { 652f2ec16ccSHideki Saito addInductionPhi(Phi, ID, AllowedExit); 653f2ec16ccSHideki Saito continue; 654f2ec16ccSHideki Saito } 655f2ec16ccSHideki Saito 6569e97caf5SRenato Golin reportVectorizationFailure("Found an unidentified PHI", 6579e97caf5SRenato Golin "value that could not be identified as " 6589e97caf5SRenato Golin "reduction is used outside the loop", 659ec818d7fSHideki Saito "NonReductionValueUsedOutsideLoop", ORE, TheLoop, Phi); 660f2ec16ccSHideki Saito return false; 661f2ec16ccSHideki Saito } // end of PHI handling 662f2ec16ccSHideki Saito 663f2ec16ccSHideki Saito // We handle calls that: 664f2ec16ccSHideki Saito // * Are debug info intrinsics. 665f2ec16ccSHideki Saito // * Have a mapping to an IR intrinsic. 666f2ec16ccSHideki Saito // * Have a vector version available. 667f2ec16ccSHideki Saito auto *CI = dyn_cast<CallInst>(&I); 66866c120f0SFrancesco Petrogalli 669f2ec16ccSHideki Saito if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && 670f2ec16ccSHideki Saito !isa<DbgInfoIntrinsic>(CI) && 671f2ec16ccSHideki Saito !(CI->getCalledFunction() && TLI && 67266c120f0SFrancesco Petrogalli (!VFDatabase::getMappings(*CI).empty() || 67366c120f0SFrancesco Petrogalli isTLIScalarize(*TLI, *CI)))) { 6747d65fe5cSSanjay Patel // If the call is a recognized math libary call, it is likely that 6757d65fe5cSSanjay Patel // we can vectorize it given loosened floating-point constraints. 6767d65fe5cSSanjay Patel LibFunc Func; 6777d65fe5cSSanjay Patel bool IsMathLibCall = 6787d65fe5cSSanjay Patel TLI && CI->getCalledFunction() && 6797d65fe5cSSanjay Patel CI->getType()->isFloatingPointTy() && 6807d65fe5cSSanjay Patel TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) && 6817d65fe5cSSanjay Patel TLI->hasOptimizedCodeGen(Func); 6827d65fe5cSSanjay Patel 6837d65fe5cSSanjay Patel if (IsMathLibCall) { 6847d65fe5cSSanjay Patel // TODO: Ideally, we should not use clang-specific language here, 6857d65fe5cSSanjay Patel // but it's hard to provide meaningful yet generic advice. 6867d65fe5cSSanjay Patel // Also, should this be guarded by allowExtraAnalysis() and/or be part 6877d65fe5cSSanjay Patel // of the returned info from isFunctionVectorizable()? 68866c120f0SFrancesco Petrogalli reportVectorizationFailure( 68966c120f0SFrancesco Petrogalli "Found a non-intrinsic callsite", 6909e97caf5SRenato Golin "library call cannot be vectorized. " 6917d65fe5cSSanjay Patel "Try compiling with -fno-math-errno, -ffast-math, " 6929e97caf5SRenato Golin "or similar flags", 693ec818d7fSHideki Saito "CantVectorizeLibcall", ORE, TheLoop, CI); 6947d65fe5cSSanjay Patel } else { 6959e97caf5SRenato Golin reportVectorizationFailure("Found a non-intrinsic callsite", 6969e97caf5SRenato Golin "call instruction cannot be vectorized", 697ec818d7fSHideki Saito "CantVectorizeLibcall", ORE, TheLoop, CI); 6987d65fe5cSSanjay Patel } 699f2ec16ccSHideki Saito return false; 700f2ec16ccSHideki Saito } 701f2ec16ccSHideki Saito 702a066f1f9SSimon Pilgrim // Some intrinsics have scalar arguments and should be same in order for 703a066f1f9SSimon Pilgrim // them to be vectorized (i.e. loop invariant). 704a066f1f9SSimon Pilgrim if (CI) { 705f2ec16ccSHideki Saito auto *SE = PSE.getSE(); 706a066f1f9SSimon Pilgrim Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI); 707a066f1f9SSimon Pilgrim for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) 708a066f1f9SSimon Pilgrim if (hasVectorInstrinsicScalarOpd(IntrinID, i)) { 709a066f1f9SSimon Pilgrim if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) { 7109e97caf5SRenato Golin reportVectorizationFailure("Found unvectorizable intrinsic", 7119e97caf5SRenato Golin "intrinsic instruction cannot be vectorized", 712ec818d7fSHideki Saito "CantVectorizeIntrinsic", ORE, TheLoop, CI); 713f2ec16ccSHideki Saito return false; 714f2ec16ccSHideki Saito } 715f2ec16ccSHideki Saito } 716a066f1f9SSimon Pilgrim } 717f2ec16ccSHideki Saito 718f2ec16ccSHideki Saito // Check that the instruction return type is vectorizable. 719f2ec16ccSHideki Saito // Also, we can't vectorize extractelement instructions. 720f2ec16ccSHideki Saito if ((!VectorType::isValidElementType(I.getType()) && 721f2ec16ccSHideki Saito !I.getType()->isVoidTy()) || 722f2ec16ccSHideki Saito isa<ExtractElementInst>(I)) { 7239e97caf5SRenato Golin reportVectorizationFailure("Found unvectorizable type", 7249e97caf5SRenato Golin "instruction return type cannot be vectorized", 725ec818d7fSHideki Saito "CantVectorizeInstructionReturnType", ORE, TheLoop, &I); 726f2ec16ccSHideki Saito return false; 727f2ec16ccSHideki Saito } 728f2ec16ccSHideki Saito 729f2ec16ccSHideki Saito // Check that the stored type is vectorizable. 730f2ec16ccSHideki Saito if (auto *ST = dyn_cast<StoreInst>(&I)) { 731f2ec16ccSHideki Saito Type *T = ST->getValueOperand()->getType(); 732f2ec16ccSHideki Saito if (!VectorType::isValidElementType(T)) { 7339e97caf5SRenato Golin reportVectorizationFailure("Store instruction cannot be vectorized", 7349e97caf5SRenato Golin "store instruction cannot be vectorized", 735ec818d7fSHideki Saito "CantVectorizeStore", ORE, TheLoop, ST); 736f2ec16ccSHideki Saito return false; 737f2ec16ccSHideki Saito } 738f2ec16ccSHideki Saito 7396452bdd2SWarren Ristow // For nontemporal stores, check that a nontemporal vector version is 7406452bdd2SWarren Ristow // supported on the target. 7416452bdd2SWarren Ristow if (ST->getMetadata(LLVMContext::MD_nontemporal)) { 7426452bdd2SWarren Ristow // Arbitrarily try a vector of 2 elements. 7436913812aSFangrui Song auto *VecTy = FixedVectorType::get(T, /*NumElts=*/2); 7446452bdd2SWarren Ristow assert(VecTy && "did not find vectorized version of stored type"); 74552e98f62SNikita Popov if (!TTI->isLegalNTStore(VecTy, ST->getAlign())) { 7466452bdd2SWarren Ristow reportVectorizationFailure( 7476452bdd2SWarren Ristow "nontemporal store instruction cannot be vectorized", 7486452bdd2SWarren Ristow "nontemporal store instruction cannot be vectorized", 749ec818d7fSHideki Saito "CantVectorizeNontemporalStore", ORE, TheLoop, ST); 7506452bdd2SWarren Ristow return false; 7516452bdd2SWarren Ristow } 7526452bdd2SWarren Ristow } 7536452bdd2SWarren Ristow 7546452bdd2SWarren Ristow } else if (auto *LD = dyn_cast<LoadInst>(&I)) { 7556452bdd2SWarren Ristow if (LD->getMetadata(LLVMContext::MD_nontemporal)) { 7566452bdd2SWarren Ristow // For nontemporal loads, check that a nontemporal vector version is 7576452bdd2SWarren Ristow // supported on the target (arbitrarily try a vector of 2 elements). 7586913812aSFangrui Song auto *VecTy = FixedVectorType::get(I.getType(), /*NumElts=*/2); 7596452bdd2SWarren Ristow assert(VecTy && "did not find vectorized version of load type"); 76052e98f62SNikita Popov if (!TTI->isLegalNTLoad(VecTy, LD->getAlign())) { 7616452bdd2SWarren Ristow reportVectorizationFailure( 7626452bdd2SWarren Ristow "nontemporal load instruction cannot be vectorized", 7636452bdd2SWarren Ristow "nontemporal load instruction cannot be vectorized", 764ec818d7fSHideki Saito "CantVectorizeNontemporalLoad", ORE, TheLoop, LD); 7656452bdd2SWarren Ristow return false; 7666452bdd2SWarren Ristow } 7676452bdd2SWarren Ristow } 7686452bdd2SWarren Ristow 769f2ec16ccSHideki Saito // FP instructions can allow unsafe algebra, thus vectorizable by 770f2ec16ccSHideki Saito // non-IEEE-754 compliant SIMD units. 771f2ec16ccSHideki Saito // This applies to floating-point math operations and calls, not memory 772f2ec16ccSHideki Saito // operations, shuffles, or casts, as they don't change precision or 773f2ec16ccSHideki Saito // semantics. 774f2ec16ccSHideki Saito } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) && 775f2ec16ccSHideki Saito !I.isFast()) { 776d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n"); 777f2ec16ccSHideki Saito Hints->setPotentiallyUnsafe(); 778f2ec16ccSHideki Saito } 779f2ec16ccSHideki Saito 780f2ec16ccSHideki Saito // Reduction instructions are allowed to have exit users. 781f2ec16ccSHideki Saito // All other instructions must not have external users. 782f2ec16ccSHideki Saito if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) { 783b02b0ad8SAnna Thomas // We can safely vectorize loops where instructions within the loop are 784b02b0ad8SAnna Thomas // used outside the loop only if the SCEV predicates within the loop is 785b02b0ad8SAnna Thomas // same as outside the loop. Allowing the exit means reusing the SCEV 786b02b0ad8SAnna Thomas // outside the loop. 787b02b0ad8SAnna Thomas if (PSE.getUnionPredicate().isAlwaysTrue()) { 788b02b0ad8SAnna Thomas AllowedExit.insert(&I); 789b02b0ad8SAnna Thomas continue; 790b02b0ad8SAnna Thomas } 7919e97caf5SRenato Golin reportVectorizationFailure("Value cannot be used outside the loop", 7929e97caf5SRenato Golin "value cannot be used outside the loop", 793ec818d7fSHideki Saito "ValueUsedOutsideLoop", ORE, TheLoop, &I); 794f2ec16ccSHideki Saito return false; 795f2ec16ccSHideki Saito } 796f2ec16ccSHideki Saito } // next instr. 797f2ec16ccSHideki Saito } 798f2ec16ccSHideki Saito 799f2ec16ccSHideki Saito if (!PrimaryInduction) { 800f2ec16ccSHideki Saito if (Inductions.empty()) { 8019e97caf5SRenato Golin reportVectorizationFailure("Did not find one integer induction var", 8029e97caf5SRenato Golin "loop induction variable could not be identified", 803ec818d7fSHideki Saito "NoInductionVariable", ORE, TheLoop); 804f2ec16ccSHideki Saito return false; 8054f27730eSWarren Ristow } else if (!WidestIndTy) { 8069e97caf5SRenato Golin reportVectorizationFailure("Did not find one integer induction var", 8079e97caf5SRenato Golin "integer loop induction variable could not be identified", 808ec818d7fSHideki Saito "NoIntegerInductionVariable", ORE, TheLoop); 8094f27730eSWarren Ristow return false; 8109e97caf5SRenato Golin } else { 8119e97caf5SRenato Golin LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 812f2ec16ccSHideki Saito } 813f2ec16ccSHideki Saito } 814f2ec16ccSHideki Saito 8159d24933fSFlorian Hahn // For first order recurrences, we use the previous value (incoming value from 8169d24933fSFlorian Hahn // the latch) to check if it dominates all users of the recurrence. Bail out 8179d24933fSFlorian Hahn // if we have to sink such an instruction for another recurrence, as the 8189d24933fSFlorian Hahn // dominance requirement may not hold after sinking. 8199d24933fSFlorian Hahn BasicBlock *LoopLatch = TheLoop->getLoopLatch(); 8209d24933fSFlorian Hahn if (any_of(FirstOrderRecurrences, [LoopLatch, this](const PHINode *Phi) { 8219d24933fSFlorian Hahn Instruction *V = 8229d24933fSFlorian Hahn cast<Instruction>(Phi->getIncomingValueForBlock(LoopLatch)); 8239d24933fSFlorian Hahn return SinkAfter.find(V) != SinkAfter.end(); 8249d24933fSFlorian Hahn })) 8259d24933fSFlorian Hahn return false; 8269d24933fSFlorian Hahn 827f2ec16ccSHideki Saito // Now we know the widest induction type, check if our found induction 828f2ec16ccSHideki Saito // is the same size. If it's not, unset it here and InnerLoopVectorizer 829f2ec16ccSHideki Saito // will create another. 830f2ec16ccSHideki Saito if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType()) 831f2ec16ccSHideki Saito PrimaryInduction = nullptr; 832f2ec16ccSHideki Saito 833f2ec16ccSHideki Saito return true; 834f2ec16ccSHideki Saito } 835f2ec16ccSHideki Saito 836f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeMemory() { 837f2ec16ccSHideki Saito LAI = &(*GetLAA)(*TheLoop); 838f2ec16ccSHideki Saito const OptimizationRemarkAnalysis *LAR = LAI->getReport(); 839f2ec16ccSHideki Saito if (LAR) { 840f2ec16ccSHideki Saito ORE->emit([&]() { 841f2ec16ccSHideki Saito return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(), 842f2ec16ccSHideki Saito "loop not vectorized: ", *LAR); 843f2ec16ccSHideki Saito }); 844f2ec16ccSHideki Saito } 845f2ec16ccSHideki Saito if (!LAI->canVectorizeMemory()) 846f2ec16ccSHideki Saito return false; 847f2ec16ccSHideki Saito 8485e9215f0SAnna Thomas if (LAI->hasDependenceInvolvingLoopInvariantAddress()) { 8499e97caf5SRenato Golin reportVectorizationFailure("Stores to a uniform address", 8509e97caf5SRenato Golin "write to a loop invariant address could not be vectorized", 851ec818d7fSHideki Saito "CantVectorizeStoreToLoopInvariantAddress", ORE, TheLoop); 852f2ec16ccSHideki Saito return false; 853f2ec16ccSHideki Saito } 854f2ec16ccSHideki Saito Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks()); 855f2ec16ccSHideki Saito PSE.addPredicate(LAI->getPSE().getUnionPredicate()); 856f2ec16ccSHideki Saito 857f2ec16ccSHideki Saito return true; 858f2ec16ccSHideki Saito } 859f2ec16ccSHideki Saito 860f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionPhi(const Value *V) { 861f2ec16ccSHideki Saito Value *In0 = const_cast<Value *>(V); 862f2ec16ccSHideki Saito PHINode *PN = dyn_cast_or_null<PHINode>(In0); 863f2ec16ccSHideki Saito if (!PN) 864f2ec16ccSHideki Saito return false; 865f2ec16ccSHideki Saito 866f2ec16ccSHideki Saito return Inductions.count(PN); 867f2ec16ccSHideki Saito } 868f2ec16ccSHideki Saito 869f2ec16ccSHideki Saito bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) { 870f2ec16ccSHideki Saito auto *Inst = dyn_cast<Instruction>(V); 871f2ec16ccSHideki Saito return (Inst && InductionCastsToIgnore.count(Inst)); 872f2ec16ccSHideki Saito } 873f2ec16ccSHideki Saito 874f2ec16ccSHideki Saito bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 875f2ec16ccSHideki Saito return isInductionPhi(V) || isCastedInductionVariable(V); 876f2ec16ccSHideki Saito } 877f2ec16ccSHideki Saito 878f2ec16ccSHideki Saito bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) { 879f2ec16ccSHideki Saito return FirstOrderRecurrences.count(Phi); 880f2ec16ccSHideki Saito } 881f2ec16ccSHideki Saito 882*f82966d1SSander de Smalen bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) const { 883f2ec16ccSHideki Saito return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 884f2ec16ccSHideki Saito } 885f2ec16ccSHideki Saito 886f2ec16ccSHideki Saito bool LoopVectorizationLegality::blockCanBePredicated( 887bda8fbe2SSjoerd Meijer BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs, 888bda8fbe2SSjoerd Meijer SmallPtrSetImpl<const Instruction *> &MaskedOp, 889bda8fbe2SSjoerd Meijer SmallPtrSetImpl<Instruction *> &ConditionalAssumes, 890bda8fbe2SSjoerd Meijer bool PreserveGuards) const { 891f2ec16ccSHideki Saito const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 892f2ec16ccSHideki Saito 893f2ec16ccSHideki Saito for (Instruction &I : *BB) { 894f2ec16ccSHideki Saito // Check that we don't have a constant expression that can trap as operand. 895f2ec16ccSHideki Saito for (Value *Operand : I.operands()) { 896f2ec16ccSHideki Saito if (auto *C = dyn_cast<Constant>(Operand)) 897f2ec16ccSHideki Saito if (C->canTrap()) 898f2ec16ccSHideki Saito return false; 899f2ec16ccSHideki Saito } 90023c11380SFlorian Hahn 90123c11380SFlorian Hahn // We can predicate blocks with calls to assume, as long as we drop them in 90223c11380SFlorian Hahn // case we flatten the CFG via predication. 90323c11380SFlorian Hahn if (match(&I, m_Intrinsic<Intrinsic::assume>())) { 90423c11380SFlorian Hahn ConditionalAssumes.insert(&I); 90523c11380SFlorian Hahn continue; 90623c11380SFlorian Hahn } 90723c11380SFlorian Hahn 908121cac01SJeroen Dobbelaere // Do not let llvm.experimental.noalias.scope.decl block the vectorization. 909121cac01SJeroen Dobbelaere // TODO: there might be cases that it should block the vectorization. Let's 910121cac01SJeroen Dobbelaere // ignore those for now. 911c83cff45SNikita Popov if (isa<NoAliasScopeDeclInst>(&I)) 912121cac01SJeroen Dobbelaere continue; 913121cac01SJeroen Dobbelaere 914f2ec16ccSHideki Saito // We might be able to hoist the load. 915f2ec16ccSHideki Saito if (I.mayReadFromMemory()) { 916f2ec16ccSHideki Saito auto *LI = dyn_cast<LoadInst>(&I); 917f2ec16ccSHideki Saito if (!LI) 918f2ec16ccSHideki Saito return false; 919f2ec16ccSHideki Saito if (!SafePtrs.count(LI->getPointerOperand())) { 920f2ec16ccSHideki Saito // !llvm.mem.parallel_loop_access implies if-conversion safety. 921f2ec16ccSHideki Saito // Otherwise, record that the load needs (real or emulated) masking 922f2ec16ccSHideki Saito // and let the cost model decide. 923d57d73daSDorit Nuzman if (!IsAnnotatedParallel || PreserveGuards) 924f2ec16ccSHideki Saito MaskedOp.insert(LI); 925f2ec16ccSHideki Saito continue; 926f2ec16ccSHideki Saito } 927f2ec16ccSHideki Saito } 928f2ec16ccSHideki Saito 929f2ec16ccSHideki Saito if (I.mayWriteToMemory()) { 930f2ec16ccSHideki Saito auto *SI = dyn_cast<StoreInst>(&I); 931f2ec16ccSHideki Saito if (!SI) 932f2ec16ccSHideki Saito return false; 933f2ec16ccSHideki Saito // Predicated store requires some form of masking: 934f2ec16ccSHideki Saito // 1) masked store HW instruction, 935f2ec16ccSHideki Saito // 2) emulation via load-blend-store (only if safe and legal to do so, 936f2ec16ccSHideki Saito // be aware on the race conditions), or 937f2ec16ccSHideki Saito // 3) element-by-element predicate check and scalar store. 938f2ec16ccSHideki Saito MaskedOp.insert(SI); 939f2ec16ccSHideki Saito continue; 940f2ec16ccSHideki Saito } 941f2ec16ccSHideki Saito if (I.mayThrow()) 942f2ec16ccSHideki Saito return false; 943f2ec16ccSHideki Saito } 944f2ec16ccSHideki Saito 945f2ec16ccSHideki Saito return true; 946f2ec16ccSHideki Saito } 947f2ec16ccSHideki Saito 948f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 949f2ec16ccSHideki Saito if (!EnableIfConversion) { 9509e97caf5SRenato Golin reportVectorizationFailure("If-conversion is disabled", 9519e97caf5SRenato Golin "if-conversion is disabled", 952ec818d7fSHideki Saito "IfConversionDisabled", 953ec818d7fSHideki Saito ORE, TheLoop); 954f2ec16ccSHideki Saito return false; 955f2ec16ccSHideki Saito } 956f2ec16ccSHideki Saito 957f2ec16ccSHideki Saito assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 958f2ec16ccSHideki Saito 959cf3b5559SPhilip Reames // A list of pointers which are known to be dereferenceable within scope of 960cf3b5559SPhilip Reames // the loop body for each iteration of the loop which executes. That is, 961cf3b5559SPhilip Reames // the memory pointed to can be dereferenced (with the access size implied by 962cf3b5559SPhilip Reames // the value's type) unconditionally within the loop header without 963cf3b5559SPhilip Reames // introducing a new fault. 9643bbc71d6SSjoerd Meijer SmallPtrSet<Value *, 8> SafePointers; 965f2ec16ccSHideki Saito 966f2ec16ccSHideki Saito // Collect safe addresses. 967f2ec16ccSHideki Saito for (BasicBlock *BB : TheLoop->blocks()) { 9687403569bSPhilip Reames if (!blockNeedsPredication(BB)) { 969f2ec16ccSHideki Saito for (Instruction &I : *BB) 970f2ec16ccSHideki Saito if (auto *Ptr = getLoadStorePointerOperand(&I)) 9713bbc71d6SSjoerd Meijer SafePointers.insert(Ptr); 9727403569bSPhilip Reames continue; 9737403569bSPhilip Reames } 9747403569bSPhilip Reames 9757403569bSPhilip Reames // For a block which requires predication, a address may be safe to access 9767403569bSPhilip Reames // in the loop w/o predication if we can prove dereferenceability facts 9777403569bSPhilip Reames // sufficient to ensure it'll never fault within the loop. For the moment, 9787403569bSPhilip Reames // we restrict this to loads; stores are more complicated due to 9797403569bSPhilip Reames // concurrency restrictions. 9807403569bSPhilip Reames ScalarEvolution &SE = *PSE.getSE(); 9817403569bSPhilip Reames for (Instruction &I : *BB) { 9827403569bSPhilip Reames LoadInst *LI = dyn_cast<LoadInst>(&I); 983467e5cf4SJoe Ellis if (LI && !LI->getType()->isVectorTy() && !mustSuppressSpeculation(*LI) && 9847403569bSPhilip Reames isDereferenceableAndAlignedInLoop(LI, TheLoop, SE, *DT)) 9853bbc71d6SSjoerd Meijer SafePointers.insert(LI->getPointerOperand()); 9867403569bSPhilip Reames } 987f2ec16ccSHideki Saito } 988f2ec16ccSHideki Saito 989f2ec16ccSHideki Saito // Collect the blocks that need predication. 990f2ec16ccSHideki Saito BasicBlock *Header = TheLoop->getHeader(); 991f2ec16ccSHideki Saito for (BasicBlock *BB : TheLoop->blocks()) { 992f2ec16ccSHideki Saito // We don't support switch statements inside loops. 993f2ec16ccSHideki Saito if (!isa<BranchInst>(BB->getTerminator())) { 9949e97caf5SRenato Golin reportVectorizationFailure("Loop contains a switch statement", 9959e97caf5SRenato Golin "loop contains a switch statement", 996ec818d7fSHideki Saito "LoopContainsSwitch", ORE, TheLoop, 997ec818d7fSHideki Saito BB->getTerminator()); 998f2ec16ccSHideki Saito return false; 999f2ec16ccSHideki Saito } 1000f2ec16ccSHideki Saito 1001f2ec16ccSHideki Saito // We must be able to predicate all blocks that need to be predicated. 1002f2ec16ccSHideki Saito if (blockNeedsPredication(BB)) { 1003bda8fbe2SSjoerd Meijer if (!blockCanBePredicated(BB, SafePointers, MaskedOp, 1004bda8fbe2SSjoerd Meijer ConditionalAssumes)) { 10059e97caf5SRenato Golin reportVectorizationFailure( 10069e97caf5SRenato Golin "Control flow cannot be substituted for a select", 10079e97caf5SRenato Golin "control flow cannot be substituted for a select", 1008ec818d7fSHideki Saito "NoCFGForSelect", ORE, TheLoop, 1009ec818d7fSHideki Saito BB->getTerminator()); 1010f2ec16ccSHideki Saito return false; 1011f2ec16ccSHideki Saito } 1012f2ec16ccSHideki Saito } else if (BB != Header && !canIfConvertPHINodes(BB)) { 10139e97caf5SRenato Golin reportVectorizationFailure( 10149e97caf5SRenato Golin "Control flow cannot be substituted for a select", 10159e97caf5SRenato Golin "control flow cannot be substituted for a select", 1016ec818d7fSHideki Saito "NoCFGForSelect", ORE, TheLoop, 1017ec818d7fSHideki Saito BB->getTerminator()); 1018f2ec16ccSHideki Saito return false; 1019f2ec16ccSHideki Saito } 1020f2ec16ccSHideki Saito } 1021f2ec16ccSHideki Saito 1022f2ec16ccSHideki Saito // We can if-convert this loop. 1023f2ec16ccSHideki Saito return true; 1024f2ec16ccSHideki Saito } 1025f2ec16ccSHideki Saito 1026f2ec16ccSHideki Saito // Helper function to canVectorizeLoopNestCFG. 1027f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp, 1028f2ec16ccSHideki Saito bool UseVPlanNativePath) { 102989c1e35fSStefanos Baziotis assert((UseVPlanNativePath || Lp->isInnermost()) && 1030f2ec16ccSHideki Saito "VPlan-native path is not enabled."); 1031f2ec16ccSHideki Saito 1032f2ec16ccSHideki Saito // TODO: ORE should be improved to show more accurate information when an 1033f2ec16ccSHideki Saito // outer loop can't be vectorized because a nested loop is not understood or 1034f2ec16ccSHideki Saito // legal. Something like: "outer_loop_location: loop not vectorized: 1035f2ec16ccSHideki Saito // (inner_loop_location) loop control flow is not understood by vectorizer". 1036f2ec16ccSHideki Saito 1037f2ec16ccSHideki Saito // Store the result and return it at the end instead of exiting early, in case 1038f2ec16ccSHideki Saito // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1039f2ec16ccSHideki Saito bool Result = true; 1040f2ec16ccSHideki Saito bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1041f2ec16ccSHideki Saito 1042f2ec16ccSHideki Saito // We must have a loop in canonical form. Loops with indirectbr in them cannot 1043f2ec16ccSHideki Saito // be canonicalized. 1044f2ec16ccSHideki Saito if (!Lp->getLoopPreheader()) { 10459e97caf5SRenato Golin reportVectorizationFailure("Loop doesn't have a legal pre-header", 10469e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 1047ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 1048f2ec16ccSHideki Saito if (DoExtraAnalysis) 1049f2ec16ccSHideki Saito Result = false; 1050f2ec16ccSHideki Saito else 1051f2ec16ccSHideki Saito return false; 1052f2ec16ccSHideki Saito } 1053f2ec16ccSHideki Saito 1054f2ec16ccSHideki Saito // We must have a single backedge. 1055f2ec16ccSHideki Saito if (Lp->getNumBackEdges() != 1) { 10569e97caf5SRenato Golin reportVectorizationFailure("The loop must have a single backedge", 10579e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 1058ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 1059f2ec16ccSHideki Saito if (DoExtraAnalysis) 1060f2ec16ccSHideki Saito Result = false; 1061f2ec16ccSHideki Saito else 1062f2ec16ccSHideki Saito return false; 1063f2ec16ccSHideki Saito } 1064f2ec16ccSHideki Saito 10654b33b238SPhilip Reames // We currently must have a single "exit block" after the loop. Note that 10664b33b238SPhilip Reames // multiple "exiting blocks" inside the loop are allowed, provided they all 10674b33b238SPhilip Reames // reach the single exit block. 10684b33b238SPhilip Reames // TODO: This restriction can be relaxed in the near future, it's here solely 10694b33b238SPhilip Reames // to allow separation of changes for review. We need to generalize the phi 10704b33b238SPhilip Reames // update logic in a number of places. 10719f61fbd7SPhilip Reames if (!Lp->getUniqueExitBlock()) { 10724b33b238SPhilip Reames reportVectorizationFailure("The loop must have a unique exit block", 10739e97caf5SRenato Golin "loop control flow is not understood by vectorizer", 1074ec818d7fSHideki Saito "CFGNotUnderstood", ORE, TheLoop); 1075f2ec16ccSHideki Saito if (DoExtraAnalysis) 1076f2ec16ccSHideki Saito Result = false; 1077f2ec16ccSHideki Saito else 1078f2ec16ccSHideki Saito return false; 1079f2ec16ccSHideki Saito } 1080f2ec16ccSHideki Saito return Result; 1081f2ec16ccSHideki Saito } 1082f2ec16ccSHideki Saito 1083f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorizeLoopNestCFG( 1084f2ec16ccSHideki Saito Loop *Lp, bool UseVPlanNativePath) { 1085f2ec16ccSHideki Saito // Store the result and return it at the end instead of exiting early, in case 1086f2ec16ccSHideki Saito // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1087f2ec16ccSHideki Saito bool Result = true; 1088f2ec16ccSHideki Saito bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1089f2ec16ccSHideki Saito if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) { 1090f2ec16ccSHideki Saito if (DoExtraAnalysis) 1091f2ec16ccSHideki Saito Result = false; 1092f2ec16ccSHideki Saito else 1093f2ec16ccSHideki Saito return false; 1094f2ec16ccSHideki Saito } 1095f2ec16ccSHideki Saito 1096f2ec16ccSHideki Saito // Recursively check whether the loop control flow of nested loops is 1097f2ec16ccSHideki Saito // understood. 1098f2ec16ccSHideki Saito for (Loop *SubLp : *Lp) 1099f2ec16ccSHideki Saito if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) { 1100f2ec16ccSHideki Saito if (DoExtraAnalysis) 1101f2ec16ccSHideki Saito Result = false; 1102f2ec16ccSHideki Saito else 1103f2ec16ccSHideki Saito return false; 1104f2ec16ccSHideki Saito } 1105f2ec16ccSHideki Saito 1106f2ec16ccSHideki Saito return Result; 1107f2ec16ccSHideki Saito } 1108f2ec16ccSHideki Saito 1109f2ec16ccSHideki Saito bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) { 1110f2ec16ccSHideki Saito // Store the result and return it at the end instead of exiting early, in case 1111f2ec16ccSHideki Saito // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1112f2ec16ccSHideki Saito bool Result = true; 1113f2ec16ccSHideki Saito 1114f2ec16ccSHideki Saito bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1115f2ec16ccSHideki Saito // Check whether the loop-related control flow in the loop nest is expected by 1116f2ec16ccSHideki Saito // vectorizer. 1117f2ec16ccSHideki Saito if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) { 1118f2ec16ccSHideki Saito if (DoExtraAnalysis) 1119f2ec16ccSHideki Saito Result = false; 1120f2ec16ccSHideki Saito else 1121f2ec16ccSHideki Saito return false; 1122f2ec16ccSHideki Saito } 1123f2ec16ccSHideki Saito 1124f2ec16ccSHideki Saito // We need to have a loop header. 1125d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName() 1126f2ec16ccSHideki Saito << '\n'); 1127f2ec16ccSHideki Saito 1128f2ec16ccSHideki Saito // Specific checks for outer loops. We skip the remaining legal checks at this 1129f2ec16ccSHideki Saito // point because they don't support outer loops. 113089c1e35fSStefanos Baziotis if (!TheLoop->isInnermost()) { 1131f2ec16ccSHideki Saito assert(UseVPlanNativePath && "VPlan-native path is not enabled."); 1132f2ec16ccSHideki Saito 1133f2ec16ccSHideki Saito if (!canVectorizeOuterLoop()) { 11349e97caf5SRenato Golin reportVectorizationFailure("Unsupported outer loop", 11359e97caf5SRenato Golin "unsupported outer loop", 1136ec818d7fSHideki Saito "UnsupportedOuterLoop", 1137ec818d7fSHideki Saito ORE, TheLoop); 1138f2ec16ccSHideki Saito // TODO: Implement DoExtraAnalysis when subsequent legal checks support 1139f2ec16ccSHideki Saito // outer loops. 1140f2ec16ccSHideki Saito return false; 1141f2ec16ccSHideki Saito } 1142f2ec16ccSHideki Saito 1143d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n"); 1144f2ec16ccSHideki Saito return Result; 1145f2ec16ccSHideki Saito } 1146f2ec16ccSHideki Saito 114789c1e35fSStefanos Baziotis assert(TheLoop->isInnermost() && "Inner loop expected."); 1148f2ec16ccSHideki Saito // Check if we can if-convert non-single-bb loops. 1149f2ec16ccSHideki Saito unsigned NumBlocks = TheLoop->getNumBlocks(); 1150f2ec16ccSHideki Saito if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 1151d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 1152f2ec16ccSHideki Saito if (DoExtraAnalysis) 1153f2ec16ccSHideki Saito Result = false; 1154f2ec16ccSHideki Saito else 1155f2ec16ccSHideki Saito return false; 1156f2ec16ccSHideki Saito } 1157f2ec16ccSHideki Saito 1158f2ec16ccSHideki Saito // Check if we can vectorize the instructions and CFG in this loop. 1159f2ec16ccSHideki Saito if (!canVectorizeInstrs()) { 1160d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 1161f2ec16ccSHideki Saito if (DoExtraAnalysis) 1162f2ec16ccSHideki Saito Result = false; 1163f2ec16ccSHideki Saito else 1164f2ec16ccSHideki Saito return false; 1165f2ec16ccSHideki Saito } 1166f2ec16ccSHideki Saito 1167f2ec16ccSHideki Saito // Go over each instruction and look at memory deps. 1168f2ec16ccSHideki Saito if (!canVectorizeMemory()) { 1169d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 1170f2ec16ccSHideki Saito if (DoExtraAnalysis) 1171f2ec16ccSHideki Saito Result = false; 1172f2ec16ccSHideki Saito else 1173f2ec16ccSHideki Saito return false; 1174f2ec16ccSHideki Saito } 1175f2ec16ccSHideki Saito 1176d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop" 1177f2ec16ccSHideki Saito << (LAI->getRuntimePointerChecking()->Need 1178f2ec16ccSHideki Saito ? " (with a runtime bound check)" 1179f2ec16ccSHideki Saito : "") 1180f2ec16ccSHideki Saito << "!\n"); 1181f2ec16ccSHideki Saito 1182f2ec16ccSHideki Saito unsigned SCEVThreshold = VectorizeSCEVCheckThreshold; 1183f2ec16ccSHideki Saito if (Hints->getForce() == LoopVectorizeHints::FK_Enabled) 1184f2ec16ccSHideki Saito SCEVThreshold = PragmaVectorizeSCEVCheckThreshold; 1185f2ec16ccSHideki Saito 1186f2ec16ccSHideki Saito if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) { 11879e97caf5SRenato Golin reportVectorizationFailure("Too many SCEV checks needed", 11889e97caf5SRenato Golin "Too many SCEV assumptions need to be made and checked at runtime", 1189ec818d7fSHideki Saito "TooManySCEVRunTimeChecks", ORE, TheLoop); 1190f2ec16ccSHideki Saito if (DoExtraAnalysis) 1191f2ec16ccSHideki Saito Result = false; 1192f2ec16ccSHideki Saito else 1193f2ec16ccSHideki Saito return false; 1194f2ec16ccSHideki Saito } 1195f2ec16ccSHideki Saito 1196f2ec16ccSHideki Saito // Okay! We've done all the tests. If any have failed, return false. Otherwise 1197f2ec16ccSHideki Saito // we can vectorize, and at this point we don't have any other mem analysis 1198f2ec16ccSHideki Saito // which may limit our maximum vectorization factor, so just return true with 1199f2ec16ccSHideki Saito // no restrictions. 1200f2ec16ccSHideki Saito return Result; 1201f2ec16ccSHideki Saito } 1202f2ec16ccSHideki Saito 1203d57d73daSDorit Nuzman bool LoopVectorizationLegality::prepareToFoldTailByMasking() { 1204b0b5312eSAyal Zaks 1205b0b5312eSAyal Zaks LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n"); 1206b0b5312eSAyal Zaks 1207d15df0edSAyal Zaks SmallPtrSet<const Value *, 8> ReductionLiveOuts; 1208b0b5312eSAyal Zaks 1209d0d38df0SDavid Green for (auto &Reduction : getReductionVars()) 1210d15df0edSAyal Zaks ReductionLiveOuts.insert(Reduction.second.getLoopExitInstr()); 1211d15df0edSAyal Zaks 1212d15df0edSAyal Zaks // TODO: handle non-reduction outside users when tail is folded by masking. 1213b0b5312eSAyal Zaks for (auto *AE : AllowedExit) { 1214d15df0edSAyal Zaks // Check that all users of allowed exit values are inside the loop or 1215d15df0edSAyal Zaks // are the live-out of a reduction. 1216d15df0edSAyal Zaks if (ReductionLiveOuts.count(AE)) 1217d15df0edSAyal Zaks continue; 1218b0b5312eSAyal Zaks for (User *U : AE->users()) { 1219b0b5312eSAyal Zaks Instruction *UI = cast<Instruction>(U); 1220b0b5312eSAyal Zaks if (TheLoop->contains(UI)) 1221b0b5312eSAyal Zaks continue; 1222bda8fbe2SSjoerd Meijer LLVM_DEBUG( 1223bda8fbe2SSjoerd Meijer dbgs() 1224bda8fbe2SSjoerd Meijer << "LV: Cannot fold tail by masking, loop has an outside user for " 1225bda8fbe2SSjoerd Meijer << *UI << "\n"); 1226b0b5312eSAyal Zaks return false; 1227b0b5312eSAyal Zaks } 1228b0b5312eSAyal Zaks } 1229b0b5312eSAyal Zaks 1230b0b5312eSAyal Zaks // The list of pointers that we can safely read and write to remains empty. 1231b0b5312eSAyal Zaks SmallPtrSet<Value *, 8> SafePointers; 1232b0b5312eSAyal Zaks 1233bda8fbe2SSjoerd Meijer SmallPtrSet<const Instruction *, 8> TmpMaskedOp; 1234bda8fbe2SSjoerd Meijer SmallPtrSet<Instruction *, 8> TmpConditionalAssumes; 1235bda8fbe2SSjoerd Meijer 1236b0b5312eSAyal Zaks // Check and mark all blocks for predication, including those that ordinarily 1237b0b5312eSAyal Zaks // do not need predication such as the header block. 1238b0b5312eSAyal Zaks for (BasicBlock *BB : TheLoop->blocks()) { 1239bda8fbe2SSjoerd Meijer if (!blockCanBePredicated(BB, SafePointers, TmpMaskedOp, 1240bda8fbe2SSjoerd Meijer TmpConditionalAssumes, 1241bda8fbe2SSjoerd Meijer /* MaskAllLoads= */ true)) { 1242bda8fbe2SSjoerd Meijer LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking as requested.\n"); 1243b0b5312eSAyal Zaks return false; 1244b0b5312eSAyal Zaks } 1245b0b5312eSAyal Zaks } 1246b0b5312eSAyal Zaks 1247b0b5312eSAyal Zaks LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n"); 1248bda8fbe2SSjoerd Meijer 1249bda8fbe2SSjoerd Meijer MaskedOp.insert(TmpMaskedOp.begin(), TmpMaskedOp.end()); 1250bda8fbe2SSjoerd Meijer ConditionalAssumes.insert(TmpConditionalAssumes.begin(), 1251bda8fbe2SSjoerd Meijer TmpConditionalAssumes.end()); 1252bda8fbe2SSjoerd Meijer 1253b0b5312eSAyal Zaks return true; 1254b0b5312eSAyal Zaks } 1255b0b5312eSAyal Zaks 1256f2ec16ccSHideki Saito } // namespace llvm 1257