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