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 // Hook up the new basic block to its predecessors. 418 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 419 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 420 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 421 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 422 423 assert(PredBB && "Predecessor basic-block not found building successor."); 424 auto *PredBBTerminator = PredBB->getTerminator(); 425 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 426 427 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 428 if (isa<UnreachableInst>(PredBBTerminator)) { 429 assert(PredVPSuccessors.size() == 1 && 430 "Predecessor ending w/o branch must have single successor."); 431 DebugLoc DL = PredBBTerminator->getDebugLoc(); 432 PredBBTerminator->eraseFromParent(); 433 auto *Br = BranchInst::Create(NewBB, PredBB); 434 Br->setDebugLoc(DL); 435 } else if (TermBr && !TermBr->isConditional()) { 436 TermBr->setSuccessor(0, NewBB); 437 } else { 438 // Set each forward successor here when it is created, excluding 439 // backedges. A backward successor is set when the branch is created. 440 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 441 assert(!TermBr->getSuccessor(idx) && 442 "Trying to reset an existing successor block."); 443 TermBr->setSuccessor(idx, NewBB); 444 } 445 CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}}); 446 } 447 return NewBB; 448 } 449 450 void VPIRBasicBlock::execute(VPTransformState *State) { 451 assert(getHierarchicalSuccessors().size() <= 2 && 452 "VPIRBasicBlock can have at most two successors at the moment!"); 453 State->Builder.SetInsertPoint(IRBB->getTerminator()); 454 executeRecipes(State, IRBB); 455 // Create a branch instruction to terminate IRBB if one was not created yet 456 // and is needed. 457 if (getSingleSuccessor() && isa<UnreachableInst>(IRBB->getTerminator())) { 458 auto *Br = State->Builder.CreateBr(IRBB); 459 Br->setOperand(0, nullptr); 460 IRBB->getTerminator()->eraseFromParent(); 461 } else { 462 assert( 463 (getNumSuccessors() == 0 || isa<BranchInst>(IRBB->getTerminator())) && 464 "other blocks must be terminated by a branch"); 465 } 466 467 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 468 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 469 BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB]; 470 assert(PredBB && "Predecessor basic-block not found building successor."); 471 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 472 473 auto *PredBBTerminator = PredBB->getTerminator(); 474 auto *TermBr = cast<BranchInst>(PredBBTerminator); 475 // Set each forward successor here when it is created, excluding 476 // backedges. A backward successor is set when the branch is created. 477 const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 478 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 479 assert((!TermBr->getSuccessor(idx) || TermBr->getSuccessor(idx) == IRBB) && 480 "Trying to reset an existing successor block."); 481 TermBr->setSuccessor(idx, IRBB); 482 State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}}); 483 } 484 } 485 486 void VPBasicBlock::execute(VPTransformState *State) { 487 bool Replica = bool(State->Lane); 488 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 489 VPBlockBase *SingleHPred = nullptr; 490 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 491 492 auto IsLoopRegion = [](VPBlockBase *BB) { 493 auto *R = dyn_cast<VPRegionBlock>(BB); 494 return R && !R->isReplicator(); 495 }; 496 497 // 1. Create an IR basic block. 498 if (PrevVPBB && /* A */ 499 !((SingleHPred = getSingleHierarchicalPredecessor()) && 500 SingleHPred->getExitingBasicBlock() == PrevVPBB && 501 PrevVPBB->getSingleHierarchicalSuccessor() && 502 (SingleHPred->getParent() == getEnclosingLoopRegion() && 503 !IsLoopRegion(SingleHPred))) && /* B */ 504 !(Replica && getPredecessors().empty())) { /* C */ 505 // The last IR basic block is reused, as an optimization, in three cases: 506 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 507 // B. when the current VPBB has a single (hierarchical) predecessor which 508 // is PrevVPBB and the latter has a single (hierarchical) successor which 509 // both are in the same non-replicator region; and 510 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 511 // is the exiting VPBB of this region from a previous instance, or the 512 // predecessor of this region. 513 514 NewBB = createEmptyBasicBlock(State->CFG); 515 State->Builder.SetInsertPoint(NewBB); 516 // Temporarily terminate with unreachable until CFG is rewired. 517 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 518 // Register NewBB in its loop. In innermost loops its the same for all 519 // BB's. 520 if (State->CurrentVectorLoop) 521 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 522 State->Builder.SetInsertPoint(Terminator); 523 State->CFG.PrevBB = NewBB; 524 } 525 526 // 2. Fill the IR basic block with IR instructions. 527 executeRecipes(State, NewBB); 528 } 529 530 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 531 for (VPRecipeBase &R : Recipes) { 532 for (auto *Def : R.definedValues()) 533 Def->replaceAllUsesWith(NewValue); 534 535 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 536 R.setOperand(I, NewValue); 537 } 538 } 539 540 void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) { 541 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 542 << " in BB:" << BB->getName() << '\n'); 543 544 State->CFG.VPBB2IRBB[this] = BB; 545 State->CFG.PrevVPBB = this; 546 547 for (VPRecipeBase &Recipe : Recipes) 548 Recipe.execute(*State); 549 550 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB); 551 } 552 553 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 554 assert((SplitAt == end() || SplitAt->getParent() == this) && 555 "can only split at a position in the same block"); 556 557 SmallVector<VPBlockBase *, 2> Succs(successors()); 558 // First, disconnect the current block from its successors. 559 for (VPBlockBase *Succ : Succs) 560 VPBlockUtils::disconnectBlocks(this, Succ); 561 562 // Create new empty block after the block to split. 563 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 564 VPBlockUtils::insertBlockAfter(SplitBlock, this); 565 566 // Add successors for block to split to new block. 567 for (VPBlockBase *Succ : Succs) 568 VPBlockUtils::connectBlocks(SplitBlock, Succ); 569 570 // Finally, move the recipes starting at SplitAt to new block. 571 for (VPRecipeBase &ToMove : 572 make_early_inc_range(make_range(SplitAt, this->end()))) 573 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 574 575 return SplitBlock; 576 } 577 578 /// Return the enclosing loop region for region \p P. The templated version is 579 /// used to support both const and non-const block arguments. 580 template <typename T> static T *getEnclosingLoopRegionForRegion(T *P) { 581 if (P && P->isReplicator()) { 582 P = P->getParent(); 583 assert(!cast<VPRegionBlock>(P)->isReplicator() && 584 "unexpected nested replicate regions"); 585 } 586 return P; 587 } 588 589 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 590 return getEnclosingLoopRegionForRegion(getParent()); 591 } 592 593 const VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() const { 594 return getEnclosingLoopRegionForRegion(getParent()); 595 } 596 597 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 598 if (VPBB->empty()) { 599 assert( 600 VPBB->getNumSuccessors() < 2 && 601 "block with multiple successors doesn't have a recipe as terminator"); 602 return false; 603 } 604 605 const VPRecipeBase *R = &VPBB->back(); 606 bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) || 607 match(R, m_BranchOnCond(m_VPValue())) || 608 match(R, m_BranchOnCount(m_VPValue(), m_VPValue())); 609 (void)IsCondBranch; 610 611 if (VPBB->getNumSuccessors() >= 2 || 612 (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) { 613 assert(IsCondBranch && "block with multiple successors not terminated by " 614 "conditional branch recipe"); 615 616 return true; 617 } 618 619 assert( 620 !IsCondBranch && 621 "block with 0 or 1 successors terminated by conditional branch recipe"); 622 return false; 623 } 624 625 VPRecipeBase *VPBasicBlock::getTerminator() { 626 if (hasConditionalTerminator(this)) 627 return &back(); 628 return nullptr; 629 } 630 631 const VPRecipeBase *VPBasicBlock::getTerminator() const { 632 if (hasConditionalTerminator(this)) 633 return &back(); 634 return nullptr; 635 } 636 637 bool VPBasicBlock::isExiting() const { 638 return getParent() && getParent()->getExitingBasicBlock() == this; 639 } 640 641 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 642 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 643 if (getSuccessors().empty()) { 644 O << Indent << "No successors\n"; 645 } else { 646 O << Indent << "Successor(s): "; 647 ListSeparator LS; 648 for (auto *Succ : getSuccessors()) 649 O << LS << Succ->getName(); 650 O << '\n'; 651 } 652 } 653 654 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 655 VPSlotTracker &SlotTracker) const { 656 O << Indent << getName() << ":\n"; 657 658 auto RecipeIndent = Indent + " "; 659 for (const VPRecipeBase &Recipe : *this) { 660 Recipe.print(O, RecipeIndent, SlotTracker); 661 O << '\n'; 662 } 663 664 printSuccessors(O, Indent); 665 } 666 #endif 667 668 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry); 669 670 // Clone the CFG for all nodes reachable from \p Entry, this includes cloning 671 // the blocks and their recipes. Operands of cloned recipes will NOT be updated. 672 // Remapping of operands must be done separately. Returns a pair with the new 673 // entry and exiting blocks of the cloned region. If \p Entry isn't part of a 674 // region, return nullptr for the exiting block. 675 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) { 676 DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks; 677 VPBlockBase *Exiting = nullptr; 678 bool InRegion = Entry->getParent(); 679 // First, clone blocks reachable from Entry. 680 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) { 681 VPBlockBase *NewBB = BB->clone(); 682 Old2NewVPBlocks[BB] = NewBB; 683 if (InRegion && BB->getNumSuccessors() == 0) { 684 assert(!Exiting && "Multiple exiting blocks?"); 685 Exiting = BB; 686 } 687 } 688 assert((!InRegion || Exiting) && "regions must have a single exiting block"); 689 690 // Second, update the predecessors & successors of the cloned blocks. 691 for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) { 692 VPBlockBase *NewBB = Old2NewVPBlocks[BB]; 693 SmallVector<VPBlockBase *> NewPreds; 694 for (VPBlockBase *Pred : BB->getPredecessors()) { 695 NewPreds.push_back(Old2NewVPBlocks[Pred]); 696 } 697 NewBB->setPredecessors(NewPreds); 698 SmallVector<VPBlockBase *> NewSuccs; 699 for (VPBlockBase *Succ : BB->successors()) { 700 NewSuccs.push_back(Old2NewVPBlocks[Succ]); 701 } 702 NewBB->setSuccessors(NewSuccs); 703 } 704 705 #if !defined(NDEBUG) 706 // Verify that the order of predecessors and successors matches in the cloned 707 // version. 708 for (const auto &[OldBB, NewBB] : 709 zip(vp_depth_first_shallow(Entry), 710 vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) { 711 for (const auto &[OldPred, NewPred] : 712 zip(OldBB->getPredecessors(), NewBB->getPredecessors())) 713 assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors"); 714 715 for (const auto &[OldSucc, NewSucc] : 716 zip(OldBB->successors(), NewBB->successors())) 717 assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors"); 718 } 719 #endif 720 721 return std::make_pair(Old2NewVPBlocks[Entry], 722 Exiting ? Old2NewVPBlocks[Exiting] : nullptr); 723 } 724 725 VPRegionBlock *VPRegionBlock::clone() { 726 const auto &[NewEntry, NewExiting] = cloneFrom(getEntry()); 727 auto *NewRegion = 728 new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator()); 729 for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry)) 730 Block->setParent(NewRegion); 731 return NewRegion; 732 } 733 734 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 735 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 736 // Drop all references in VPBasicBlocks and replace all uses with 737 // DummyValue. 738 Block->dropAllReferences(NewValue); 739 } 740 741 void VPRegionBlock::execute(VPTransformState *State) { 742 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 743 RPOT(Entry); 744 745 if (!isReplicator()) { 746 // Create and register the new vector loop. 747 Loop *PrevLoop = State->CurrentVectorLoop; 748 State->CurrentVectorLoop = State->LI->AllocateLoop(); 749 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 750 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 751 752 // Insert the new loop into the loop nest and register the new basic blocks 753 // before calling any utilities such as SCEV that require valid LoopInfo. 754 if (ParentLoop) 755 ParentLoop->addChildLoop(State->CurrentVectorLoop); 756 else 757 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 758 759 // Visit the VPBlocks connected to "this", starting from it. 760 for (VPBlockBase *Block : RPOT) { 761 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 762 Block->execute(State); 763 } 764 765 State->CurrentVectorLoop = PrevLoop; 766 return; 767 } 768 769 assert(!State->Lane && "Replicating a Region with non-null instance."); 770 771 // Enter replicating mode. 772 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 773 State->Lane = VPLane(0); 774 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 775 ++Lane) { 776 State->Lane = VPLane(Lane, VPLane::Kind::First); 777 // Visit the VPBlocks connected to \p this, starting from it. 778 for (VPBlockBase *Block : RPOT) { 779 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 780 Block->execute(State); 781 } 782 } 783 784 // Exit replicating mode. 785 State->Lane.reset(); 786 } 787 788 InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) { 789 InstructionCost Cost = 0; 790 for (VPRecipeBase &R : Recipes) 791 Cost += R.cost(VF, Ctx); 792 return Cost; 793 } 794 795 InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) { 796 if (!isReplicator()) { 797 InstructionCost Cost = 0; 798 for (VPBlockBase *Block : vp_depth_first_shallow(getEntry())) 799 Cost += Block->cost(VF, Ctx); 800 InstructionCost BackedgeCost = 801 ForceTargetInstructionCost.getNumOccurrences() 802 ? InstructionCost(ForceTargetInstructionCost.getNumOccurrences()) 803 : Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput); 804 LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF 805 << ": vector loop backedge\n"); 806 Cost += BackedgeCost; 807 return Cost; 808 } 809 810 // Compute the cost of a replicate region. Replicating isn't supported for 811 // scalable vectors, return an invalid cost for them. 812 // TODO: Discard scalable VPlans with replicate recipes earlier after 813 // construction. 814 if (VF.isScalable()) 815 return InstructionCost::getInvalid(); 816 817 // First compute the cost of the conditionally executed recipes, followed by 818 // account for the branching cost, except if the mask is a header mask or 819 // uniform condition. 820 using namespace llvm::VPlanPatternMatch; 821 VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]); 822 InstructionCost ThenCost = Then->cost(VF, Ctx); 823 824 // For the scalar case, we may not always execute the original predicated 825 // block, Thus, scale the block's cost by the probability of executing it. 826 if (VF.isScalar()) 827 return ThenCost / getReciprocalPredBlockProb(); 828 829 return ThenCost; 830 } 831 832 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 833 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 834 VPSlotTracker &SlotTracker) const { 835 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 836 auto NewIndent = Indent + " "; 837 for (auto *BlockBase : vp_depth_first_shallow(Entry)) { 838 O << '\n'; 839 BlockBase->print(O, NewIndent, SlotTracker); 840 } 841 O << Indent << "}\n"; 842 843 printSuccessors(O, Indent); 844 } 845 #endif 846 847 VPlan::~VPlan() { 848 if (Entry) { 849 VPValue DummyValue; 850 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 851 Block->dropAllReferences(&DummyValue); 852 853 VPBlockBase::deleteCFG(Entry); 854 855 Preheader->dropAllReferences(&DummyValue); 856 delete Preheader; 857 } 858 for (VPValue *VPV : VPLiveInsToFree) 859 delete VPV; 860 if (BackedgeTakenCount) 861 delete BackedgeTakenCount; 862 } 863 864 VPIRBasicBlock *VPIRBasicBlock::fromBasicBlock(BasicBlock *IRBB) { 865 auto *VPIRBB = new VPIRBasicBlock(IRBB); 866 for (Instruction &I : 867 make_range(IRBB->begin(), IRBB->getTerminator()->getIterator())) 868 VPIRBB->appendRecipe(new VPIRInstruction(I)); 869 return VPIRBB; 870 } 871 872 VPlanPtr VPlan::createInitialVPlan(Type *InductionTy, 873 PredicatedScalarEvolution &PSE, 874 bool RequiresScalarEpilogueCheck, 875 bool TailFolded, Loop *TheLoop) { 876 VPIRBasicBlock *Entry = 877 VPIRBasicBlock::fromBasicBlock(TheLoop->getLoopPreheader()); 878 VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph"); 879 VPIRBasicBlock *ScalarHeader = 880 VPIRBasicBlock::fromBasicBlock(TheLoop->getHeader()); 881 auto Plan = std::make_unique<VPlan>(Entry, VecPreheader, ScalarHeader); 882 883 // Create SCEV and VPValue for the trip count. 884 885 // Currently only loops with countable exits are vectorized, but calling 886 // getSymbolicMaxBackedgeTakenCount allows enablement work for loops with 887 // uncountable exits whilst also ensuring the symbolic maximum and known 888 // back-edge taken count remain identical for loops with countable exits. 889 const SCEV *BackedgeTakenCountSCEV = PSE.getSymbolicMaxBackedgeTakenCount(); 890 assert((!isa<SCEVCouldNotCompute>(BackedgeTakenCountSCEV) && 891 BackedgeTakenCountSCEV == PSE.getBackedgeTakenCount()) && 892 "Invalid loop count"); 893 ScalarEvolution &SE = *PSE.getSE(); 894 const SCEV *TripCount = SE.getTripCountFromExitCount(BackedgeTakenCountSCEV, 895 InductionTy, TheLoop); 896 Plan->TripCount = 897 vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE); 898 899 // Create VPRegionBlock, with empty header and latch blocks, to be filled 900 // during processing later. 901 VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body"); 902 VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch"); 903 VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB); 904 auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop", 905 false /*isReplicator*/); 906 907 VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader); 908 VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block"); 909 VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion); 910 911 VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph"); 912 VPBlockUtils::connectBlocks(ScalarPH, ScalarHeader); 913 if (!RequiresScalarEpilogueCheck) { 914 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH); 915 return Plan; 916 } 917 918 // If needed, add a check in the middle block to see if we have completed 919 // all of the iterations in the first vector loop. Three cases: 920 // 1) If (N - N%VF) == N, then we *don't* need to run the remainder. 921 // Thus if tail is to be folded, we know we don't need to run the 922 // remainder and we can set the condition to true. 923 // 2) If we require a scalar epilogue, there is no conditional branch as 924 // we unconditionally branch to the scalar preheader. Do nothing. 925 // 3) Otherwise, construct a runtime check. 926 BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock(); 927 auto *VPExitBlock = VPIRBasicBlock::fromBasicBlock(IRExitBlock); 928 // The connection order corresponds to the operands of the conditional branch. 929 VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB); 930 VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH); 931 932 auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator(); 933 // Here we use the same DebugLoc as the scalar loop latch terminator instead 934 // of the corresponding compare because they may have ended up with 935 // different line numbers and we want to avoid awkward line stepping while 936 // debugging. Eg. if the compare has got a line number inside the loop. 937 VPBuilder Builder(MiddleVPBB); 938 VPValue *Cmp = 939 TailFolded 940 ? Plan->getOrAddLiveIn(ConstantInt::getTrue( 941 IntegerType::getInt1Ty(TripCount->getType()->getContext()))) 942 : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(), 943 &Plan->getVectorTripCount(), 944 ScalarLatchTerm->getDebugLoc(), "cmp.n"); 945 Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp}, 946 ScalarLatchTerm->getDebugLoc()); 947 return Plan; 948 } 949 950 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 951 Value *CanonicalIVStartValue, 952 VPTransformState &State) { 953 Type *TCTy = TripCountV->getType(); 954 // Check if the backedge taken count is needed, and if so build it. 955 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 956 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 957 auto *TCMO = Builder.CreateSub(TripCountV, ConstantInt::get(TCTy, 1), 958 "trip.count.minus.1"); 959 BackedgeTakenCount->setUnderlyingValue(TCMO); 960 } 961 962 VectorTripCount.setUnderlyingValue(VectorTripCountV); 963 964 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 965 // FIXME: Model VF * UF computation completely in VPlan. 966 assert(VFxUF.getNumUsers() && "VFxUF expected to always have users"); 967 unsigned UF = getUF(); 968 if (VF.getNumUsers()) { 969 Value *RuntimeVF = getRuntimeVF(Builder, TCTy, State.VF); 970 VF.setUnderlyingValue(RuntimeVF); 971 VFxUF.setUnderlyingValue( 972 UF > 1 ? Builder.CreateMul(RuntimeVF, ConstantInt::get(TCTy, UF)) 973 : RuntimeVF); 974 } else { 975 VFxUF.setUnderlyingValue(createStepForVF(Builder, TCTy, State.VF, UF)); 976 } 977 978 // When vectorizing the epilogue loop, the canonical induction start value 979 // needs to be changed from zero to the value after the main vector loop. 980 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 981 if (CanonicalIVStartValue) { 982 VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue); 983 auto *IV = getCanonicalIV(); 984 assert(all_of(IV->users(), 985 [](const VPUser *U) { 986 return isa<VPScalarIVStepsRecipe>(U) || 987 isa<VPScalarCastRecipe>(U) || 988 isa<VPDerivedIVRecipe>(U) || 989 cast<VPInstruction>(U)->getOpcode() == 990 Instruction::Add; 991 }) && 992 "the canonical IV should only be used by its increment or " 993 "ScalarIVSteps when resetting the start value"); 994 IV->setOperand(0, VPV); 995 } 996 } 997 998 /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p 999 /// VPBB are moved to the end of the newly created VPIRBasicBlock. VPBB must 1000 /// have a single predecessor, which is rewired to the new VPIRBasicBlock. All 1001 /// successors of VPBB, if any, are rewired to the new VPIRBasicBlock. 1002 static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) { 1003 VPIRBasicBlock *IRVPBB = VPIRBasicBlock::fromBasicBlock(IRBB); 1004 for (auto &R : make_early_inc_range(*VPBB)) { 1005 assert(!R.isPhi() && "Tried to move phi recipe to end of block"); 1006 R.moveBefore(*IRVPBB, IRVPBB->end()); 1007 } 1008 1009 VPBlockUtils::reassociateBlocks(VPBB, IRVPBB); 1010 1011 delete VPBB; 1012 } 1013 1014 /// Generate the code inside the preheader and body of the vectorized loop. 1015 /// Assumes a single pre-header basic-block was created for this. Introduce 1016 /// additional basic-blocks as needed, and fill them all. 1017 void VPlan::execute(VPTransformState *State) { 1018 // Initialize CFG state. 1019 State->CFG.PrevVPBB = nullptr; 1020 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 1021 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 1022 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 1023 1024 // Disconnect VectorPreHeader from ExitBB in both the CFG and DT. 1025 cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr); 1026 State->CFG.DTU.applyUpdates( 1027 {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}}); 1028 1029 // Replace regular VPBB's for the middle and scalar preheader blocks with 1030 // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during 1031 // skeleton creation, so we can only create the VPIRBasicBlocks now during 1032 // VPlan execution rather than earlier during VPlan construction. 1033 BasicBlock *MiddleBB = State->CFG.ExitBB; 1034 VPBasicBlock *MiddleVPBB = getMiddleBlock(); 1035 BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor(); 1036 replaceVPBBWithIRVPBB(getScalarPreheader(), ScalarPh); 1037 replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB); 1038 1039 // Disconnect the middle block from its single successor (the scalar loop 1040 // header) in both the CFG and DT. The branch will be recreated during VPlan 1041 // execution. 1042 auto *BrInst = new UnreachableInst(MiddleBB->getContext()); 1043 BrInst->insertBefore(MiddleBB->getTerminator()); 1044 MiddleBB->getTerminator()->eraseFromParent(); 1045 State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}}); 1046 // Disconnect scalar preheader and scalar header, as the dominator tree edge 1047 // will be updated as part of VPlan execution. This allows keeping the DTU 1048 // logic generic during VPlan execution. 1049 State->CFG.DTU.applyUpdates( 1050 {{DominatorTree::Delete, ScalarPh, ScalarPh->getSingleSuccessor()}}); 1051 1052 // Generate code in the loop pre-header and body. 1053 for (VPBlockBase *Block : vp_depth_first_shallow(Entry)) 1054 Block->execute(State); 1055 1056 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 1057 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 1058 1059 // Fix the latch value of canonical, reduction and first-order recurrences 1060 // phis in the vector loop. 1061 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 1062 for (VPRecipeBase &R : Header->phis()) { 1063 // Skip phi-like recipes that generate their backedege values themselves. 1064 if (isa<VPWidenPHIRecipe>(&R)) 1065 continue; 1066 1067 if (isa<VPWidenPointerInductionRecipe>(&R) || 1068 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 1069 PHINode *Phi = nullptr; 1070 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 1071 Phi = cast<PHINode>(State->get(R.getVPSingleValue())); 1072 } else { 1073 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 1074 assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) && 1075 "recipe generating only scalars should have been replaced"); 1076 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi)); 1077 Phi = cast<PHINode>(GEP->getPointerOperand()); 1078 } 1079 1080 Phi->setIncomingBlock(1, VectorLatchBB); 1081 1082 // Move the last step to the end of the latch block. This ensures 1083 // consistent placement of all induction updates. 1084 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 1085 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 1086 1087 // Use the steps for the last part as backedge value for the induction. 1088 if (auto *IV = dyn_cast<VPWidenIntOrFpInductionRecipe>(&R)) 1089 Inc->setOperand(0, State->get(IV->getLastUnrolledPartOperand())); 1090 continue; 1091 } 1092 1093 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 1094 bool NeedsScalar = 1095 isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) || 1096 (isa<VPReductionPHIRecipe>(PhiR) && 1097 cast<VPReductionPHIRecipe>(PhiR)->isInLoop()); 1098 Value *Phi = State->get(PhiR, NeedsScalar); 1099 Value *Val = State->get(PhiR->getBackedgeValue(), NeedsScalar); 1100 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 1101 } 1102 1103 State->CFG.DTU.flush(); 1104 assert(State->CFG.DTU.getDomTree().verify( 1105 DominatorTree::VerificationLevel::Fast) && 1106 "DT not preserved correctly"); 1107 } 1108 1109 InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) { 1110 // For now only return the cost of the vector loop region, ignoring any other 1111 // blocks, like the preheader or middle blocks. 1112 return getVectorLoopRegion()->cost(VF, Ctx); 1113 } 1114 1115 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1116 void VPlan::printLiveIns(raw_ostream &O) const { 1117 VPSlotTracker SlotTracker(this); 1118 1119 if (VF.getNumUsers() > 0) { 1120 O << "\nLive-in "; 1121 VF.printAsOperand(O, SlotTracker); 1122 O << " = VF"; 1123 } 1124 1125 if (VFxUF.getNumUsers() > 0) { 1126 O << "\nLive-in "; 1127 VFxUF.printAsOperand(O, SlotTracker); 1128 O << " = VF * UF"; 1129 } 1130 1131 if (VectorTripCount.getNumUsers() > 0) { 1132 O << "\nLive-in "; 1133 VectorTripCount.printAsOperand(O, SlotTracker); 1134 O << " = vector-trip-count"; 1135 } 1136 1137 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 1138 O << "\nLive-in "; 1139 BackedgeTakenCount->printAsOperand(O, SlotTracker); 1140 O << " = backedge-taken count"; 1141 } 1142 1143 O << "\n"; 1144 if (TripCount->isLiveIn()) 1145 O << "Live-in "; 1146 TripCount->printAsOperand(O, SlotTracker); 1147 O << " = original trip-count"; 1148 O << "\n"; 1149 } 1150 1151 LLVM_DUMP_METHOD 1152 void VPlan::print(raw_ostream &O) const { 1153 VPSlotTracker SlotTracker(this); 1154 1155 O << "VPlan '" << getName() << "' {"; 1156 1157 printLiveIns(O); 1158 1159 if (!getPreheader()->empty()) { 1160 O << "\n"; 1161 getPreheader()->print(O, "", SlotTracker); 1162 } 1163 1164 for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) { 1165 O << '\n'; 1166 Block->print(O, "", SlotTracker); 1167 } 1168 1169 O << "}\n"; 1170 } 1171 1172 std::string VPlan::getName() const { 1173 std::string Out; 1174 raw_string_ostream RSO(Out); 1175 RSO << Name << " for "; 1176 if (!VFs.empty()) { 1177 RSO << "VF={" << VFs[0]; 1178 for (ElementCount VF : drop_begin(VFs)) 1179 RSO << "," << VF; 1180 RSO << "},"; 1181 } 1182 1183 if (UFs.empty()) { 1184 RSO << "UF>=1"; 1185 } else { 1186 RSO << "UF={" << UFs[0]; 1187 for (unsigned UF : drop_begin(UFs)) 1188 RSO << "," << UF; 1189 RSO << "}"; 1190 } 1191 1192 return Out; 1193 } 1194 1195 LLVM_DUMP_METHOD 1196 void VPlan::printDOT(raw_ostream &O) const { 1197 VPlanPrinter Printer(O, *this); 1198 Printer.dump(); 1199 } 1200 1201 LLVM_DUMP_METHOD 1202 void VPlan::dump() const { print(dbgs()); } 1203 #endif 1204 1205 static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry, 1206 DenseMap<VPValue *, VPValue *> &Old2NewVPValues) { 1207 // Update the operands of all cloned recipes starting at NewEntry. This 1208 // traverses all reachable blocks. This is done in two steps, to handle cycles 1209 // in PHI recipes. 1210 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> 1211 OldDeepRPOT(Entry); 1212 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>> 1213 NewDeepRPOT(NewEntry); 1214 // First, collect all mappings from old to new VPValues defined by cloned 1215 // recipes. 1216 for (const auto &[OldBB, NewBB] : 1217 zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT), 1218 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) { 1219 assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() && 1220 "blocks must have the same number of recipes"); 1221 for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) { 1222 assert(OldR.getNumOperands() == NewR.getNumOperands() && 1223 "recipes must have the same number of operands"); 1224 assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() && 1225 "recipes must define the same number of operands"); 1226 for (const auto &[OldV, NewV] : 1227 zip(OldR.definedValues(), NewR.definedValues())) 1228 Old2NewVPValues[OldV] = NewV; 1229 } 1230 } 1231 1232 // Update all operands to use cloned VPValues. 1233 for (VPBasicBlock *NewBB : 1234 VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) { 1235 for (VPRecipeBase &NewR : *NewBB) 1236 for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) { 1237 VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I)); 1238 NewR.setOperand(I, NewOp); 1239 } 1240 } 1241 } 1242 1243 VPlan *VPlan::duplicate() { 1244 // Clone blocks. 1245 VPBasicBlock *NewPreheader = Preheader->clone(); 1246 const auto &[NewEntry, __] = cloneFrom(Entry); 1247 1248 BasicBlock *ScalarHeaderIRBB = getScalarHeader()->getIRBasicBlock(); 1249 VPIRBasicBlock *NewScalarHeader = cast<VPIRBasicBlock>(*find_if( 1250 vp_depth_first_shallow(NewEntry), [ScalarHeaderIRBB](VPBlockBase *VPB) { 1251 auto *VPIRBB = dyn_cast<VPIRBasicBlock>(VPB); 1252 return VPIRBB && VPIRBB->getIRBasicBlock() == ScalarHeaderIRBB; 1253 })); 1254 // Create VPlan, clone live-ins and remap operands in the cloned blocks. 1255 auto *NewPlan = 1256 new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry), NewScalarHeader); 1257 DenseMap<VPValue *, VPValue *> Old2NewVPValues; 1258 for (VPValue *OldLiveIn : VPLiveInsToFree) { 1259 Old2NewVPValues[OldLiveIn] = 1260 NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue()); 1261 } 1262 Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount; 1263 Old2NewVPValues[&VF] = &NewPlan->VF; 1264 Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF; 1265 if (BackedgeTakenCount) { 1266 NewPlan->BackedgeTakenCount = new VPValue(); 1267 Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount; 1268 } 1269 assert(TripCount && "trip count must be set"); 1270 if (TripCount->isLiveIn()) 1271 Old2NewVPValues[TripCount] = 1272 NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue()); 1273 // else NewTripCount will be created and inserted into Old2NewVPValues when 1274 // TripCount is cloned. In any case NewPlan->TripCount is updated below. 1275 1276 remapOperands(Preheader, NewPreheader, Old2NewVPValues); 1277 remapOperands(Entry, NewEntry, Old2NewVPValues); 1278 1279 // Initialize remaining fields of cloned VPlan. 1280 NewPlan->VFs = VFs; 1281 NewPlan->UFs = UFs; 1282 // TODO: Adjust names. 1283 NewPlan->Name = Name; 1284 assert(Old2NewVPValues.contains(TripCount) && 1285 "TripCount must have been added to Old2NewVPValues"); 1286 NewPlan->TripCount = Old2NewVPValues[TripCount]; 1287 return NewPlan; 1288 } 1289 1290 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1291 1292 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 1293 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 1294 Twine(getOrCreateBID(Block)); 1295 } 1296 1297 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 1298 const std::string &Name = Block->getName(); 1299 if (!Name.empty()) 1300 return Name; 1301 return "VPB" + Twine(getOrCreateBID(Block)); 1302 } 1303 1304 void VPlanPrinter::dump() { 1305 Depth = 1; 1306 bumpIndent(0); 1307 OS << "digraph VPlan {\n"; 1308 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 1309 if (!Plan.getName().empty()) 1310 OS << "\\n" << DOT::EscapeString(Plan.getName()); 1311 1312 { 1313 // Print live-ins. 1314 std::string Str; 1315 raw_string_ostream SS(Str); 1316 Plan.printLiveIns(SS); 1317 SmallVector<StringRef, 0> Lines; 1318 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1319 for (auto Line : Lines) 1320 OS << DOT::EscapeString(Line.str()) << "\\n"; 1321 } 1322 1323 OS << "\"]\n"; 1324 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1325 OS << "edge [fontname=Courier, fontsize=30]\n"; 1326 OS << "compound=true\n"; 1327 1328 dumpBlock(Plan.getPreheader()); 1329 1330 for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry())) 1331 dumpBlock(Block); 1332 1333 OS << "}\n"; 1334 } 1335 1336 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1337 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1338 dumpBasicBlock(BasicBlock); 1339 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1340 dumpRegion(Region); 1341 else 1342 llvm_unreachable("Unsupported kind of VPBlock."); 1343 } 1344 1345 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1346 bool Hidden, const Twine &Label) { 1347 // Due to "dot" we print an edge between two regions as an edge between the 1348 // exiting basic block and the entry basic of the respective regions. 1349 const VPBlockBase *Tail = From->getExitingBasicBlock(); 1350 const VPBlockBase *Head = To->getEntryBasicBlock(); 1351 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1352 OS << " [ label=\"" << Label << '\"'; 1353 if (Tail != From) 1354 OS << " ltail=" << getUID(From); 1355 if (Head != To) 1356 OS << " lhead=" << getUID(To); 1357 if (Hidden) 1358 OS << "; splines=none"; 1359 OS << "]\n"; 1360 } 1361 1362 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1363 auto &Successors = Block->getSuccessors(); 1364 if (Successors.size() == 1) 1365 drawEdge(Block, Successors.front(), false, ""); 1366 else if (Successors.size() == 2) { 1367 drawEdge(Block, Successors.front(), false, "T"); 1368 drawEdge(Block, Successors.back(), false, "F"); 1369 } else { 1370 unsigned SuccessorNumber = 0; 1371 for (auto *Successor : Successors) 1372 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1373 } 1374 } 1375 1376 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1377 // Implement dot-formatted dump by performing plain-text dump into the 1378 // temporary storage followed by some post-processing. 1379 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1380 bumpIndent(1); 1381 std::string Str; 1382 raw_string_ostream SS(Str); 1383 // Use no indentation as we need to wrap the lines into quotes ourselves. 1384 BasicBlock->print(SS, "", SlotTracker); 1385 1386 // We need to process each line of the output separately, so split 1387 // single-string plain-text dump. 1388 SmallVector<StringRef, 0> Lines; 1389 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1390 1391 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1392 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1393 }; 1394 1395 // Don't need the "+" after the last line. 1396 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1397 EmitLine(Line, " +\n"); 1398 EmitLine(Lines.back(), "\n"); 1399 1400 bumpIndent(-1); 1401 OS << Indent << "]\n"; 1402 1403 dumpEdges(BasicBlock); 1404 } 1405 1406 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1407 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1408 bumpIndent(1); 1409 OS << Indent << "fontname=Courier\n" 1410 << Indent << "label=\"" 1411 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1412 << DOT::EscapeString(Region->getName()) << "\"\n"; 1413 // Dump the blocks of the region. 1414 assert(Region->getEntry() && "Region contains no inner blocks."); 1415 for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry())) 1416 dumpBlock(Block); 1417 bumpIndent(-1); 1418 OS << Indent << "}\n"; 1419 dumpEdges(Region); 1420 } 1421 1422 void VPlanIngredient::print(raw_ostream &O) const { 1423 if (auto *Inst = dyn_cast<Instruction>(V)) { 1424 if (!Inst->getType()->isVoidTy()) { 1425 Inst->printAsOperand(O, false); 1426 O << " = "; 1427 } 1428 O << Inst->getOpcodeName() << " "; 1429 unsigned E = Inst->getNumOperands(); 1430 if (E > 0) { 1431 Inst->getOperand(0)->printAsOperand(O, false); 1432 for (unsigned I = 1; I < E; ++I) 1433 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1434 } 1435 } else // !Inst 1436 V->printAsOperand(O, false); 1437 } 1438 1439 #endif 1440 1441 bool VPValue::isDefinedOutsideLoopRegions() const { 1442 return !hasDefiningRecipe() || 1443 !getDefiningRecipe()->getParent()->getEnclosingLoopRegion(); 1444 } 1445 1446 void VPValue::replaceAllUsesWith(VPValue *New) { 1447 replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; }); 1448 } 1449 1450 void VPValue::replaceUsesWithIf( 1451 VPValue *New, 1452 llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) { 1453 // Note that this early exit is required for correctness; the implementation 1454 // below relies on the number of users for this VPValue to decrease, which 1455 // isn't the case if this == New. 1456 if (this == New) 1457 return; 1458 1459 for (unsigned J = 0; J < getNumUsers();) { 1460 VPUser *User = Users[J]; 1461 bool RemovedUser = false; 1462 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) { 1463 if (User->getOperand(I) != this || !ShouldReplace(*User, I)) 1464 continue; 1465 1466 RemovedUser = true; 1467 User->setOperand(I, New); 1468 } 1469 // If a user got removed after updating the current user, the next user to 1470 // update will be moved to the current position, so we only need to 1471 // increment the index if the number of users did not change. 1472 if (!RemovedUser) 1473 J++; 1474 } 1475 } 1476 1477 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1478 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1479 OS << Tracker.getOrCreateName(this); 1480 } 1481 1482 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1483 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1484 Op->printAsOperand(O, SlotTracker); 1485 }); 1486 } 1487 #endif 1488 1489 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1490 Old2NewTy &Old2New, 1491 InterleavedAccessInfo &IAI) { 1492 ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>> 1493 RPOT(Region->getEntry()); 1494 for (VPBlockBase *Base : RPOT) { 1495 visitBlock(Base, Old2New, IAI); 1496 } 1497 } 1498 1499 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1500 InterleavedAccessInfo &IAI) { 1501 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1502 for (VPRecipeBase &VPI : *VPBB) { 1503 if (isa<VPWidenPHIRecipe>(&VPI)) 1504 continue; 1505 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1506 auto *VPInst = cast<VPInstruction>(&VPI); 1507 1508 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1509 if (!Inst) 1510 continue; 1511 auto *IG = IAI.getInterleaveGroup(Inst); 1512 if (!IG) 1513 continue; 1514 1515 auto NewIGIter = Old2New.find(IG); 1516 if (NewIGIter == Old2New.end()) 1517 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1518 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1519 1520 if (Inst == IG->getInsertPos()) 1521 Old2New[IG]->setInsertPos(VPInst); 1522 1523 InterleaveGroupMap[VPInst] = Old2New[IG]; 1524 InterleaveGroupMap[VPInst]->insertMember( 1525 VPInst, IG->getIndex(Inst), 1526 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1527 : IG->getFactor())); 1528 } 1529 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1530 visitRegion(Region, Old2New, IAI); 1531 else 1532 llvm_unreachable("Unsupported kind of VPBlock."); 1533 } 1534 1535 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1536 InterleavedAccessInfo &IAI) { 1537 Old2NewTy Old2New; 1538 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1539 } 1540 1541 void VPSlotTracker::assignName(const VPValue *V) { 1542 assert(!VPValue2Name.contains(V) && "VPValue already has a name!"); 1543 auto *UV = V->getUnderlyingValue(); 1544 auto *VPI = dyn_cast_or_null<VPInstruction>(V->getDefiningRecipe()); 1545 if (!UV && !(VPI && !VPI->getName().empty())) { 1546 VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str(); 1547 NextSlot++; 1548 return; 1549 } 1550 1551 // Use the name of the underlying Value, wrapped in "ir<>", and versioned by 1552 // appending ".Number" to the name if there are multiple uses. 1553 std::string Name; 1554 if (UV) { 1555 raw_string_ostream S(Name); 1556 UV->printAsOperand(S, false); 1557 } else 1558 Name = VPI->getName(); 1559 1560 assert(!Name.empty() && "Name cannot be empty."); 1561 StringRef Prefix = UV ? "ir<" : "vp<%"; 1562 std::string BaseName = (Twine(Prefix) + Name + Twine(">")).str(); 1563 1564 // First assign the base name for V. 1565 const auto &[A, _] = VPValue2Name.insert({V, BaseName}); 1566 // Integer or FP constants with different types will result in he same string 1567 // due to stripping types. 1568 if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV)) 1569 return; 1570 1571 // If it is already used by C > 0 other VPValues, increase the version counter 1572 // C and use it for V. 1573 const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0}); 1574 if (!UseInserted) { 1575 C->second++; 1576 A->second = (BaseName + Twine(".") + Twine(C->second)).str(); 1577 } 1578 } 1579 1580 void VPSlotTracker::assignNames(const VPlan &Plan) { 1581 if (Plan.VF.getNumUsers() > 0) 1582 assignName(&Plan.VF); 1583 if (Plan.VFxUF.getNumUsers() > 0) 1584 assignName(&Plan.VFxUF); 1585 assignName(&Plan.VectorTripCount); 1586 if (Plan.BackedgeTakenCount) 1587 assignName(Plan.BackedgeTakenCount); 1588 for (VPValue *LI : Plan.VPLiveInsToFree) 1589 assignName(LI); 1590 assignNames(Plan.getPreheader()); 1591 1592 ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>> 1593 RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry())); 1594 for (const VPBasicBlock *VPBB : 1595 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1596 assignNames(VPBB); 1597 } 1598 1599 void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) { 1600 for (const VPRecipeBase &Recipe : *VPBB) 1601 for (VPValue *Def : Recipe.definedValues()) 1602 assignName(Def); 1603 } 1604 1605 std::string VPSlotTracker::getOrCreateName(const VPValue *V) const { 1606 std::string Name = VPValue2Name.lookup(V); 1607 if (!Name.empty()) 1608 return Name; 1609 1610 // If no name was assigned, no VPlan was provided when creating the slot 1611 // tracker or it is not reachable from the provided VPlan. This can happen, 1612 // e.g. when trying to print a recipe that has not been inserted into a VPlan 1613 // in a debugger. 1614 // TODO: Update VPSlotTracker constructor to assign names to recipes & 1615 // VPValues not associated with a VPlan, instead of constructing names ad-hoc 1616 // here. 1617 const VPRecipeBase *DefR = V->getDefiningRecipe(); 1618 (void)DefR; 1619 assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) && 1620 "VPValue defined by a recipe in a VPlan?"); 1621 1622 // Use the underlying value's name, if there is one. 1623 if (auto *UV = V->getUnderlyingValue()) { 1624 std::string Name; 1625 raw_string_ostream S(Name); 1626 UV->printAsOperand(S, false); 1627 return (Twine("ir<") + Name + ">").str(); 1628 } 1629 1630 return "<badref>"; 1631 } 1632 1633 bool LoopVectorizationPlanner::getDecisionAndClampRange( 1634 const std::function<bool(ElementCount)> &Predicate, VFRange &Range) { 1635 assert(!Range.isEmpty() && "Trying to test an empty VF range."); 1636 bool PredicateAtRangeStart = Predicate(Range.Start); 1637 1638 for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End)) 1639 if (Predicate(TmpVF) != PredicateAtRangeStart) { 1640 Range.End = TmpVF; 1641 break; 1642 } 1643 1644 return PredicateAtRangeStart; 1645 } 1646 1647 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF, 1648 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range 1649 /// of VF's starting at a given VF and extending it as much as possible. Each 1650 /// vectorization decision can potentially shorten this sub-range during 1651 /// buildVPlan(). 1652 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF, 1653 ElementCount MaxVF) { 1654 auto MaxVFTimes2 = MaxVF * 2; 1655 for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) { 1656 VFRange SubRange = {VF, MaxVFTimes2}; 1657 auto Plan = buildVPlan(SubRange); 1658 VPlanTransforms::optimize(*Plan); 1659 VPlans.push_back(std::move(Plan)); 1660 VF = SubRange.End; 1661 } 1662 } 1663 1664 VPlan &LoopVectorizationPlanner::getPlanFor(ElementCount VF) const { 1665 assert(count_if(VPlans, 1666 [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) == 1667 1 && 1668 "Multiple VPlans for VF."); 1669 1670 for (const VPlanPtr &Plan : VPlans) { 1671 if (Plan->hasVF(VF)) 1672 return *Plan.get(); 1673 } 1674 llvm_unreachable("No plan found!"); 1675 } 1676 1677 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1678 void LoopVectorizationPlanner::printPlans(raw_ostream &O) { 1679 if (VPlans.empty()) { 1680 O << "LV: No VPlans built.\n"; 1681 return; 1682 } 1683 for (const auto &Plan : VPlans) 1684 if (PrintVPlansInDotFormat) 1685 Plan->printDOT(O); 1686 else 1687 Plan->print(O); 1688 } 1689 #endif 1690 1691 TargetTransformInfo::OperandValueInfo 1692 VPCostContext::getOperandInfo(VPValue *V) const { 1693 if (!V->isLiveIn()) 1694 return {}; 1695 1696 return TTI::getOperandInfo(V->getLiveInIRValue()); 1697 } 1698