1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===// 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 /// \file 10 /// This is the LLVM vectorization plan. It represents a candidate for 11 /// vectorization, allowing to plan and optimize how to vectorize a given loop 12 /// before generating LLVM-IR. 13 /// The vectorizer uses vectorization plans to estimate the costs of potential 14 /// candidates and if profitable to execute the desired plan, generating vector 15 /// LLVM-IR code. 16 /// 17 //===----------------------------------------------------------------------===// 18 19 #include "VPlan.h" 20 #include "LoopVectorizationPlanner.h" 21 #include "VPlanCFG.h" 22 #include "VPlanPatternMatch.h" 23 #include "VPlanTransforms.h" 24 #include "VPlanUtils.h" 25 #include "llvm/ADT/PostOrderIterator.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringExtras.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Analysis/DomTreeUpdater.h" 31 #include "llvm/Analysis/LoopInfo.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CFG.h" 34 #include "llvm/IR/IRBuilder.h" 35 #include "llvm/IR/Instruction.h" 36 #include "llvm/IR/Instructions.h" 37 #include "llvm/IR/Type.h" 38 #include "llvm/IR/Value.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/GraphWriter.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 45 #include "llvm/Transforms/Utils/LoopVersioning.h" 46 #include <cassert> 47 #include <string> 48 49 using namespace llvm; 50 using namespace llvm::VPlanPatternMatch; 51 52 namespace llvm { 53 extern cl::opt<bool> EnableVPlanNativePath; 54 } 55 extern cl::opt<unsigned> ForceTargetInstructionCost; 56 57 static cl::opt<bool> PrintVPlansInDotFormat( 58 "vplan-print-in-dot-format", cl::Hidden, 59 cl::desc("Use dot format instead of plain text when dumping VPlans")); 60 61 #define DEBUG_TYPE "vplan" 62 63 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 64 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 65 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 66 VPSlotTracker SlotTracker( 67 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 68 V.print(OS, SlotTracker); 69 return OS; 70 } 71 #endif 72 73 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 74 const ElementCount &VF) const { 75 switch (LaneKind) { 76 case VPLane::Kind::ScalableLast: 77 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 78 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 79 Builder.getInt32(VF.getKnownMinValue() - Lane)); 80 case VPLane::Kind::First: 81 return Builder.getInt32(Lane); 82 } 83 llvm_unreachable("Unknown lane kind"); 84 } 85 86 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 87 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 88 if (Def) 89 Def->addDefinedValue(this); 90 } 91 92 VPValue::~VPValue() { 93 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 94 if (Def) 95 Def->removeDefinedValue(this); 96 } 97 98 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 99 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 100 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 101 R->print(OS, "", SlotTracker); 102 else 103 printAsOperand(OS, SlotTracker); 104 } 105 106 void VPValue::dump() const { 107 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 108 VPSlotTracker SlotTracker( 109 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 110 print(dbgs(), SlotTracker); 111 dbgs() << "\n"; 112 } 113 114 void VPDef::dump() const { 115 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 116 VPSlotTracker SlotTracker( 117 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 118 print(dbgs(), "", SlotTracker); 119 dbgs() << "\n"; 120 } 121 #endif 122 123 VPRecipeBase *VPValue::getDefiningRecipe() { 124 return cast_or_null<VPRecipeBase>(Def); 125 } 126 127 const VPRecipeBase *VPValue::getDefiningRecipe() const { 128 return cast_or_null<VPRecipeBase>(Def); 129 } 130 131 // Get the top-most entry block of \p Start. This is the entry block of the 132 // containing VPlan. This function is templated to support both const and non-const blocks 133 template <typename T> static T *getPlanEntry(T *Start) { 134 T *Next = Start; 135 T *Current = Start; 136 while ((Next = Next->getParent())) 137 Current = Next; 138 139 SmallSetVector<T *, 8> WorkList; 140 WorkList.insert(Current); 141 142 for (unsigned i = 0; i < WorkList.size(); i++) { 143 T *Current = WorkList[i]; 144 if (Current->getNumPredecessors() == 0) 145 return Current; 146 auto &Predecessors = Current->getPredecessors(); 147 WorkList.insert(Predecessors.begin(), Predecessors.end()); 148 } 149 150 llvm_unreachable("VPlan without any entry node without predecessors"); 151 } 152 153 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 154 155 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 156 157 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 158 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 159 const VPBlockBase *Block = this; 160 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 161 Block = Region->getEntry(); 162 return cast<VPBasicBlock>(Block); 163 } 164 165 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 166 VPBlockBase *Block = this; 167 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 168 Block = Region->getEntry(); 169 return cast<VPBasicBlock>(Block); 170 } 171 172 void VPBlockBase::setPlan(VPlan *ParentPlan) { 173 assert( 174 (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) && 175 "Can only set plan on its entry or preheader block."); 176 Plan = ParentPlan; 177 } 178 179 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 180 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const { 181 const VPBlockBase *Block = this; 182 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 183 Block = Region->getExiting(); 184 return cast<VPBasicBlock>(Block); 185 } 186 187 VPBasicBlock *VPBlockBase::getExitingBasicBlock() { 188 VPBlockBase *Block = this; 189 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 190 Block = Region->getExiting(); 191 return cast<VPBasicBlock>(Block); 192 } 193 194 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 195 if (!Successors.empty() || !Parent) 196 return this; 197 assert(Parent->getExiting() == this && 198 "Block w/o successors not the exiting block of its parent."); 199 return Parent->getEnclosingBlockWithSuccessors(); 200 } 201 202 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 203 if (!Predecessors.empty() || !Parent) 204 return this; 205 assert(Parent->getEntry() == this && 206 "Block w/o predecessors not the entry of its parent."); 207 return Parent->getEnclosingBlockWithPredecessors(); 208 } 209 210 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 211 for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry))) 212 delete Block; 213 } 214 215 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 216 iterator It = begin(); 217 while (It != end() && It->isPhi()) 218 It++; 219 return It; 220 } 221 222 VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI, 223 DominatorTree *DT, IRBuilderBase &Builder, 224 InnerLoopVectorizer *ILV, VPlan *Plan) 225 : VF(VF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan), 226 LVer(nullptr), TypeAnalysis(Plan->getCanonicalIV()->getScalarType()) {} 227 228 Value *VPTransformState::get(VPValue *Def, const VPLane &Lane) { 229 if (Def->isLiveIn()) 230 return Def->getLiveInIRValue(); 231 232 if (hasScalarValue(Def, Lane)) 233 return Data.VPV2Scalars[Def][Lane.mapToCacheIndex(VF)]; 234 235 if (!Lane.isFirstLane() && vputils::isUniformAfterVectorization(Def) && 236 hasScalarValue(Def, VPLane::getFirstLane())) { 237 return Data.VPV2Scalars[Def][0]; 238 } 239 240 assert(hasVectorValue(Def)); 241 auto *VecPart = Data.VPV2Vector[Def]; 242 if (!VecPart->getType()->isVectorTy()) { 243 assert(Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 244 return VecPart; 245 } 246 // TODO: Cache created scalar values. 247 Value *LaneV = Lane.getAsRuntimeExpr(Builder, VF); 248 auto *Extract = Builder.CreateExtractElement(VecPart, LaneV); 249 // set(Def, Extract, Instance); 250 return Extract; 251 } 252 253 Value *VPTransformState::get(VPValue *Def, bool NeedsScalar) { 254 if (NeedsScalar) { 255 assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def) || 256 !vputils::onlyFirstLaneUsed(Def) || 257 (hasScalarValue(Def, VPLane(0)) && 258 Data.VPV2Scalars[Def].size() == 1)) && 259 "Trying to access a single scalar per part but has multiple scalars " 260 "per part."); 261 return get(Def, VPLane(0)); 262 } 263 264 // If Values have been set for this Def return the one relevant for \p Part. 265 if (hasVectorValue(Def)) 266 return Data.VPV2Vector[Def]; 267 268 auto GetBroadcastInstrs = [this, Def](Value *V) { 269 bool SafeToHoist = Def->isDefinedOutsideLoopRegions(); 270 if (VF.isScalar()) 271 return V; 272 // Place the code for broadcasting invariant variables in the new preheader. 273 IRBuilder<>::InsertPointGuard Guard(Builder); 274 if (SafeToHoist) { 275 BasicBlock *LoopVectorPreHeader = 276 CFG.VPBB2IRBB[Plan->getVectorPreheader()]; 277 if (LoopVectorPreHeader) 278 Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator()); 279 } 280 281 // Place the code for broadcasting invariant variables in the new preheader. 282 // Broadcast the scalar into all locations in the vector. 283 Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast"); 284 285 return Shuf; 286 }; 287 288 if (!hasScalarValue(Def, {0})) { 289 assert(Def->isLiveIn() && "expected a live-in"); 290 Value *IRV = Def->getLiveInIRValue(); 291 Value *B = GetBroadcastInstrs(IRV); 292 set(Def, B); 293 return B; 294 } 295 296 Value *ScalarValue = get(Def, VPLane(0)); 297 // If we aren't vectorizing, we can just copy the scalar map values over 298 // to the vector map. 299 if (VF.isScalar()) { 300 set(Def, ScalarValue); 301 return ScalarValue; 302 } 303 304 bool IsUniform = vputils::isUniformAfterVectorization(Def); 305 306 VPLane LastLane(IsUniform ? 0 : VF.getKnownMinValue() - 1); 307 // Check if there is a scalar value for the selected lane. 308 if (!hasScalarValue(Def, LastLane)) { 309 // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and 310 // VPExpandSCEVRecipes can also be uniform. 311 assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) || 312 isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) || 313 isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) && 314 "unexpected recipe found to be invariant"); 315 IsUniform = true; 316 LastLane = 0; 317 } 318 319 auto *LastInst = cast<Instruction>(get(Def, LastLane)); 320 // Set the insert point after the last scalarized instruction or after the 321 // last PHI, if LastInst is a PHI. This ensures the insertelement sequence 322 // will directly follow the scalar definitions. 323 auto OldIP = Builder.saveIP(); 324 auto NewIP = 325 isa<PHINode>(LastInst) 326 ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI()) 327 : std::next(BasicBlock::iterator(LastInst)); 328 Builder.SetInsertPoint(&*NewIP); 329 330 // However, if we are vectorizing, we need to construct the vector values. 331 // If the value is known to be uniform after vectorization, we can just 332 // broadcast the scalar value corresponding to lane zero. Otherwise, we 333 // construct the vector values using insertelement instructions. Since the 334 // resulting vectors are stored in State, we will only generate the 335 // insertelements once. 336 Value *VectorValue = nullptr; 337 if (IsUniform) { 338 VectorValue = GetBroadcastInstrs(ScalarValue); 339 set(Def, VectorValue); 340 } else { 341 // Initialize packing with insertelements to start from undef. 342 assert(!VF.isScalable() && "VF is assumed to be non scalable."); 343 Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF)); 344 set(Def, Undef); 345 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane) 346 packScalarIntoVectorValue(Def, Lane); 347 VectorValue = get(Def); 348 } 349 Builder.restoreIP(OldIP); 350 return VectorValue; 351 } 352 353 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) { 354 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion(); 355 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()]; 356 } 357 358 void VPTransformState::addNewMetadata(Instruction *To, 359 const Instruction *Orig) { 360 // If the loop was versioned with memchecks, add the corresponding no-alias 361 // metadata. 362 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 363 LVer->annotateInstWithNoAlias(To, Orig); 364 } 365 366 void VPTransformState::addMetadata(Value *To, Instruction *From) { 367 // No source instruction to transfer metadata from? 368 if (!From) 369 return; 370 371 if (Instruction *ToI = dyn_cast<Instruction>(To)) { 372 propagateMetadata(ToI, From); 373 addNewMetadata(ToI, From); 374 } 375 } 376 377 void VPTransformState::setDebugLocFrom(DebugLoc DL) { 378 const DILocation *DIL = DL; 379 // When a FSDiscriminator is enabled, we don't need to add the multiply 380 // factors to the discriminators. 381 if (DIL && 382 Builder.GetInsertBlock() 383 ->getParent() 384 ->shouldEmitDebugInfoForProfiling() && 385 !EnableFSDiscriminator) { 386 // FIXME: For scalable vectors, assume vscale=1. 387 unsigned UF = Plan->getUF(); 388 auto NewDIL = 389 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue()); 390 if (NewDIL) 391 Builder.SetCurrentDebugLocation(*NewDIL); 392 else 393 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: " 394 << DIL->getFilename() << " Line: " << DIL->getLine()); 395 } else 396 Builder.SetCurrentDebugLocation(DIL); 397 } 398 399 void VPTransformState::packScalarIntoVectorValue(VPValue *Def, 400 const VPLane &Lane) { 401 Value *ScalarInst = get(Def, Lane); 402 Value *VectorValue = get(Def); 403 VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst, 404 Lane.getAsRuntimeExpr(Builder, VF)); 405 set(Def, VectorValue); 406 } 407 408 BasicBlock * 409 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 410 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 411 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 412 BasicBlock *PrevBB = CFG.PrevBB; 413 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 414 PrevBB->getParent(), CFG.ExitBB); 415 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 416 417 return NewBB; 418 } 419 420 void VPBasicBlock::connectToPredecessors(VPTransformState::CFGState &CFG) { 421 BasicBlock *NewBB = CFG.VPBB2IRBB[this]; 422 // Hook up the new basic block to its predecessors. 423 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 424 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 425 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 426 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 427 428 assert(PredBB && "Predecessor basic-block not found building successor."); 429 auto *PredBBTerminator = PredBB->getTerminator(); 430 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 431 432 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 433 if (isa<UnreachableInst>(PredBBTerminator)) { 434 assert(PredVPSuccessors.size() == 1 && 435 "Predecessor ending w/o branch must have single successor."); 436 DebugLoc DL = PredBBTerminator->getDebugLoc(); 437 PredBBTerminator->eraseFromParent(); 438 auto *Br = BranchInst::Create(NewBB, PredBB); 439 Br->setDebugLoc(DL); 440 } else if (TermBr && !TermBr->isConditional()) { 441 TermBr->setSuccessor(0, NewBB); 442 } else { 443 // Set each forward successor here when it is created, excluding 444 // backedges. A backward successor is set when the branch is created. 445 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 446 assert( 447 (!TermBr->getSuccessor(idx) || 448 (isa<VPIRBasicBlock>(this) && TermBr->getSuccessor(idx) == NewBB)) && 449 "Trying to reset an existing successor block."); 450 TermBr->setSuccessor(idx, NewBB); 451 } 452 CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}}); 453 } 454 } 455 456 void VPIRBasicBlock::execute(VPTransformState *State) { 457 assert(getHierarchicalSuccessors().size() <= 2 && 458 "VPIRBasicBlock can have at most two successors at the moment!"); 459 State->Builder.SetInsertPoint(IRBB->getTerminator()); 460 State->CFG.PrevBB = IRBB; 461 State->CFG.VPBB2IRBB[this] = IRBB; 462 executeRecipes(State, IRBB); 463 // Create a branch instruction to terminate IRBB if one was not created yet 464 // and is needed. 465 if (getSingleSuccessor() && isa<UnreachableInst>(IRBB->getTerminator())) { 466 auto *Br = State->Builder.CreateBr(IRBB); 467 Br->setOperand(0, nullptr); 468 IRBB->getTerminator()->eraseFromParent(); 469 } else { 470 assert( 471 (getNumSuccessors() == 0 || isa<BranchInst>(IRBB->getTerminator())) && 472 "other blocks must be terminated by a branch"); 473 } 474 475 connectToPredecessors(State->CFG); 476 } 477 478 void VPBasicBlock::execute(VPTransformState *State) { 479 bool Replica = bool(State->Lane); 480 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 481 VPBlockBase *SingleHPred = nullptr; 482 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 483 484 auto IsLoopRegion = [](VPBlockBase *BB) { 485 auto *R = dyn_cast<VPRegionBlock>(BB); 486 return R && !R->isReplicator(); 487 }; 488 489 // 1. Create an IR basic block. 490 if (PrevVPBB && /* A */ 491 !((SingleHPred = getSingleHierarchicalPredecessor()) && 492 SingleHPred->getExitingBasicBlock() == PrevVPBB && 493 PrevVPBB->getSingleHierarchicalSuccessor() && 494 (SingleHPred->getParent() == getEnclosingLoopRegion() && 495 !IsLoopRegion(SingleHPred))) && /* B */ 496 !(Replica && getPredecessors().empty())) { /* C */ 497 // The last IR basic block is reused, as an optimization, in three cases: 498 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 499 // B. when the current VPBB has a single (hierarchical) predecessor which 500 // is PrevVPBB and the latter has a single (hierarchical) successor which 501 // both are in the same non-replicator region; and 502 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 503 // is the exiting VPBB of this region from a previous instance, or the 504 // predecessor of this region. 505 506 NewBB = createEmptyBasicBlock(State->CFG); 507 508 State->Builder.SetInsertPoint(NewBB); 509 // Temporarily terminate with unreachable until CFG is rewired. 510 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 511 // Register NewBB in its loop. In innermost loops its the same for all 512 // BB's. 513 if (State->CurrentVectorLoop) 514 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 515 State->Builder.SetInsertPoint(Terminator); 516 517 State->CFG.PrevBB = NewBB; 518 State->CFG.VPBB2IRBB[this] = NewBB; 519 connectToPredecessors(State->CFG); 520 } else { 521 State->CFG.VPBB2IRBB[this] = NewBB; 522 } 523 524 // 2. Fill the IR basic block with IR instructions. 525 executeRecipes(State, NewBB); 526 } 527 528 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 529 for (VPRecipeBase &R : Recipes) { 530 for (auto *Def : R.definedValues()) 531 Def->replaceAllUsesWith(NewValue); 532 533 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 534 R.setOperand(I, NewValue); 535 } 536 } 537 538 void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) { 539 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 540 << " in BB:" << BB->getName() << '\n'); 541 542 State->CFG.PrevVPBB = this; 543 544 for (VPRecipeBase &Recipe : Recipes) 545 Recipe.execute(*State); 546 547 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB); 548 } 549 550 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 551 assert((SplitAt == end() || SplitAt->getParent() == this) && 552 "can only split at a position in the same block"); 553 554 SmallVector<VPBlockBase *, 2> Succs(successors()); 555 // First, disconnect the current block from its successors. 556 for (VPBlockBase *Succ : Succs) 557 VPBlockUtils::disconnectBlocks(this, Succ); 558 559 // Create new empty block after the block to split. 560 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 561 VPBlockUtils::insertBlockAfter(SplitBlock, this); 562 563 // Add successors for block to split to new block. 564 for (VPBlockBase *Succ : Succs) 565 VPBlockUtils::connectBlocks(SplitBlock, Succ); 566 567 // Finally, move the recipes starting at SplitAt to new block. 568 for (VPRecipeBase &ToMove : 569 make_early_inc_range(make_range(SplitAt, this->end()))) 570 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 571 572 return SplitBlock; 573 } 574 575 /// Return the enclosing loop region for region \p P. The templated version is 576 /// used to support both const and non-const block arguments. 577 template <typename T> static T *getEnclosingLoopRegionForRegion(T *P) { 578 if (P && P->isReplicator()) { 579 P = P->getParent(); 580 assert(!cast<VPRegionBlock>(P)->isReplicator() && 581 "unexpected nested replicate regions"); 582 } 583 return P; 584 } 585 586 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 587 return getEnclosingLoopRegionForRegion(getParent()); 588 } 589 590 const VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() const { 591 return getEnclosingLoopRegionForRegion(getParent()); 592 } 593 594 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 595 if (VPBB->empty()) { 596 assert( 597 VPBB->getNumSuccessors() < 2 && 598 "block with multiple successors doesn't have a recipe as terminator"); 599 return false; 600 } 601 602 const VPRecipeBase *R = &VPBB->back(); 603 bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) || 604 match(R, m_BranchOnCond(m_VPValue())) || 605 match(R, m_BranchOnCount(m_VPValue(), m_VPValue())); 606 (void)IsCondBranch; 607 608 if (VPBB->getNumSuccessors() >= 2 || 609 (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) { 610 assert(IsCondBranch && "block with multiple successors not terminated by " 611 "conditional branch recipe"); 612 613 return true; 614 } 615 616 assert( 617 !IsCondBranch && 618 "block with 0 or 1 successors terminated by conditional branch recipe"); 619 return false; 620 } 621 622 VPRecipeBase *VPBasicBlock::getTerminator() { 623 if (hasConditionalTerminator(this)) 624 return &back(); 625 return nullptr; 626 } 627 628 const VPRecipeBase *VPBasicBlock::getTerminator() const { 629 if (hasConditionalTerminator(this)) 630 return &back(); 631 return nullptr; 632 } 633 634 bool VPBasicBlock::isExiting() const { 635 return getParent() && getParent()->getExitingBasicBlock() == this; 636 } 637 638 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 639 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 640 if (getSuccessors().empty()) { 641 O << Indent << "No successors\n"; 642 } else { 643 O << Indent << "Successor(s): "; 644 ListSeparator LS; 645 for (auto *Succ : getSuccessors()) 646 O << LS << Succ->getName(); 647 O << '\n'; 648 } 649 } 650 651 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 652 VPSlotTracker &SlotTracker) const { 653 O << Indent << getName() << ":\n"; 654 655 auto RecipeIndent = Indent + " "; 656 for (const VPRecipeBase &Recipe : *this) { 657 Recipe.print(O, RecipeIndent, SlotTracker); 658 O << '\n'; 659 } 660 661 printSuccessors(O, Indent); 662 } 663 #endif 664 665 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry); 666 667 // Clone the CFG for all nodes reachable from \p Entry, this includes cloning 668 // the blocks and their recipes. Operands of cloned recipes will NOT be updated. 669 // Remapping of operands must be done separately. Returns a pair with the new 670 // entry and exiting blocks of the cloned region. If \p Entry isn't part of a 671 // region, return nullptr for the exiting block. 672 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) { 673 DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks; 674 VPBlockBase *Exiting = nullptr; 675 bool InRegion = Entry->getParent(); 676 // First, clone blocks reachable from Entry. 677 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) { 678 VPBlockBase *NewBB = BB->clone(); 679 Old2NewVPBlocks[BB] = NewBB; 680 if (InRegion && BB->getNumSuccessors() == 0) { 681 assert(!Exiting && "Multiple exiting blocks?"); 682 Exiting = BB; 683 } 684 } 685 assert((!InRegion || Exiting) && "regions must have a single exiting block"); 686 687 // Second, update the predecessors & successors of the cloned blocks. 688 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) { 689 VPBlockBase *NewBB = Old2NewVPBlocks[BB]; 690 SmallVector<VPBlockBase *> NewPreds; 691 for (VPBlockBase *Pred : BB->getPredecessors()) { 692 NewPreds.push_back(Old2NewVPBlocks[Pred]); 693 } 694 NewBB->setPredecessors(NewPreds); 695 SmallVector<VPBlockBase *> NewSuccs; 696 for (VPBlockBase *Succ : BB->successors()) { 697 NewSuccs.push_back(Old2NewVPBlocks[Succ]); 698 } 699 NewBB->setSuccessors(NewSuccs); 700 } 701 702 #if !defined(NDEBUG) 703 // Verify that the order of predecessors and successors matches in the cloned 704 // version. 705 for (const auto &[OldBB, NewBB] : 706 zip(vp_depth_first_shallow(Entry), 707 vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) { 708 for (const auto &[OldPred, NewPred] : 709 zip(OldBB->getPredecessors(), NewBB->getPredecessors())) 710 assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors"); 711 712 for (const auto &[OldSucc, NewSucc] : 713 zip(OldBB->successors(), NewBB->successors())) 714 assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors"); 715 } 716 #endif 717 718 return std::make_pair(Old2NewVPBlocks[Entry], 719 Exiting ? Old2NewVPBlocks[Exiting] : nullptr); 720 } 721 722 VPRegionBlock *VPRegionBlock::clone() { 723 const auto &[NewEntry, NewExiting] = cloneFrom(getEntry()); 724 auto *NewRegion = 725 new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator()); 726 for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry)) 727 Block->setParent(NewRegion); 728 return NewRegion; 729 } 730 731 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 732 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 733 // Drop all references in VPBasicBlocks and replace all uses with 734 // DummyValue. 735 Block->dropAllReferences(NewValue); 736 } 737 738 void VPRegionBlock::execute(VPTransformState *State) { 739 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 740 RPOT(Entry); 741 742 if (!isReplicator()) { 743 // Create and register the new vector loop. 744 Loop *PrevLoop = State->CurrentVectorLoop; 745 State->CurrentVectorLoop = State->LI->AllocateLoop(); 746 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 747 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 748 749 // Insert the new loop into the loop nest and register the new basic blocks 750 // before calling any utilities such as SCEV that require valid LoopInfo. 751 if (ParentLoop) 752 ParentLoop->addChildLoop(State->CurrentVectorLoop); 753 else 754 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 755 756 // Visit the VPBlocks connected to "this", starting from it. 757 for (VPBlockBase *Block : RPOT) { 758 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 759 Block->execute(State); 760 } 761 762 State->CurrentVectorLoop = PrevLoop; 763 return; 764 } 765 766 assert(!State->Lane && "Replicating a Region with non-null instance."); 767 768 // Enter replicating mode. 769 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 770 State->Lane = VPLane(0); 771 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 772 ++Lane) { 773 State->Lane = VPLane(Lane, VPLane::Kind::First); 774 // Visit the VPBlocks connected to \p this, starting from it. 775 for (VPBlockBase *Block : RPOT) { 776 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 777 Block->execute(State); 778 } 779 } 780 781 // Exit replicating mode. 782 State->Lane.reset(); 783 } 784 785 InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) { 786 InstructionCost Cost = 0; 787 for (VPRecipeBase &R : Recipes) 788 Cost += R.cost(VF, Ctx); 789 return Cost; 790 } 791 792 InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) { 793 if (!isReplicator()) { 794 InstructionCost Cost = 0; 795 for (VPBlockBase *Block : vp_depth_first_shallow(getEntry())) 796 Cost += Block->cost(VF, Ctx); 797 InstructionCost BackedgeCost = 798 ForceTargetInstructionCost.getNumOccurrences() 799 ? InstructionCost(ForceTargetInstructionCost.getNumOccurrences()) 800 : Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput); 801 LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF 802 << ": vector loop backedge\n"); 803 Cost += BackedgeCost; 804 return Cost; 805 } 806 807 // Compute the cost of a replicate region. Replicating isn't supported for 808 // scalable vectors, return an invalid cost for them. 809 // TODO: Discard scalable VPlans with replicate recipes earlier after 810 // construction. 811 if (VF.isScalable()) 812 return InstructionCost::getInvalid(); 813 814 // First compute the cost of the conditionally executed recipes, followed by 815 // account for the branching cost, except if the mask is a header mask or 816 // uniform condition. 817 using namespace llvm::VPlanPatternMatch; 818 VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]); 819 InstructionCost ThenCost = Then->cost(VF, Ctx); 820 821 // For the scalar case, we may not always execute the original predicated 822 // block, Thus, scale the block's cost by the probability of executing it. 823 if (VF.isScalar()) 824 return ThenCost / getReciprocalPredBlockProb(); 825 826 return ThenCost; 827 } 828 829 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 830 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 831 VPSlotTracker &SlotTracker) const { 832 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 833 auto NewIndent = Indent + " "; 834 for (auto *BlockBase : vp_depth_first_shallow(Entry)) { 835 O << '\n'; 836 BlockBase->print(O, NewIndent, SlotTracker); 837 } 838 O << Indent << "}\n"; 839 840 printSuccessors(O, Indent); 841 } 842 #endif 843 844 VPlan::~VPlan() { 845 if (Entry) { 846 VPValue DummyValue; 847 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 848 Block->dropAllReferences(&DummyValue); 849 850 VPBlockBase::deleteCFG(Entry); 851 852 Preheader->dropAllReferences(&DummyValue); 853 delete Preheader; 854 } 855 for (VPValue *VPV : VPLiveInsToFree) 856 delete VPV; 857 if (BackedgeTakenCount) 858 delete BackedgeTakenCount; 859 } 860 861 VPIRBasicBlock *VPIRBasicBlock::fromBasicBlock(BasicBlock *IRBB) { 862 auto *VPIRBB = new VPIRBasicBlock(IRBB); 863 for (Instruction &I : 864 make_range(IRBB->begin(), IRBB->getTerminator()->getIterator())) 865 VPIRBB->appendRecipe(new VPIRInstruction(I)); 866 return VPIRBB; 867 } 868 869 VPlanPtr VPlan::createInitialVPlan(Type *InductionTy, 870 PredicatedScalarEvolution &PSE, 871 bool RequiresScalarEpilogueCheck, 872 bool TailFolded, Loop *TheLoop) { 873 VPIRBasicBlock *Entry = 874 VPIRBasicBlock::fromBasicBlock(TheLoop->getLoopPreheader()); 875 VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph"); 876 VPIRBasicBlock *ScalarHeader = 877 VPIRBasicBlock::fromBasicBlock(TheLoop->getHeader()); 878 auto Plan = std::make_unique<VPlan>(Entry, VecPreheader, ScalarHeader); 879 880 // Create SCEV and VPValue for the trip count. 881 882 // Currently only loops with countable exits are vectorized, but calling 883 // getSymbolicMaxBackedgeTakenCount allows enablement work for loops with 884 // uncountable exits whilst also ensuring the symbolic maximum and known 885 // back-edge taken count remain identical for loops with countable exits. 886 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount(); 887 assert((!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) && 888 BackedgeTakenCountSCEV == PSE.getBackedgeTakenCount()) && 889 "Invalid loop count"); 890 ScalarEvolution &SE = *PSE.getSE(); 891 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV, 892 InductionTy, TheLoop); 893 Plan->TripCount = 894 vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE); 895 896 // Create VPRegionBlock, with empty header and latch blocks, to be filled 897 // during processing later. 898 VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body"); 899 VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch"); 900 VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB); 901 auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop", 902 false /*isReplicator*/); 903 904 VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader); 905 VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block"); 906 VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion); 907 908 VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph"); 909 VPBlockUtils::connectBlocks(ScalarPH, ScalarHeader); 910 if (!RequiresScalarEpilogueCheck) { 911 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH); 912 return Plan; 913 } 914 915 // If needed, add a check in the middle block to see if we have completed 916 // all of the iterations in the first vector loop. Three cases: 917 // 1) If (N - N%VF) == N, then we *don't* need to run the remainder. 918 // Thus if tail is to be folded, we know we don't need to run the 919 // remainder and we can set the condition to true. 920 // 2) If we require a scalar epilogue, there is no conditional branch as 921 // we unconditionally branch to the scalar preheader. Do nothing. 922 // 3) Otherwise, construct a runtime check. 923 BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock(); 924 auto *VPExitBlock = VPIRBasicBlock::fromBasicBlock(IRExitBlock); 925 // The connection order corresponds to the operands of the conditional branch. 926 VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB); 927 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH); 928 929 auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator(); 930 // Here we use the same DebugLoc as the scalar loop latch terminator instead 931 // of the corresponding compare because they may have ended up with 932 // different line numbers and we want to avoid awkward line stepping while 933 // debugging. Eg. if the compare has got a line number inside the loop. 934 VPBuilder Builder(MiddleVPBB); 935 VPValue *Cmp = 936 TailFolded 937 ? Plan->getOrAddLiveIn(ConstantInt::getTrue( 938 IntegerType::getInt1Ty(TripCount->getType()->getContext()))) 939 : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(), 940 &Plan->getVectorTripCount(), 941 ScalarLatchTerm->getDebugLoc(), "cmp.n"); 942 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, 943 ScalarLatchTerm->getDebugLoc()); 944 return Plan; 945 } 946 947 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 948 Value *CanonicalIVStartValue, 949 VPTransformState &State) { 950 Type *TCTy = TripCountV->getType(); 951 // Check if the backedge taken count is needed, and if so build it. 952 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 953 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 954 auto *TCMO = Builder.CreateSub(TripCountV, ConstantInt::get(TCTy, 1), 955 "trip.count.minus.1"); 956 BackedgeTakenCount->setUnderlyingValue(TCMO); 957 } 958 959 VectorTripCount.setUnderlyingValue(VectorTripCountV); 960 961 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 962 // FIXME: Model VF * UF computation completely in VPlan. 963 assert(VFxUF.getNumUsers() && "VFxUF expected to always have users"); 964 unsigned UF = getUF(); 965 if (VF.getNumUsers()) { 966 Value *RuntimeVF = getRuntimeVF(Builder, TCTy, State.VF); 967 VF.setUnderlyingValue(RuntimeVF); 968 VFxUF.setUnderlyingValue( 969 UF > 1 ? Builder.CreateMul(RuntimeVF, ConstantInt::get(TCTy, UF)) 970 : RuntimeVF); 971 } else { 972 VFxUF.setUnderlyingValue(createStepForVF(Builder, TCTy, State.VF, UF)); 973 } 974 975 // When vectorizing the epilogue loop, the canonical induction start value 976 // needs to be changed from zero to the value after the main vector loop. 977 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 978 if (CanonicalIVStartValue) { 979 VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue); 980 auto *IV = getCanonicalIV(); 981 assert(all_of(IV->users(), 982 [](const VPUser *U) { 983 return isa<VPScalarIVStepsRecipe>(U) || 984 isa<VPScalarCastRecipe>(U) || 985 isa<VPDerivedIVRecipe>(U) || 986 cast<VPInstruction>(U)->getOpcode() == 987 Instruction::Add; 988 }) && 989 "the canonical IV should only be used by its increment or " 990 "ScalarIVSteps when resetting the start value"); 991 IV->setOperand(0, VPV); 992 } 993 } 994 995 /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p 996 /// VPBB are moved to the end of the newly created VPIRBasicBlock. VPBB must 997 /// have a single predecessor, which is rewired to the new VPIRBasicBlock. All 998 /// successors of VPBB, if any, are rewired to the new VPIRBasicBlock. 999 static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) { 1000 VPIRBasicBlock *IRVPBB = VPIRBasicBlock::fromBasicBlock(IRBB); 1001 for (auto &R : make_early_inc_range(*VPBB)) { 1002 assert(!R.isPhi() && "Tried to move phi recipe to end of block"); 1003 R.moveBefore(*IRVPBB, IRVPBB->end()); 1004 } 1005 1006 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB); 1007 1008 delete VPBB; 1009 } 1010 1011 /// Generate the code inside the preheader and body of the vectorized loop. 1012 /// Assumes a single pre-header basic-block was created for this. Introduce 1013 /// additional basic-blocks as needed, and fill them all. 1014 void VPlan::execute(VPTransformState *State) { 1015 // Initialize CFG state. 1016 State->CFG.PrevVPBB = nullptr; 1017 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 1018 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 1019 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 1020 1021 // Disconnect VectorPreHeader from ExitBB in both the CFG and DT. 1022 cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr); 1023 State->CFG.DTU.applyUpdates( 1024 {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}}); 1025 1026 // Replace regular VPBB's for the middle and scalar preheader blocks with 1027 // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during 1028 // skeleton creation, so we can only create the VPIRBasicBlocks now during 1029 // VPlan execution rather than earlier during VPlan construction. 1030 BasicBlock *MiddleBB = State->CFG.ExitBB; 1031 VPBasicBlock *MiddleVPBB = getMiddleBlock(); 1032 BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor(); 1033 replaceVPBBWithIRVPBB(getScalarPreheader(), ScalarPh); 1034 replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB); 1035 1036 // Disconnect the middle block from its single successor (the scalar loop 1037 // header) in both the CFG and DT. The branch will be recreated during VPlan 1038 // execution. 1039 auto *BrInst = new UnreachableInst(MiddleBB->getContext()); 1040 BrInst->insertBefore(MiddleBB->getTerminator()); 1041 MiddleBB->getTerminator()->eraseFromParent(); 1042 State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}}); 1043 // Disconnect scalar preheader and scalar header, as the dominator tree edge 1044 // will be updated as part of VPlan execution. This allows keeping the DTU 1045 // logic generic during VPlan execution. 1046 State->CFG.DTU.applyUpdates( 1047 {{DominatorTree::Delete, ScalarPh, ScalarPh->getSingleSuccessor()}}); 1048 1049 // Generate code in the loop pre-header and body. 1050 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 1051 Block->execute(State); 1052 1053 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 1054 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 1055 1056 // Fix the latch value of canonical, reduction and first-order recurrences 1057 // phis in the vector loop. 1058 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 1059 for (VPRecipeBase &R : Header->phis()) { 1060 // Skip phi-like recipes that generate their backedege values themselves. 1061 if (isa<VPWidenPHIRecipe>(&R)) 1062 continue; 1063 1064 if (isa<VPWidenPointerInductionRecipe>(&R) || 1065 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 1066 PHINode *Phi = nullptr; 1067 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 1068 Phi = cast<PHINode>(State->get(R.getVPSingleValue())); 1069 } else { 1070 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 1071 assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) && 1072 "recipe generating only scalars should have been replaced"); 1073 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi)); 1074 Phi = cast<PHINode>(GEP->getPointerOperand()); 1075 } 1076 1077 Phi->setIncomingBlock(1, VectorLatchBB); 1078 1079 // Move the last step to the end of the latch block. This ensures 1080 // consistent placement of all induction updates. 1081 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 1082 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 1083 1084 // Use the steps for the last part as backedge value for the induction. 1085 if (auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) 1086 Inc->setOperand(0, State->get(IV->getLastUnrolledPartOperand())); 1087 continue; 1088 } 1089 1090 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 1091 bool NeedsScalar = 1092 isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) || 1093 (isa<VPReductionPHIRecipe>(PhiR) && 1094 cast<VPReductionPHIRecipe>(PhiR)->isInLoop()); 1095 Value *Phi = State->get(PhiR, NeedsScalar); 1096 Value *Val = State->get(PhiR->getBackedgeValue(), NeedsScalar); 1097 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 1098 } 1099 1100 State->CFG.DTU.flush(); 1101 assert(State->CFG.DTU.getDomTree().verify( 1102 DominatorTree::VerificationLevel::Fast) && 1103 "DT not preserved correctly"); 1104 } 1105 1106 InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) { 1107 // For now only return the cost of the vector loop region, ignoring any other 1108 // blocks, like the preheader or middle blocks. 1109 return getVectorLoopRegion()->cost(VF, Ctx); 1110 } 1111 1112 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1113 void VPlan::printLiveIns(raw_ostream &O) const { 1114 VPSlotTracker SlotTracker(this); 1115 1116 if (VF.getNumUsers() > 0) { 1117 O << "\nLive-in "; 1118 VF.printAsOperand(O, SlotTracker); 1119 O << " = VF"; 1120 } 1121 1122 if (VFxUF.getNumUsers() > 0) { 1123 O << "\nLive-in "; 1124 VFxUF.printAsOperand(O, SlotTracker); 1125 O << " = VF * UF"; 1126 } 1127 1128 if (VectorTripCount.getNumUsers() > 0) { 1129 O << "\nLive-in "; 1130 VectorTripCount.printAsOperand(O, SlotTracker); 1131 O << " = vector-trip-count"; 1132 } 1133 1134 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 1135 O << "\nLive-in "; 1136 BackedgeTakenCount->printAsOperand(O, SlotTracker); 1137 O << " = backedge-taken count"; 1138 } 1139 1140 O << "\n"; 1141 if (TripCount->isLiveIn()) 1142 O << "Live-in "; 1143 TripCount->printAsOperand(O, SlotTracker); 1144 O << " = original trip-count"; 1145 O << "\n"; 1146 } 1147 1148 LLVM_DUMP_METHOD 1149 void VPlan::print(raw_ostream &O) const { 1150 VPSlotTracker SlotTracker(this); 1151 1152 O << "VPlan '" << getName() << "' {"; 1153 1154 printLiveIns(O); 1155 1156 if (!getPreheader()->empty()) { 1157 O << "\n"; 1158 getPreheader()->print(O, "", SlotTracker); 1159 } 1160 1161 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) { 1162 O << '\n'; 1163 Block->print(O, "", SlotTracker); 1164 } 1165 1166 O << "}\n"; 1167 } 1168 1169 std::string VPlan::getName() const { 1170 std::string Out; 1171 raw_string_ostream RSO(Out); 1172 RSO << Name << " for "; 1173 if (!VFs.empty()) { 1174 RSO << "VF={" << VFs[0]; 1175 for (ElementCount VF : drop_begin(VFs)) 1176 RSO << "," << VF; 1177 RSO << "},"; 1178 } 1179 1180 if (UFs.empty()) { 1181 RSO << "UF>=1"; 1182 } else { 1183 RSO << "UF={" << UFs[0]; 1184 for (unsigned UF : drop_begin(UFs)) 1185 RSO << "," << UF; 1186 RSO << "}"; 1187 } 1188 1189 return Out; 1190 } 1191 1192 LLVM_DUMP_METHOD 1193 void VPlan::printDOT(raw_ostream &O) const { 1194 VPlanPrinter Printer(O, *this); 1195 Printer.dump(); 1196 } 1197 1198 LLVM_DUMP_METHOD 1199 void VPlan::dump() const { print(dbgs()); } 1200 #endif 1201 1202 static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, 1203 DenseMap<VPValue *, VPValue *> &Old2NewVPValues) { 1204 // Update the operands of all cloned recipes starting at NewEntry. This 1205 // traverses all reachable blocks. This is done in two steps, to handle cycles 1206 // in PHI recipes. 1207 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> 1208 OldDeepRPOT(Entry); 1209 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> 1210 NewDeepRPOT(NewEntry); 1211 // First, collect all mappings from old to new VPValues defined by cloned 1212 // recipes. 1213 for (const auto &[OldBB, NewBB] : 1214 zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT), 1215 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) { 1216 assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() && 1217 "blocks must have the same number of recipes"); 1218 for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) { 1219 assert(OldR.getNumOperands() == NewR.getNumOperands() && 1220 "recipes must have the same number of operands"); 1221 assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() && 1222 "recipes must define the same number of operands"); 1223 for (const auto &[OldV, NewV] : 1224 zip(OldR.definedValues(), NewR.definedValues())) 1225 Old2NewVPValues[OldV] = NewV; 1226 } 1227 } 1228 1229 // Update all operands to use cloned VPValues. 1230 for (VPBasicBlock *NewBB : 1231 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) { 1232 for (VPRecipeBase &NewR : *NewBB) 1233 for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) { 1234 VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I)); 1235 NewR.setOperand(I, NewOp); 1236 } 1237 } 1238 } 1239 1240 VPlan *VPlan::duplicate() { 1241 // Clone blocks. 1242 VPBasicBlock *NewPreheader = Preheader->clone(); 1243 const auto &[NewEntry, __] = cloneFrom(Entry); 1244 1245 BasicBlock *ScalarHeaderIRBB = getScalarHeader()->getIRBasicBlock(); 1246 VPIRBasicBlock *NewScalarHeader = cast<VPIRBasicBlock>(*find_if( 1247 vp_depth_first_shallow(NewEntry), [ScalarHeaderIRBB](VPBlockBase *VPB) { 1248 auto *VPIRBB = dyn_cast<VPIRBasicBlock>(VPB); 1249 return VPIRBB && VPIRBB->getIRBasicBlock() == ScalarHeaderIRBB; 1250 })); 1251 // Create VPlan, clone live-ins and remap operands in the cloned blocks. 1252 auto *NewPlan = 1253 new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry), NewScalarHeader); 1254 DenseMap<VPValue *, VPValue *> Old2NewVPValues; 1255 for (VPValue *OldLiveIn : VPLiveInsToFree) { 1256 Old2NewVPValues[OldLiveIn] = 1257 NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue()); 1258 } 1259 Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount; 1260 Old2NewVPValues[&VF] = &NewPlan->VF; 1261 Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF; 1262 if (BackedgeTakenCount) { 1263 NewPlan->BackedgeTakenCount = new VPValue(); 1264 Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount; 1265 } 1266 assert(TripCount && "trip count must be set"); 1267 if (TripCount->isLiveIn()) 1268 Old2NewVPValues[TripCount] = 1269 NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue()); 1270 // else NewTripCount will be created and inserted into Old2NewVPValues when 1271 // TripCount is cloned. In any case NewPlan->TripCount is updated below. 1272 1273 remapOperands(Preheader, NewPreheader, Old2NewVPValues); 1274 remapOperands(Entry, NewEntry, Old2NewVPValues); 1275 1276 // Initialize remaining fields of cloned VPlan. 1277 NewPlan->VFs = VFs; 1278 NewPlan->UFs = UFs; 1279 // TODO: Adjust names. 1280 NewPlan->Name = Name; 1281 assert(Old2NewVPValues.contains(TripCount) && 1282 "TripCount must have been added to Old2NewVPValues"); 1283 NewPlan->TripCount = Old2NewVPValues[TripCount]; 1284 return NewPlan; 1285 } 1286 1287 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1288 1289 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 1290 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 1291 Twine(getOrCreateBID(Block)); 1292 } 1293 1294 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 1295 const std::string &Name = Block->getName(); 1296 if (!Name.empty()) 1297 return Name; 1298 return "VPB" + Twine(getOrCreateBID(Block)); 1299 } 1300 1301 void VPlanPrinter::dump() { 1302 Depth = 1; 1303 bumpIndent(0); 1304 OS << "digraph VPlan {\n"; 1305 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 1306 if (!Plan.getName().empty()) 1307 OS << "\\n" << DOT::EscapeString(Plan.getName()); 1308 1309 { 1310 // Print live-ins. 1311 std::string Str; 1312 raw_string_ostream SS(Str); 1313 Plan.printLiveIns(SS); 1314 SmallVector<StringRef, 0> Lines; 1315 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1316 for (auto Line : Lines) 1317 OS << DOT::EscapeString(Line.str()) << "\\n"; 1318 } 1319 1320 OS << "\"]\n"; 1321 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1322 OS << "edge [fontname=Courier, fontsize=30]\n"; 1323 OS << "compound=true\n"; 1324 1325 dumpBlock(Plan.getPreheader()); 1326 1327 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry())) 1328 dumpBlock(Block); 1329 1330 OS << "}\n"; 1331 } 1332 1333 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1334 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1335 dumpBasicBlock(BasicBlock); 1336 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1337 dumpRegion(Region); 1338 else 1339 llvm_unreachable("Unsupported kind of VPBlock."); 1340 } 1341 1342 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1343 bool Hidden, const Twine &Label) { 1344 // Due to "dot" we print an edge between two regions as an edge between the 1345 // exiting basic block and the entry basic of the respective regions. 1346 const VPBlockBase *Tail = From->getExitingBasicBlock(); 1347 const VPBlockBase *Head = To->getEntryBasicBlock(); 1348 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1349 OS << " [ label=\"" << Label << '\"'; 1350 if (Tail != From) 1351 OS << " ltail=" << getUID(From); 1352 if (Head != To) 1353 OS << " lhead=" << getUID(To); 1354 if (Hidden) 1355 OS << "; splines=none"; 1356 OS << "]\n"; 1357 } 1358 1359 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1360 auto &Successors = Block->getSuccessors(); 1361 if (Successors.size() == 1) 1362 drawEdge(Block, Successors.front(), false, ""); 1363 else if (Successors.size() == 2) { 1364 drawEdge(Block, Successors.front(), false, "T"); 1365 drawEdge(Block, Successors.back(), false, "F"); 1366 } else { 1367 unsigned SuccessorNumber = 0; 1368 for (auto *Successor : Successors) 1369 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1370 } 1371 } 1372 1373 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1374 // Implement dot-formatted dump by performing plain-text dump into the 1375 // temporary storage followed by some post-processing. 1376 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1377 bumpIndent(1); 1378 std::string Str; 1379 raw_string_ostream SS(Str); 1380 // Use no indentation as we need to wrap the lines into quotes ourselves. 1381 BasicBlock->print(SS, "", SlotTracker); 1382 1383 // We need to process each line of the output separately, so split 1384 // single-string plain-text dump. 1385 SmallVector<StringRef, 0> Lines; 1386 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1387 1388 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1389 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1390 }; 1391 1392 // Don't need the "+" after the last line. 1393 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1394 EmitLine(Line, " +\n"); 1395 EmitLine(Lines.back(), "\n"); 1396 1397 bumpIndent(-1); 1398 OS << Indent << "]\n"; 1399 1400 dumpEdges(BasicBlock); 1401 } 1402 1403 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1404 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1405 bumpIndent(1); 1406 OS << Indent << "fontname=Courier\n" 1407 << Indent << "label=\"" 1408 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1409 << DOT::EscapeString(Region->getName()) << "\"\n"; 1410 // Dump the blocks of the region. 1411 assert(Region->getEntry() && "Region contains no inner blocks."); 1412 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry())) 1413 dumpBlock(Block); 1414 bumpIndent(-1); 1415 OS << Indent << "}\n"; 1416 dumpEdges(Region); 1417 } 1418 1419 void VPlanIngredient::print(raw_ostream &O) const { 1420 if (auto *Inst = dyn_cast<Instruction>(V)) { 1421 if (!Inst->getType()->isVoidTy()) { 1422 Inst->printAsOperand(O, false); 1423 O << " = "; 1424 } 1425 O << Inst->getOpcodeName() << " "; 1426 unsigned E = Inst->getNumOperands(); 1427 if (E > 0) { 1428 Inst->getOperand(0)->printAsOperand(O, false); 1429 for (unsigned I = 1; I < E; ++I) 1430 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1431 } 1432 } else // !Inst 1433 V->printAsOperand(O, false); 1434 } 1435 1436 #endif 1437 1438 bool VPValue::isDefinedOutsideLoopRegions() const { 1439 return !hasDefiningRecipe() || 1440 !getDefiningRecipe()->getParent()->getEnclosingLoopRegion(); 1441 } 1442 1443 void VPValue::replaceAllUsesWith(VPValue *New) { 1444 replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; }); 1445 } 1446 1447 void VPValue::replaceUsesWithIf( 1448 VPValue *New, 1449 llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) { 1450 // Note that this early exit is required for correctness; the implementation 1451 // below relies on the number of users for this VPValue to decrease, which 1452 // isn't the case if this == New. 1453 if (this == New) 1454 return; 1455 1456 for (unsigned J = 0; J < getNumUsers();) { 1457 VPUser *User = Users[J]; 1458 bool RemovedUser = false; 1459 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) { 1460 if (User->getOperand(I) != this || !ShouldReplace(*User, I)) 1461 continue; 1462 1463 RemovedUser = true; 1464 User->setOperand(I, New); 1465 } 1466 // If a user got removed after updating the current user, the next user to 1467 // update will be moved to the current position, so we only need to 1468 // increment the index if the number of users did not change. 1469 if (!RemovedUser) 1470 J++; 1471 } 1472 } 1473 1474 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1475 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1476 OS << Tracker.getOrCreateName(this); 1477 } 1478 1479 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1480 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1481 Op->printAsOperand(O, SlotTracker); 1482 }); 1483 } 1484 #endif 1485 1486 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1487 Old2NewTy &Old2New, 1488 InterleavedAccessInfo &IAI) { 1489 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 1490 RPOT(Region->getEntry()); 1491 for (VPBlockBase *Base : RPOT) { 1492 visitBlock(Base, Old2New, IAI); 1493 } 1494 } 1495 1496 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1497 InterleavedAccessInfo &IAI) { 1498 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1499 for (VPRecipeBase &VPI : *VPBB) { 1500 if (isa<VPWidenPHIRecipe>(&VPI)) 1501 continue; 1502 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1503 auto *VPInst = cast<VPInstruction>(&VPI); 1504 1505 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1506 if (!Inst) 1507 continue; 1508 auto *IG = IAI.getInterleaveGroup(Inst); 1509 if (!IG) 1510 continue; 1511 1512 auto NewIGIter = Old2New.find(IG); 1513 if (NewIGIter == Old2New.end()) 1514 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1515 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1516 1517 if (Inst == IG->getInsertPos()) 1518 Old2New[IG]->setInsertPos(VPInst); 1519 1520 InterleaveGroupMap[VPInst] = Old2New[IG]; 1521 InterleaveGroupMap[VPInst]->insertMember( 1522 VPInst, IG->getIndex(Inst), 1523 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1524 : IG->getFactor())); 1525 } 1526 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1527 visitRegion(Region, Old2New, IAI); 1528 else 1529 llvm_unreachable("Unsupported kind of VPBlock."); 1530 } 1531 1532 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1533 InterleavedAccessInfo &IAI) { 1534 Old2NewTy Old2New; 1535 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1536 } 1537 1538 void VPSlotTracker::assignName(const VPValue *V) { 1539 assert(!VPValue2Name.contains(V) && "VPValue already has a name!"); 1540 auto *UV = V->getUnderlyingValue(); 1541 auto *VPI = dyn_cast_or_null<VPInstruction>(V->getDefiningRecipe()); 1542 if (!UV && !(VPI && !VPI->getName().empty())) { 1543 VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str(); 1544 NextSlot++; 1545 return; 1546 } 1547 1548 // Use the name of the underlying Value, wrapped in "ir<>", and versioned by 1549 // appending ".Number" to the name if there are multiple uses. 1550 std::string Name; 1551 if (UV) { 1552 raw_string_ostream S(Name); 1553 UV->printAsOperand(S, false); 1554 } else 1555 Name = VPI->getName(); 1556 1557 assert(!Name.empty() && "Name cannot be empty."); 1558 StringRef Prefix = UV ? "ir<" : "vp<%"; 1559 std::string BaseName = (Twine(Prefix) + Name + Twine(">")).str(); 1560 1561 // First assign the base name for V. 1562 const auto &[A, _] = VPValue2Name.insert({V, BaseName}); 1563 // Integer or FP constants with different types will result in he same string 1564 // due to stripping types. 1565 if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV)) 1566 return; 1567 1568 // If it is already used by C > 0 other VPValues, increase the version counter 1569 // C and use it for V. 1570 const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0}); 1571 if (!UseInserted) { 1572 C->second++; 1573 A->second = (BaseName + Twine(".") + Twine(C->second)).str(); 1574 } 1575 } 1576 1577 void VPSlotTracker::assignNames(const VPlan &Plan) { 1578 if (Plan.VF.getNumUsers() > 0) 1579 assignName(&Plan.VF); 1580 if (Plan.VFxUF.getNumUsers() > 0) 1581 assignName(&Plan.VFxUF); 1582 assignName(&Plan.VectorTripCount); 1583 if (Plan.BackedgeTakenCount) 1584 assignName(Plan.BackedgeTakenCount); 1585 for (VPValue *LI : Plan.VPLiveInsToFree) 1586 assignName(LI); 1587 assignNames(Plan.getPreheader()); 1588 1589 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>> 1590 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry())); 1591 for (const VPBasicBlock *VPBB : 1592 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1593 assignNames(VPBB); 1594 } 1595 1596 void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) { 1597 for (const VPRecipeBase &Recipe : *VPBB) 1598 for (VPValue *Def : Recipe.definedValues()) 1599 assignName(Def); 1600 } 1601 1602 std::string VPSlotTracker::getOrCreateName(const VPValue *V) const { 1603 std::string Name = VPValue2Name.lookup(V); 1604 if (!Name.empty()) 1605 return Name; 1606 1607 // If no name was assigned, no VPlan was provided when creating the slot 1608 // tracker or it is not reachable from the provided VPlan. This can happen, 1609 // e.g. when trying to print a recipe that has not been inserted into a VPlan 1610 // in a debugger. 1611 // TODO: Update VPSlotTracker constructor to assign names to recipes & 1612 // VPValues not associated with a VPlan, instead of constructing names ad-hoc 1613 // here. 1614 const VPRecipeBase *DefR = V->getDefiningRecipe(); 1615 (void)DefR; 1616 assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) && 1617 "VPValue defined by a recipe in a VPlan?"); 1618 1619 // Use the underlying value's name, if there is one. 1620 if (auto *UV = V->getUnderlyingValue()) { 1621 std::string Name; 1622 raw_string_ostream S(Name); 1623 UV->printAsOperand(S, false); 1624 return (Twine("ir<") + Name + ">").str(); 1625 } 1626 1627 return "<badref>"; 1628 } 1629 1630 bool LoopVectorizationPlanner::getDecisionAndClampRange( 1631 const std::function<bool(ElementCount)> &Predicate, VFRange &Range) { 1632 assert(!Range.isEmpty() && "Trying to test an empty VF range."); 1633 bool PredicateAtRangeStart = Predicate(Range.Start); 1634 1635 for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End)) 1636 if (Predicate(TmpVF) != PredicateAtRangeStart) { 1637 Range.End = TmpVF; 1638 break; 1639 } 1640 1641 return PredicateAtRangeStart; 1642 } 1643 1644 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF, 1645 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range 1646 /// of VF's starting at a given VF and extending it as much as possible. Each 1647 /// vectorization decision can potentially shorten this sub-range during 1648 /// buildVPlan(). 1649 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF, 1650 ElementCount MaxVF) { 1651 auto MaxVFTimes2 = MaxVF * 2; 1652 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) { 1653 VFRange SubRange = {VF, MaxVFTimes2}; 1654 auto Plan = buildVPlan(SubRange); 1655 VPlanTransforms::optimize(*Plan); 1656 VPlans.push_back(std::move(Plan)); 1657 VF = SubRange.End; 1658 } 1659 } 1660 1661 VPlan &LoopVectorizationPlanner::getPlanFor(ElementCount VF) const { 1662 assert(count_if(VPlans, 1663 [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) == 1664 1 && 1665 "Multiple VPlans for VF."); 1666 1667 for (const VPlanPtr &Plan : VPlans) { 1668 if (Plan->hasVF(VF)) 1669 return *Plan.get(); 1670 } 1671 llvm_unreachable("No plan found!"); 1672 } 1673 1674 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1675 void LoopVectorizationPlanner::printPlans(raw_ostream &O) { 1676 if (VPlans.empty()) { 1677 O << "LV: No VPlans built.\n"; 1678 return; 1679 } 1680 for (const auto &Plan : VPlans) 1681 if (PrintVPlansInDotFormat) 1682 Plan->printDOT(O); 1683 else 1684 Plan->print(O); 1685 } 1686 #endif 1687 1688 TargetTransformInfo::OperandValueInfo 1689 VPCostContext::getOperandInfo(VPValue *V) const { 1690 if (!V->isLiveIn()) 1691 return {}; 1692 1693 return TTI::getOperandInfo(V->getLiveInIRValue()); 1694 } 1695