1 //===- LoopVectorizationLegality.cpp --------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides loop vectorization legality analysis. Original code 10 // resided in LoopVectorize.cpp for a long time. 11 // 12 // At this point, it is implemented as a utility class, not as an analysis 13 // pass. It should be easy to create an analysis pass around it if there 14 // is a need (but D45420 needs to happen first). 15 // 16 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h" 17 #include "llvm/Analysis/VectorUtils.h" 18 #include "llvm/IR/IntrinsicInst.h" 19 20 using namespace llvm; 21 22 #define LV_NAME "loop-vectorize" 23 #define DEBUG_TYPE LV_NAME 24 25 extern cl::opt<bool> EnableVPlanPredication; 26 27 static cl::opt<bool> 28 EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden, 29 cl::desc("Enable if-conversion during vectorization.")); 30 31 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold( 32 "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden, 33 cl::desc("The maximum allowed number of runtime memory checks with a " 34 "vectorize(enable) pragma.")); 35 36 static cl::opt<unsigned> VectorizeSCEVCheckThreshold( 37 "vectorize-scev-check-threshold", cl::init(16), cl::Hidden, 38 cl::desc("The maximum number of SCEV checks allowed.")); 39 40 static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold( 41 "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden, 42 cl::desc("The maximum number of SCEV checks allowed with a " 43 "vectorize(enable) pragma")); 44 45 /// Maximum vectorization interleave count. 46 static const unsigned MaxInterleaveFactor = 16; 47 48 namespace llvm { 49 50 #ifndef NDEBUG 51 static void debugVectorizationFailure(const StringRef DebugMsg, 52 Instruction *I) { 53 dbgs() << "LV: Not vectorizing: " << DebugMsg; 54 if (I != nullptr) 55 dbgs() << " " << *I; 56 else 57 dbgs() << '.'; 58 dbgs() << '\n'; 59 } 60 #endif 61 62 OptimizationRemarkAnalysis createLVMissedAnalysis(const char *PassName, 63 StringRef RemarkName, 64 Loop *TheLoop, 65 Instruction *I) { 66 Value *CodeRegion = TheLoop->getHeader(); 67 DebugLoc DL = TheLoop->getStartLoc(); 68 69 if (I) { 70 CodeRegion = I->getParent(); 71 // If there is no debug location attached to the instruction, revert back to 72 // using the loop's. 73 if (I->getDebugLoc()) 74 DL = I->getDebugLoc(); 75 } 76 77 OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion); 78 R << "loop not vectorized: "; 79 return R; 80 } 81 82 bool LoopVectorizeHints::Hint::validate(unsigned Val) { 83 switch (Kind) { 84 case HK_WIDTH: 85 return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth; 86 case HK_UNROLL: 87 return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor; 88 case HK_FORCE: 89 return (Val <= 1); 90 case HK_ISVECTORIZED: 91 return (Val == 0 || Val == 1); 92 } 93 return false; 94 } 95 96 LoopVectorizeHints::LoopVectorizeHints(const Loop *L, 97 bool InterleaveOnlyWhenForced, 98 OptimizationRemarkEmitter &ORE) 99 : Width("vectorize.width", VectorizerParams::VectorizationFactor, HK_WIDTH), 100 Interleave("interleave.count", InterleaveOnlyWhenForced, HK_UNROLL), 101 Force("vectorize.enable", FK_Undefined, HK_FORCE), 102 IsVectorized("isvectorized", 0, HK_ISVECTORIZED), TheLoop(L), ORE(ORE) { 103 // Populate values with existing loop metadata. 104 getHintsFromMetadata(); 105 106 // force-vector-interleave overrides DisableInterleaving. 107 if (VectorizerParams::isInterleaveForced()) 108 Interleave.Value = VectorizerParams::VectorizationInterleave; 109 110 if (IsVectorized.Value != 1) 111 // If the vectorization width and interleaving count are both 1 then 112 // consider the loop to have been already vectorized because there's 113 // nothing more that we can do. 114 IsVectorized.Value = Width.Value == 1 && Interleave.Value == 1; 115 LLVM_DEBUG(if (InterleaveOnlyWhenForced && Interleave.Value == 1) dbgs() 116 << "LV: Interleaving disabled by the pass manager\n"); 117 } 118 119 void LoopVectorizeHints::setAlreadyVectorized() { 120 LLVMContext &Context = TheLoop->getHeader()->getContext(); 121 122 MDNode *IsVectorizedMD = MDNode::get( 123 Context, 124 {MDString::get(Context, "llvm.loop.isvectorized"), 125 ConstantAsMetadata::get(ConstantInt::get(Context, APInt(32, 1)))}); 126 MDNode *LoopID = TheLoop->getLoopID(); 127 MDNode *NewLoopID = 128 makePostTransformationMetadata(Context, LoopID, 129 {Twine(Prefix(), "vectorize.").str(), 130 Twine(Prefix(), "interleave.").str()}, 131 {IsVectorizedMD}); 132 TheLoop->setLoopID(NewLoopID); 133 134 // Update internal cache. 135 IsVectorized.Value = 1; 136 } 137 138 bool LoopVectorizeHints::allowVectorization( 139 Function *F, Loop *L, bool VectorizeOnlyWhenForced) const { 140 if (getForce() == LoopVectorizeHints::FK_Disabled) { 141 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n"); 142 emitRemarkWithHints(); 143 return false; 144 } 145 146 if (VectorizeOnlyWhenForced && getForce() != LoopVectorizeHints::FK_Enabled) { 147 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n"); 148 emitRemarkWithHints(); 149 return false; 150 } 151 152 if (getIsVectorized() == 1) { 153 LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n"); 154 // FIXME: Add interleave.disable metadata. This will allow 155 // vectorize.disable to be used without disabling the pass and errors 156 // to differentiate between disabled vectorization and a width of 1. 157 ORE.emit([&]() { 158 return OptimizationRemarkAnalysis(vectorizeAnalysisPassName(), 159 "AllDisabled", L->getStartLoc(), 160 L->getHeader()) 161 << "loop not vectorized: vectorization and interleaving are " 162 "explicitly disabled, or the loop has already been " 163 "vectorized"; 164 }); 165 return false; 166 } 167 168 return true; 169 } 170 171 void LoopVectorizeHints::emitRemarkWithHints() const { 172 using namespace ore; 173 174 ORE.emit([&]() { 175 if (Force.Value == LoopVectorizeHints::FK_Disabled) 176 return OptimizationRemarkMissed(LV_NAME, "MissedExplicitlyDisabled", 177 TheLoop->getStartLoc(), 178 TheLoop->getHeader()) 179 << "loop not vectorized: vectorization is explicitly disabled"; 180 else { 181 OptimizationRemarkMissed R(LV_NAME, "MissedDetails", 182 TheLoop->getStartLoc(), TheLoop->getHeader()); 183 R << "loop not vectorized"; 184 if (Force.Value == LoopVectorizeHints::FK_Enabled) { 185 R << " (Force=" << NV("Force", true); 186 if (Width.Value != 0) 187 R << ", Vector Width=" << NV("VectorWidth", Width.Value); 188 if (Interleave.Value != 0) 189 R << ", Interleave Count=" << NV("InterleaveCount", Interleave.Value); 190 R << ")"; 191 } 192 return R; 193 } 194 }); 195 } 196 197 const char *LoopVectorizeHints::vectorizeAnalysisPassName() const { 198 if (getWidth() == 1) 199 return LV_NAME; 200 if (getForce() == LoopVectorizeHints::FK_Disabled) 201 return LV_NAME; 202 if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0) 203 return LV_NAME; 204 return OptimizationRemarkAnalysis::AlwaysPrint; 205 } 206 207 void LoopVectorizeHints::getHintsFromMetadata() { 208 MDNode *LoopID = TheLoop->getLoopID(); 209 if (!LoopID) 210 return; 211 212 // First operand should refer to the loop id itself. 213 assert(LoopID->getNumOperands() > 0 && "requires at least one operand"); 214 assert(LoopID->getOperand(0) == LoopID && "invalid loop id"); 215 216 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) { 217 const MDString *S = nullptr; 218 SmallVector<Metadata *, 4> Args; 219 220 // The expected hint is either a MDString or a MDNode with the first 221 // operand a MDString. 222 if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) { 223 if (!MD || MD->getNumOperands() == 0) 224 continue; 225 S = dyn_cast<MDString>(MD->getOperand(0)); 226 for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i) 227 Args.push_back(MD->getOperand(i)); 228 } else { 229 S = dyn_cast<MDString>(LoopID->getOperand(i)); 230 assert(Args.size() == 0 && "too many arguments for MDString"); 231 } 232 233 if (!S) 234 continue; 235 236 // Check if the hint starts with the loop metadata prefix. 237 StringRef Name = S->getString(); 238 if (Args.size() == 1) 239 setHint(Name, Args[0]); 240 } 241 } 242 243 void LoopVectorizeHints::setHint(StringRef Name, Metadata *Arg) { 244 if (!Name.startswith(Prefix())) 245 return; 246 Name = Name.substr(Prefix().size(), StringRef::npos); 247 248 const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg); 249 if (!C) 250 return; 251 unsigned Val = C->getZExtValue(); 252 253 Hint *Hints[] = {&Width, &Interleave, &Force, &IsVectorized}; 254 for (auto H : Hints) { 255 if (Name == H->Name) { 256 if (H->validate(Val)) 257 H->Value = Val; 258 else 259 LLVM_DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n"); 260 break; 261 } 262 } 263 } 264 265 bool LoopVectorizationRequirements::doesNotMeet( 266 Function *F, Loop *L, const LoopVectorizeHints &Hints) { 267 const char *PassName = Hints.vectorizeAnalysisPassName(); 268 bool Failed = false; 269 if (UnsafeAlgebraInst && !Hints.allowReordering()) { 270 ORE.emit([&]() { 271 return OptimizationRemarkAnalysisFPCommute( 272 PassName, "CantReorderFPOps", UnsafeAlgebraInst->getDebugLoc(), 273 UnsafeAlgebraInst->getParent()) 274 << "loop not vectorized: cannot prove it is safe to reorder " 275 "floating-point operations"; 276 }); 277 Failed = true; 278 } 279 280 // Test if runtime memcheck thresholds are exceeded. 281 bool PragmaThresholdReached = 282 NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold; 283 bool ThresholdReached = 284 NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold; 285 if ((ThresholdReached && !Hints.allowReordering()) || 286 PragmaThresholdReached) { 287 ORE.emit([&]() { 288 return OptimizationRemarkAnalysisAliasing(PassName, "CantReorderMemOps", 289 L->getStartLoc(), 290 L->getHeader()) 291 << "loop not vectorized: cannot prove it is safe to reorder " 292 "memory operations"; 293 }); 294 LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n"); 295 Failed = true; 296 } 297 298 return Failed; 299 } 300 301 // Return true if the inner loop \p Lp is uniform with regard to the outer loop 302 // \p OuterLp (i.e., if the outer loop is vectorized, all the vector lanes 303 // executing the inner loop will execute the same iterations). This check is 304 // very constrained for now but it will be relaxed in the future. \p Lp is 305 // considered uniform if it meets all the following conditions: 306 // 1) it has a canonical IV (starting from 0 and with stride 1), 307 // 2) its latch terminator is a conditional branch and, 308 // 3) its latch condition is a compare instruction whose operands are the 309 // canonical IV and an OuterLp invariant. 310 // This check doesn't take into account the uniformity of other conditions not 311 // related to the loop latch because they don't affect the loop uniformity. 312 // 313 // NOTE: We decided to keep all these checks and its associated documentation 314 // together so that we can easily have a picture of the current supported loop 315 // nests. However, some of the current checks don't depend on \p OuterLp and 316 // would be redundantly executed for each \p Lp if we invoked this function for 317 // different candidate outer loops. This is not the case for now because we 318 // don't currently have the infrastructure to evaluate multiple candidate outer 319 // loops and \p OuterLp will be a fixed parameter while we only support explicit 320 // outer loop vectorization. It's also very likely that these checks go away 321 // before introducing the aforementioned infrastructure. However, if this is not 322 // the case, we should move the \p OuterLp independent checks to a separate 323 // function that is only executed once for each \p Lp. 324 static bool isUniformLoop(Loop *Lp, Loop *OuterLp) { 325 assert(Lp->getLoopLatch() && "Expected loop with a single latch."); 326 327 // If Lp is the outer loop, it's uniform by definition. 328 if (Lp == OuterLp) 329 return true; 330 assert(OuterLp->contains(Lp) && "OuterLp must contain Lp."); 331 332 // 1. 333 PHINode *IV = Lp->getCanonicalInductionVariable(); 334 if (!IV) { 335 LLVM_DEBUG(dbgs() << "LV: Canonical IV not found.\n"); 336 return false; 337 } 338 339 // 2. 340 BasicBlock *Latch = Lp->getLoopLatch(); 341 auto *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator()); 342 if (!LatchBr || LatchBr->isUnconditional()) { 343 LLVM_DEBUG(dbgs() << "LV: Unsupported loop latch branch.\n"); 344 return false; 345 } 346 347 // 3. 348 auto *LatchCmp = dyn_cast<CmpInst>(LatchBr->getCondition()); 349 if (!LatchCmp) { 350 LLVM_DEBUG( 351 dbgs() << "LV: Loop latch condition is not a compare instruction.\n"); 352 return false; 353 } 354 355 Value *CondOp0 = LatchCmp->getOperand(0); 356 Value *CondOp1 = LatchCmp->getOperand(1); 357 Value *IVUpdate = IV->getIncomingValueForBlock(Latch); 358 if (!(CondOp0 == IVUpdate && OuterLp->isLoopInvariant(CondOp1)) && 359 !(CondOp1 == IVUpdate && OuterLp->isLoopInvariant(CondOp0))) { 360 LLVM_DEBUG(dbgs() << "LV: Loop latch condition is not uniform.\n"); 361 return false; 362 } 363 364 return true; 365 } 366 367 // Return true if \p Lp and all its nested loops are uniform with regard to \p 368 // OuterLp. 369 static bool isUniformLoopNest(Loop *Lp, Loop *OuterLp) { 370 if (!isUniformLoop(Lp, OuterLp)) 371 return false; 372 373 // Check if nested loops are uniform. 374 for (Loop *SubLp : *Lp) 375 if (!isUniformLoopNest(SubLp, OuterLp)) 376 return false; 377 378 return true; 379 } 380 381 /// Check whether it is safe to if-convert this phi node. 382 /// 383 /// Phi nodes with constant expressions that can trap are not safe to if 384 /// convert. 385 static bool canIfConvertPHINodes(BasicBlock *BB) { 386 for (PHINode &Phi : BB->phis()) { 387 for (Value *V : Phi.incoming_values()) 388 if (auto *C = dyn_cast<Constant>(V)) 389 if (C->canTrap()) 390 return false; 391 } 392 return true; 393 } 394 395 static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) { 396 if (Ty->isPointerTy()) 397 return DL.getIntPtrType(Ty); 398 399 // It is possible that char's or short's overflow when we ask for the loop's 400 // trip count, work around this by changing the type size. 401 if (Ty->getScalarSizeInBits() < 32) 402 return Type::getInt32Ty(Ty->getContext()); 403 404 return Ty; 405 } 406 407 static Type *getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) { 408 Ty0 = convertPointerToIntegerType(DL, Ty0); 409 Ty1 = convertPointerToIntegerType(DL, Ty1); 410 if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits()) 411 return Ty0; 412 return Ty1; 413 } 414 415 /// Check that the instruction has outside loop users and is not an 416 /// identified reduction variable. 417 static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst, 418 SmallPtrSetImpl<Value *> &AllowedExit) { 419 // Reductions, Inductions and non-header phis are allowed to have exit users. All 420 // other instructions must not have external users. 421 if (!AllowedExit.count(Inst)) 422 // Check that all of the users of the loop are inside the BB. 423 for (User *U : Inst->users()) { 424 Instruction *UI = cast<Instruction>(U); 425 // This user may be a reduction exit value. 426 if (!TheLoop->contains(UI)) { 427 LLVM_DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n'); 428 return true; 429 } 430 } 431 return false; 432 } 433 434 int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) { 435 const ValueToValueMap &Strides = 436 getSymbolicStrides() ? *getSymbolicStrides() : ValueToValueMap(); 437 438 int Stride = getPtrStride(PSE, Ptr, TheLoop, Strides, true, false); 439 if (Stride == 1 || Stride == -1) 440 return Stride; 441 return 0; 442 } 443 444 bool LoopVectorizationLegality::isUniform(Value *V) { 445 return LAI->isUniform(V); 446 } 447 448 void LoopVectorizationLegality::reportVectorizationFailure( 449 const StringRef DebugMsg, const StringRef OREMsg, 450 const StringRef ORETag, Instruction *I) const { 451 LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I)); 452 ORE->emit(createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(), 453 ORETag, TheLoop, I) << OREMsg); 454 } 455 456 bool LoopVectorizationLegality::canVectorizeOuterLoop() { 457 assert(!TheLoop->empty() && "We are not vectorizing an outer loop."); 458 // Store the result and return it at the end instead of exiting early, in case 459 // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 460 bool Result = true; 461 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 462 463 for (BasicBlock *BB : TheLoop->blocks()) { 464 // Check whether the BB terminator is a BranchInst. Any other terminator is 465 // not supported yet. 466 auto *Br = dyn_cast<BranchInst>(BB->getTerminator()); 467 if (!Br) { 468 reportVectorizationFailure("Unsupported basic block terminator", 469 "loop control flow is not understood by vectorizer", 470 "CFGNotUnderstood"); 471 if (DoExtraAnalysis) 472 Result = false; 473 else 474 return false; 475 } 476 477 // Check whether the BranchInst is a supported one. Only unconditional 478 // branches, conditional branches with an outer loop invariant condition or 479 // backedges are supported. 480 // FIXME: We skip these checks when VPlan predication is enabled as we 481 // want to allow divergent branches. This whole check will be removed 482 // once VPlan predication is on by default. 483 if (!EnableVPlanPredication && Br && Br->isConditional() && 484 !TheLoop->isLoopInvariant(Br->getCondition()) && 485 !LI->isLoopHeader(Br->getSuccessor(0)) && 486 !LI->isLoopHeader(Br->getSuccessor(1))) { 487 reportVectorizationFailure("Unsupported conditional branch", 488 "loop control flow is not understood by vectorizer", 489 "CFGNotUnderstood"); 490 if (DoExtraAnalysis) 491 Result = false; 492 else 493 return false; 494 } 495 } 496 497 // Check whether inner loops are uniform. At this point, we only support 498 // simple outer loops scenarios with uniform nested loops. 499 if (!isUniformLoopNest(TheLoop /*loop nest*/, 500 TheLoop /*context outer loop*/)) { 501 reportVectorizationFailure("Outer loop contains divergent loops", 502 "loop control flow is not understood by vectorizer", 503 "CFGNotUnderstood"); 504 if (DoExtraAnalysis) 505 Result = false; 506 else 507 return false; 508 } 509 510 // Check whether we are able to set up outer loop induction. 511 if (!setupOuterLoopInductions()) { 512 reportVectorizationFailure("Unsupported outer loop Phi(s)", 513 "Unsupported outer loop Phi(s)", 514 "UnsupportedPhi"); 515 if (DoExtraAnalysis) 516 Result = false; 517 else 518 return false; 519 } 520 521 return Result; 522 } 523 524 void LoopVectorizationLegality::addInductionPhi( 525 PHINode *Phi, const InductionDescriptor &ID, 526 SmallPtrSetImpl<Value *> &AllowedExit) { 527 Inductions[Phi] = ID; 528 529 // In case this induction also comes with casts that we know we can ignore 530 // in the vectorized loop body, record them here. All casts could be recorded 531 // here for ignoring, but suffices to record only the first (as it is the 532 // only one that may bw used outside the cast sequence). 533 const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts(); 534 if (!Casts.empty()) 535 InductionCastsToIgnore.insert(*Casts.begin()); 536 537 Type *PhiTy = Phi->getType(); 538 const DataLayout &DL = Phi->getModule()->getDataLayout(); 539 540 // Get the widest type. 541 if (!PhiTy->isFloatingPointTy()) { 542 if (!WidestIndTy) 543 WidestIndTy = convertPointerToIntegerType(DL, PhiTy); 544 else 545 WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy); 546 } 547 548 // Int inductions are special because we only allow one IV. 549 if (ID.getKind() == InductionDescriptor::IK_IntInduction && 550 ID.getConstIntStepValue() && ID.getConstIntStepValue()->isOne() && 551 isa<Constant>(ID.getStartValue()) && 552 cast<Constant>(ID.getStartValue())->isNullValue()) { 553 554 // Use the phi node with the widest type as induction. Use the last 555 // one if there are multiple (no good reason for doing this other 556 // than it is expedient). We've checked that it begins at zero and 557 // steps by one, so this is a canonical induction variable. 558 if (!PrimaryInduction || PhiTy == WidestIndTy) 559 PrimaryInduction = Phi; 560 } 561 562 // Both the PHI node itself, and the "post-increment" value feeding 563 // back into the PHI node may have external users. 564 // We can allow those uses, except if the SCEVs we have for them rely 565 // on predicates that only hold within the loop, since allowing the exit 566 // currently means re-using this SCEV outside the loop (see PR33706 for more 567 // details). 568 if (PSE.getUnionPredicate().isAlwaysTrue()) { 569 AllowedExit.insert(Phi); 570 AllowedExit.insert(Phi->getIncomingValueForBlock(TheLoop->getLoopLatch())); 571 } 572 573 LLVM_DEBUG(dbgs() << "LV: Found an induction variable.\n"); 574 } 575 576 bool LoopVectorizationLegality::setupOuterLoopInductions() { 577 BasicBlock *Header = TheLoop->getHeader(); 578 579 // Returns true if a given Phi is a supported induction. 580 auto isSupportedPhi = [&](PHINode &Phi) -> bool { 581 InductionDescriptor ID; 582 if (InductionDescriptor::isInductionPHI(&Phi, TheLoop, PSE, ID) && 583 ID.getKind() == InductionDescriptor::IK_IntInduction) { 584 addInductionPhi(&Phi, ID, AllowedExit); 585 return true; 586 } else { 587 // Bail out for any Phi in the outer loop header that is not a supported 588 // induction. 589 LLVM_DEBUG( 590 dbgs() 591 << "LV: Found unsupported PHI for outer loop vectorization.\n"); 592 return false; 593 } 594 }; 595 596 if (llvm::all_of(Header->phis(), isSupportedPhi)) 597 return true; 598 else 599 return false; 600 } 601 602 bool LoopVectorizationLegality::canVectorizeInstrs() { 603 BasicBlock *Header = TheLoop->getHeader(); 604 605 // Look for the attribute signaling the absence of NaNs. 606 Function &F = *Header->getParent(); 607 HasFunNoNaNAttr = 608 F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true"; 609 610 // For each block in the loop. 611 for (BasicBlock *BB : TheLoop->blocks()) { 612 // Scan the instructions in the block and look for hazards. 613 for (Instruction &I : *BB) { 614 if (auto *Phi = dyn_cast<PHINode>(&I)) { 615 Type *PhiTy = Phi->getType(); 616 // Check that this PHI type is allowed. 617 if (!PhiTy->isIntegerTy() && !PhiTy->isFloatingPointTy() && 618 !PhiTy->isPointerTy()) { 619 reportVectorizationFailure("Found a non-int non-pointer PHI", 620 "loop control flow is not understood by vectorizer", 621 "CFGNotUnderstood"); 622 return false; 623 } 624 625 // If this PHINode is not in the header block, then we know that we 626 // can convert it to select during if-conversion. No need to check if 627 // the PHIs in this block are induction or reduction variables. 628 if (BB != Header) { 629 // Non-header phi nodes that have outside uses can be vectorized. Add 630 // them to the list of allowed exits. 631 // Unsafe cyclic dependencies with header phis are identified during 632 // legalization for reduction, induction and first order 633 // recurrences. 634 continue; 635 } 636 637 // We only allow if-converted PHIs with exactly two incoming values. 638 if (Phi->getNumIncomingValues() != 2) { 639 reportVectorizationFailure("Found an invalid PHI", 640 "loop control flow is not understood by vectorizer", 641 "CFGNotUnderstood", Phi); 642 return false; 643 } 644 645 RecurrenceDescriptor RedDes; 646 if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes, DB, AC, 647 DT)) { 648 if (RedDes.hasUnsafeAlgebra()) 649 Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst()); 650 AllowedExit.insert(RedDes.getLoopExitInstr()); 651 Reductions[Phi] = RedDes; 652 continue; 653 } 654 655 // TODO: Instead of recording the AllowedExit, it would be good to record the 656 // complementary set: NotAllowedExit. These include (but may not be 657 // limited to): 658 // 1. Reduction phis as they represent the one-before-last value, which 659 // is not available when vectorized 660 // 2. Induction phis and increment when SCEV predicates cannot be used 661 // outside the loop - see addInductionPhi 662 // 3. Non-Phis with outside uses when SCEV predicates cannot be used 663 // outside the loop - see call to hasOutsideLoopUser in the non-phi 664 // handling below 665 // 4. FirstOrderRecurrence phis that can possibly be handled by 666 // extraction. 667 // By recording these, we can then reason about ways to vectorize each 668 // of these NotAllowedExit. 669 InductionDescriptor ID; 670 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID)) { 671 addInductionPhi(Phi, ID, AllowedExit); 672 if (ID.hasUnsafeAlgebra() && !HasFunNoNaNAttr) 673 Requirements->addUnsafeAlgebraInst(ID.getUnsafeAlgebraInst()); 674 continue; 675 } 676 677 if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, 678 SinkAfter, DT)) { 679 FirstOrderRecurrences.insert(Phi); 680 continue; 681 } 682 683 // As a last resort, coerce the PHI to a AddRec expression 684 // and re-try classifying it a an induction PHI. 685 if (InductionDescriptor::isInductionPHI(Phi, TheLoop, PSE, ID, true)) { 686 addInductionPhi(Phi, ID, AllowedExit); 687 continue; 688 } 689 690 reportVectorizationFailure("Found an unidentified PHI", 691 "value that could not be identified as " 692 "reduction is used outside the loop", 693 "NonReductionValueUsedOutsideLoop", Phi); 694 return false; 695 } // end of PHI handling 696 697 // We handle calls that: 698 // * Are debug info intrinsics. 699 // * Have a mapping to an IR intrinsic. 700 // * Have a vector version available. 701 auto *CI = dyn_cast<CallInst>(&I); 702 if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && 703 !isa<DbgInfoIntrinsic>(CI) && 704 !(CI->getCalledFunction() && TLI && 705 TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) { 706 // If the call is a recognized math libary call, it is likely that 707 // we can vectorize it given loosened floating-point constraints. 708 LibFunc Func; 709 bool IsMathLibCall = 710 TLI && CI->getCalledFunction() && 711 CI->getType()->isFloatingPointTy() && 712 TLI->getLibFunc(CI->getCalledFunction()->getName(), Func) && 713 TLI->hasOptimizedCodeGen(Func); 714 715 if (IsMathLibCall) { 716 // TODO: Ideally, we should not use clang-specific language here, 717 // but it's hard to provide meaningful yet generic advice. 718 // Also, should this be guarded by allowExtraAnalysis() and/or be part 719 // of the returned info from isFunctionVectorizable()? 720 reportVectorizationFailure("Found a non-intrinsic callsite", 721 "library call cannot be vectorized. " 722 "Try compiling with -fno-math-errno, -ffast-math, " 723 "or similar flags", 724 "CantVectorizeLibcall", CI); 725 } else { 726 reportVectorizationFailure("Found a non-intrinsic callsite", 727 "call instruction cannot be vectorized", 728 "CantVectorizeLibcall", CI); 729 } 730 return false; 731 } 732 733 // Some intrinsics have scalar arguments and should be same in order for 734 // them to be vectorized (i.e. loop invariant). 735 if (CI) { 736 auto *SE = PSE.getSE(); 737 Intrinsic::ID IntrinID = getVectorIntrinsicIDForCall(CI, TLI); 738 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) 739 if (hasVectorInstrinsicScalarOpd(IntrinID, i)) { 740 if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(i)), TheLoop)) { 741 reportVectorizationFailure("Found unvectorizable intrinsic", 742 "intrinsic instruction cannot be vectorized", 743 "CantVectorizeIntrinsic", CI); 744 return false; 745 } 746 } 747 } 748 749 // Check that the instruction return type is vectorizable. 750 // Also, we can't vectorize extractelement instructions. 751 if ((!VectorType::isValidElementType(I.getType()) && 752 !I.getType()->isVoidTy()) || 753 isa<ExtractElementInst>(I)) { 754 reportVectorizationFailure("Found unvectorizable type", 755 "instruction return type cannot be vectorized", 756 "CantVectorizeInstructionReturnType", &I); 757 return false; 758 } 759 760 // Check that the stored type is vectorizable. 761 if (auto *ST = dyn_cast<StoreInst>(&I)) { 762 Type *T = ST->getValueOperand()->getType(); 763 if (!VectorType::isValidElementType(T)) { 764 reportVectorizationFailure("Store instruction cannot be vectorized", 765 "store instruction cannot be vectorized", 766 "CantVectorizeStore", ST); 767 return false; 768 } 769 770 // For nontemporal stores, check that a nontemporal vector version is 771 // supported on the target. 772 if (ST->getMetadata(LLVMContext::MD_nontemporal)) { 773 // Arbitrarily try a vector of 2 elements. 774 Type *VecTy = VectorType::get(T, /*NumElements=*/2); 775 assert(VecTy && "did not find vectorized version of stored type"); 776 unsigned Alignment = getLoadStoreAlignment(ST); 777 if (!TTI->isLegalNTStore(VecTy, Alignment)) { 778 reportVectorizationFailure( 779 "nontemporal store instruction cannot be vectorized", 780 "nontemporal store instruction cannot be vectorized", 781 "CantVectorizeNontemporalStore", ST); 782 return false; 783 } 784 } 785 786 } else if (auto *LD = dyn_cast<LoadInst>(&I)) { 787 if (LD->getMetadata(LLVMContext::MD_nontemporal)) { 788 // For nontemporal loads, check that a nontemporal vector version is 789 // supported on the target (arbitrarily try a vector of 2 elements). 790 Type *VecTy = VectorType::get(I.getType(), /*NumElements=*/2); 791 assert(VecTy && "did not find vectorized version of load type"); 792 unsigned Alignment = getLoadStoreAlignment(LD); 793 if (!TTI->isLegalNTLoad(VecTy, Alignment)) { 794 reportVectorizationFailure( 795 "nontemporal load instruction cannot be vectorized", 796 "nontemporal load instruction cannot be vectorized", 797 "CantVectorizeNontemporalLoad", LD); 798 return false; 799 } 800 } 801 802 // FP instructions can allow unsafe algebra, thus vectorizable by 803 // non-IEEE-754 compliant SIMD units. 804 // This applies to floating-point math operations and calls, not memory 805 // operations, shuffles, or casts, as they don't change precision or 806 // semantics. 807 } else if (I.getType()->isFloatingPointTy() && (CI || I.isBinaryOp()) && 808 !I.isFast()) { 809 LLVM_DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n"); 810 Hints->setPotentiallyUnsafe(); 811 } 812 813 // Reduction instructions are allowed to have exit users. 814 // All other instructions must not have external users. 815 if (hasOutsideLoopUser(TheLoop, &I, AllowedExit)) { 816 // We can safely vectorize loops where instructions within the loop are 817 // used outside the loop only if the SCEV predicates within the loop is 818 // same as outside the loop. Allowing the exit means reusing the SCEV 819 // outside the loop. 820 if (PSE.getUnionPredicate().isAlwaysTrue()) { 821 AllowedExit.insert(&I); 822 continue; 823 } 824 reportVectorizationFailure("Value cannot be used outside the loop", 825 "value cannot be used outside the loop", 826 "ValueUsedOutsideLoop", &I); 827 return false; 828 } 829 } // next instr. 830 } 831 832 if (!PrimaryInduction) { 833 if (Inductions.empty()) { 834 reportVectorizationFailure("Did not find one integer induction var", 835 "loop induction variable could not be identified", 836 "NoInductionVariable"); 837 return false; 838 } else if (!WidestIndTy) { 839 reportVectorizationFailure("Did not find one integer induction var", 840 "integer loop induction variable could not be identified", 841 "NoIntegerInductionVariable"); 842 return false; 843 } else { 844 LLVM_DEBUG(dbgs() << "LV: Did not find one integer induction var.\n"); 845 } 846 } 847 848 // Now we know the widest induction type, check if our found induction 849 // is the same size. If it's not, unset it here and InnerLoopVectorizer 850 // will create another. 851 if (PrimaryInduction && WidestIndTy != PrimaryInduction->getType()) 852 PrimaryInduction = nullptr; 853 854 return true; 855 } 856 857 bool LoopVectorizationLegality::canVectorizeMemory() { 858 LAI = &(*GetLAA)(*TheLoop); 859 const OptimizationRemarkAnalysis *LAR = LAI->getReport(); 860 if (LAR) { 861 ORE->emit([&]() { 862 return OptimizationRemarkAnalysis(Hints->vectorizeAnalysisPassName(), 863 "loop not vectorized: ", *LAR); 864 }); 865 } 866 if (!LAI->canVectorizeMemory()) 867 return false; 868 869 if (LAI->hasDependenceInvolvingLoopInvariantAddress()) { 870 reportVectorizationFailure("Stores to a uniform address", 871 "write to a loop invariant address could not be vectorized", 872 "CantVectorizeStoreToLoopInvariantAddress"); 873 return false; 874 } 875 Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks()); 876 PSE.addPredicate(LAI->getPSE().getUnionPredicate()); 877 878 return true; 879 } 880 881 bool LoopVectorizationLegality::isInductionPhi(const Value *V) { 882 Value *In0 = const_cast<Value *>(V); 883 PHINode *PN = dyn_cast_or_null<PHINode>(In0); 884 if (!PN) 885 return false; 886 887 return Inductions.count(PN); 888 } 889 890 bool LoopVectorizationLegality::isCastedInductionVariable(const Value *V) { 891 auto *Inst = dyn_cast<Instruction>(V); 892 return (Inst && InductionCastsToIgnore.count(Inst)); 893 } 894 895 bool LoopVectorizationLegality::isInductionVariable(const Value *V) { 896 return isInductionPhi(V) || isCastedInductionVariable(V); 897 } 898 899 bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) { 900 return FirstOrderRecurrences.count(Phi); 901 } 902 903 bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) { 904 return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT); 905 } 906 907 bool LoopVectorizationLegality::blockCanBePredicated( 908 BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs) { 909 const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel(); 910 911 for (Instruction &I : *BB) { 912 // Check that we don't have a constant expression that can trap as operand. 913 for (Value *Operand : I.operands()) { 914 if (auto *C = dyn_cast<Constant>(Operand)) 915 if (C->canTrap()) 916 return false; 917 } 918 // We might be able to hoist the load. 919 if (I.mayReadFromMemory()) { 920 auto *LI = dyn_cast<LoadInst>(&I); 921 if (!LI) 922 return false; 923 if (!SafePtrs.count(LI->getPointerOperand())) { 924 // !llvm.mem.parallel_loop_access implies if-conversion safety. 925 // Otherwise, record that the load needs (real or emulated) masking 926 // and let the cost model decide. 927 if (!IsAnnotatedParallel) 928 MaskedOp.insert(LI); 929 continue; 930 } 931 } 932 933 if (I.mayWriteToMemory()) { 934 auto *SI = dyn_cast<StoreInst>(&I); 935 if (!SI) 936 return false; 937 // Predicated store requires some form of masking: 938 // 1) masked store HW instruction, 939 // 2) emulation via load-blend-store (only if safe and legal to do so, 940 // be aware on the race conditions), or 941 // 3) element-by-element predicate check and scalar store. 942 MaskedOp.insert(SI); 943 continue; 944 } 945 if (I.mayThrow()) 946 return false; 947 } 948 949 return true; 950 } 951 952 bool LoopVectorizationLegality::canVectorizeWithIfConvert() { 953 if (!EnableIfConversion) { 954 reportVectorizationFailure("If-conversion is disabled", 955 "if-conversion is disabled", 956 "IfConversionDisabled"); 957 return false; 958 } 959 960 assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable"); 961 962 // A list of pointers that we can safely read and write to. 963 SmallPtrSet<Value *, 8> SafePointes; 964 965 // Collect safe addresses. 966 for (BasicBlock *BB : TheLoop->blocks()) { 967 if (blockNeedsPredication(BB)) 968 continue; 969 970 for (Instruction &I : *BB) 971 if (auto *Ptr = getLoadStorePointerOperand(&I)) 972 SafePointes.insert(Ptr); 973 } 974 975 // Collect the blocks that need predication. 976 BasicBlock *Header = TheLoop->getHeader(); 977 for (BasicBlock *BB : TheLoop->blocks()) { 978 // We don't support switch statements inside loops. 979 if (!isa<BranchInst>(BB->getTerminator())) { 980 reportVectorizationFailure("Loop contains a switch statement", 981 "loop contains a switch statement", 982 "LoopContainsSwitch", BB->getTerminator()); 983 return false; 984 } 985 986 // We must be able to predicate all blocks that need to be predicated. 987 if (blockNeedsPredication(BB)) { 988 if (!blockCanBePredicated(BB, SafePointes)) { 989 reportVectorizationFailure( 990 "Control flow cannot be substituted for a select", 991 "control flow cannot be substituted for a select", 992 "NoCFGForSelect", BB->getTerminator()); 993 return false; 994 } 995 } else if (BB != Header && !canIfConvertPHINodes(BB)) { 996 reportVectorizationFailure( 997 "Control flow cannot be substituted for a select", 998 "control flow cannot be substituted for a select", 999 "NoCFGForSelect", BB->getTerminator()); 1000 return false; 1001 } 1002 } 1003 1004 // We can if-convert this loop. 1005 return true; 1006 } 1007 1008 // Helper function to canVectorizeLoopNestCFG. 1009 bool LoopVectorizationLegality::canVectorizeLoopCFG(Loop *Lp, 1010 bool UseVPlanNativePath) { 1011 assert((UseVPlanNativePath || Lp->empty()) && 1012 "VPlan-native path is not enabled."); 1013 1014 // TODO: ORE should be improved to show more accurate information when an 1015 // outer loop can't be vectorized because a nested loop is not understood or 1016 // legal. Something like: "outer_loop_location: loop not vectorized: 1017 // (inner_loop_location) loop control flow is not understood by vectorizer". 1018 1019 // Store the result and return it at the end instead of exiting early, in case 1020 // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1021 bool Result = true; 1022 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1023 1024 // We must have a loop in canonical form. Loops with indirectbr in them cannot 1025 // be canonicalized. 1026 if (!Lp->getLoopPreheader()) { 1027 reportVectorizationFailure("Loop doesn't have a legal pre-header", 1028 "loop control flow is not understood by vectorizer", 1029 "CFGNotUnderstood"); 1030 if (DoExtraAnalysis) 1031 Result = false; 1032 else 1033 return false; 1034 } 1035 1036 // We must have a single backedge. 1037 if (Lp->getNumBackEdges() != 1) { 1038 reportVectorizationFailure("The loop must have a single backedge", 1039 "loop control flow is not understood by vectorizer", 1040 "CFGNotUnderstood"); 1041 if (DoExtraAnalysis) 1042 Result = false; 1043 else 1044 return false; 1045 } 1046 1047 // We must have a single exiting block. 1048 if (!Lp->getExitingBlock()) { 1049 reportVectorizationFailure("The loop must have an exiting block", 1050 "loop control flow is not understood by vectorizer", 1051 "CFGNotUnderstood"); 1052 if (DoExtraAnalysis) 1053 Result = false; 1054 else 1055 return false; 1056 } 1057 1058 // We only handle bottom-tested loops, i.e. loop in which the condition is 1059 // checked at the end of each iteration. With that we can assume that all 1060 // instructions in the loop are executed the same number of times. 1061 if (Lp->getExitingBlock() != Lp->getLoopLatch()) { 1062 reportVectorizationFailure("The exiting block is not the loop latch", 1063 "loop control flow is not understood by vectorizer", 1064 "CFGNotUnderstood"); 1065 if (DoExtraAnalysis) 1066 Result = false; 1067 else 1068 return false; 1069 } 1070 1071 return Result; 1072 } 1073 1074 bool LoopVectorizationLegality::canVectorizeLoopNestCFG( 1075 Loop *Lp, bool UseVPlanNativePath) { 1076 // Store the result and return it at the end instead of exiting early, in case 1077 // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1078 bool Result = true; 1079 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1080 if (!canVectorizeLoopCFG(Lp, UseVPlanNativePath)) { 1081 if (DoExtraAnalysis) 1082 Result = false; 1083 else 1084 return false; 1085 } 1086 1087 // Recursively check whether the loop control flow of nested loops is 1088 // understood. 1089 for (Loop *SubLp : *Lp) 1090 if (!canVectorizeLoopNestCFG(SubLp, UseVPlanNativePath)) { 1091 if (DoExtraAnalysis) 1092 Result = false; 1093 else 1094 return false; 1095 } 1096 1097 return Result; 1098 } 1099 1100 bool LoopVectorizationLegality::canVectorize(bool UseVPlanNativePath) { 1101 // Store the result and return it at the end instead of exiting early, in case 1102 // allowExtraAnalysis is used to report multiple reasons for not vectorizing. 1103 bool Result = true; 1104 1105 bool DoExtraAnalysis = ORE->allowExtraAnalysis(DEBUG_TYPE); 1106 // Check whether the loop-related control flow in the loop nest is expected by 1107 // vectorizer. 1108 if (!canVectorizeLoopNestCFG(TheLoop, UseVPlanNativePath)) { 1109 if (DoExtraAnalysis) 1110 Result = false; 1111 else 1112 return false; 1113 } 1114 1115 // We need to have a loop header. 1116 LLVM_DEBUG(dbgs() << "LV: Found a loop: " << TheLoop->getHeader()->getName() 1117 << '\n'); 1118 1119 // Specific checks for outer loops. We skip the remaining legal checks at this 1120 // point because they don't support outer loops. 1121 if (!TheLoop->empty()) { 1122 assert(UseVPlanNativePath && "VPlan-native path is not enabled."); 1123 1124 if (!canVectorizeOuterLoop()) { 1125 reportVectorizationFailure("Unsupported outer loop", 1126 "unsupported outer loop", 1127 "UnsupportedOuterLoop"); 1128 // TODO: Implement DoExtraAnalysis when subsequent legal checks support 1129 // outer loops. 1130 return false; 1131 } 1132 1133 LLVM_DEBUG(dbgs() << "LV: We can vectorize this outer loop!\n"); 1134 return Result; 1135 } 1136 1137 assert(TheLoop->empty() && "Inner loop expected."); 1138 // Check if we can if-convert non-single-bb loops. 1139 unsigned NumBlocks = TheLoop->getNumBlocks(); 1140 if (NumBlocks != 1 && !canVectorizeWithIfConvert()) { 1141 LLVM_DEBUG(dbgs() << "LV: Can't if-convert the loop.\n"); 1142 if (DoExtraAnalysis) 1143 Result = false; 1144 else 1145 return false; 1146 } 1147 1148 // Check if we can vectorize the instructions and CFG in this loop. 1149 if (!canVectorizeInstrs()) { 1150 LLVM_DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n"); 1151 if (DoExtraAnalysis) 1152 Result = false; 1153 else 1154 return false; 1155 } 1156 1157 // Go over each instruction and look at memory deps. 1158 if (!canVectorizeMemory()) { 1159 LLVM_DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n"); 1160 if (DoExtraAnalysis) 1161 Result = false; 1162 else 1163 return false; 1164 } 1165 1166 LLVM_DEBUG(dbgs() << "LV: We can vectorize this loop" 1167 << (LAI->getRuntimePointerChecking()->Need 1168 ? " (with a runtime bound check)" 1169 : "") 1170 << "!\n"); 1171 1172 unsigned SCEVThreshold = VectorizeSCEVCheckThreshold; 1173 if (Hints->getForce() == LoopVectorizeHints::FK_Enabled) 1174 SCEVThreshold = PragmaVectorizeSCEVCheckThreshold; 1175 1176 if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) { 1177 reportVectorizationFailure("Too many SCEV checks needed", 1178 "Too many SCEV assumptions need to be made and checked at runtime", 1179 "TooManySCEVRunTimeChecks"); 1180 if (DoExtraAnalysis) 1181 Result = false; 1182 else 1183 return false; 1184 } 1185 1186 // Okay! We've done all the tests. If any have failed, return false. Otherwise 1187 // we can vectorize, and at this point we don't have any other mem analysis 1188 // which may limit our maximum vectorization factor, so just return true with 1189 // no restrictions. 1190 return Result; 1191 } 1192 1193 bool LoopVectorizationLegality::canFoldTailByMasking() { 1194 1195 LLVM_DEBUG(dbgs() << "LV: checking if tail can be folded by masking.\n"); 1196 1197 if (!PrimaryInduction) { 1198 reportVectorizationFailure( 1199 "No primary induction, cannot fold tail by masking", 1200 "Missing a primary induction variable in the loop, which is " 1201 "needed in order to fold tail by masking as required.", 1202 "NoPrimaryInduction"); 1203 return false; 1204 } 1205 1206 // TODO: handle reductions when tail is folded by masking. 1207 if (!Reductions.empty()) { 1208 reportVectorizationFailure( 1209 "Loop has reductions, cannot fold tail by masking", 1210 "Cannot fold tail by masking in the presence of reductions.", 1211 "ReductionFoldingTailByMasking"); 1212 return false; 1213 } 1214 1215 // TODO: handle outside users when tail is folded by masking. 1216 for (auto *AE : AllowedExit) { 1217 // Check that all users of allowed exit values are inside the loop. 1218 for (User *U : AE->users()) { 1219 Instruction *UI = cast<Instruction>(U); 1220 if (TheLoop->contains(UI)) 1221 continue; 1222 reportVectorizationFailure( 1223 "Cannot fold tail by masking, loop has an outside user for", 1224 "Cannot fold tail by masking in the presence of live outs.", 1225 "LiveOutFoldingTailByMasking", UI); 1226 return false; 1227 } 1228 } 1229 1230 // The list of pointers that we can safely read and write to remains empty. 1231 SmallPtrSet<Value *, 8> SafePointers; 1232 1233 // Check and mark all blocks for predication, including those that ordinarily 1234 // do not need predication such as the header block. 1235 for (BasicBlock *BB : TheLoop->blocks()) { 1236 if (!blockCanBePredicated(BB, SafePointers)) { 1237 reportVectorizationFailure( 1238 "Cannot fold tail by masking as required", 1239 "control flow cannot be substituted for a select", 1240 "NoCFGForSelect", BB->getTerminator()); 1241 return false; 1242 } 1243 } 1244 1245 LLVM_DEBUG(dbgs() << "LV: can fold tail by masking.\n"); 1246 return true; 1247 } 1248 1249 } // namespace llvm 1250