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