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 "VPlanDominatorTree.h" 21 #include "llvm/ADT/DepthFirstIterator.h" 22 #include "llvm/ADT/PostOrderIterator.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Twine.h" 26 #include "llvm/Analysis/LoopInfo.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/CFG.h" 29 #include "llvm/IR/IRBuilder.h" 30 #include "llvm/IR/Instruction.h" 31 #include "llvm/IR/Instructions.h" 32 #include "llvm/IR/Type.h" 33 #include "llvm/IR/Value.h" 34 #include "llvm/Support/Casting.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/GenericDomTreeConstruction.h" 38 #include "llvm/Support/GraphWriter.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 41 #include "llvm/Transforms/Utils/LoopVersioning.h" 42 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 43 #include <cassert> 44 #include <string> 45 #include <vector> 46 47 using namespace llvm; 48 extern cl::opt<bool> EnableVPlanNativePath; 49 50 #define DEBUG_TYPE "vplan" 51 52 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 53 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 54 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 55 VPSlotTracker SlotTracker( 56 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 57 V.print(OS, SlotTracker); 58 return OS; 59 } 60 #endif 61 62 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 63 const ElementCount &VF) const { 64 switch (LaneKind) { 65 case VPLane::Kind::ScalableLast: 66 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 67 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 68 Builder.getInt32(VF.getKnownMinValue() - Lane)); 69 case VPLane::Kind::First: 70 return Builder.getInt32(Lane); 71 } 72 llvm_unreachable("Unknown lane kind"); 73 } 74 75 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 76 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 77 if (Def) 78 Def->addDefinedValue(this); 79 } 80 81 VPValue::~VPValue() { 82 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 83 if (Def) 84 Def->removeDefinedValue(this); 85 } 86 87 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 88 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 89 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 90 R->print(OS, "", SlotTracker); 91 else 92 printAsOperand(OS, SlotTracker); 93 } 94 95 void VPValue::dump() const { 96 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 97 VPSlotTracker SlotTracker( 98 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 99 print(dbgs(), SlotTracker); 100 dbgs() << "\n"; 101 } 102 103 void VPDef::dump() const { 104 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 105 VPSlotTracker SlotTracker( 106 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 107 print(dbgs(), "", SlotTracker); 108 dbgs() << "\n"; 109 } 110 #endif 111 112 VPRecipeBase *VPValue::getDefiningRecipe() { 113 return cast_or_null<VPRecipeBase>(Def); 114 } 115 116 const VPRecipeBase *VPValue::getDefiningRecipe() const { 117 return cast_or_null<VPRecipeBase>(Def); 118 } 119 120 // Get the top-most entry block of \p Start. This is the entry block of the 121 // containing VPlan. This function is templated to support both const and non-const blocks 122 template <typename T> static T *getPlanEntry(T *Start) { 123 T *Next = Start; 124 T *Current = Start; 125 while ((Next = Next->getParent())) 126 Current = Next; 127 128 SmallSetVector<T *, 8> WorkList; 129 WorkList.insert(Current); 130 131 for (unsigned i = 0; i < WorkList.size(); i++) { 132 T *Current = WorkList[i]; 133 if (Current->getNumPredecessors() == 0) 134 return Current; 135 auto &Predecessors = Current->getPredecessors(); 136 WorkList.insert(Predecessors.begin(), Predecessors.end()); 137 } 138 139 llvm_unreachable("VPlan without any entry node without predecessors"); 140 } 141 142 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 143 144 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 145 146 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 147 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 148 const VPBlockBase *Block = this; 149 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 150 Block = Region->getEntry(); 151 return cast<VPBasicBlock>(Block); 152 } 153 154 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 155 VPBlockBase *Block = this; 156 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 157 Block = Region->getEntry(); 158 return cast<VPBasicBlock>(Block); 159 } 160 161 void VPBlockBase::setPlan(VPlan *ParentPlan) { 162 assert(ParentPlan->getEntry() == this && 163 "Can only set plan on its entry block."); 164 Plan = ParentPlan; 165 } 166 167 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 168 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const { 169 const VPBlockBase *Block = this; 170 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 171 Block = Region->getExiting(); 172 return cast<VPBasicBlock>(Block); 173 } 174 175 VPBasicBlock *VPBlockBase::getExitingBasicBlock() { 176 VPBlockBase *Block = this; 177 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 178 Block = Region->getExiting(); 179 return cast<VPBasicBlock>(Block); 180 } 181 182 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 183 if (!Successors.empty() || !Parent) 184 return this; 185 assert(Parent->getExiting() == this && 186 "Block w/o successors not the exiting block of its parent."); 187 return Parent->getEnclosingBlockWithSuccessors(); 188 } 189 190 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 191 if (!Predecessors.empty() || !Parent) 192 return this; 193 assert(Parent->getEntry() == this && 194 "Block w/o predecessors not the entry of its parent."); 195 return Parent->getEnclosingBlockWithPredecessors(); 196 } 197 198 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 199 SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry)); 200 201 for (VPBlockBase *Block : Blocks) 202 delete Block; 203 } 204 205 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 206 iterator It = begin(); 207 while (It != end() && It->isPhi()) 208 It++; 209 return It; 210 } 211 212 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 213 if (!Def->hasDefiningRecipe()) 214 return Def->getLiveInIRValue(); 215 216 if (hasScalarValue(Def, Instance)) { 217 return Data 218 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 219 } 220 221 assert(hasVectorValue(Def, Instance.Part)); 222 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 223 if (!VecPart->getType()->isVectorTy()) { 224 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 225 return VecPart; 226 } 227 // TODO: Cache created scalar values. 228 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 229 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 230 // set(Def, Extract, Instance); 231 return Extract; 232 } 233 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) { 234 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion(); 235 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()]; 236 } 237 238 void VPTransformState::addNewMetadata(Instruction *To, 239 const Instruction *Orig) { 240 // If the loop was versioned with memchecks, add the corresponding no-alias 241 // metadata. 242 if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig))) 243 LVer->annotateInstWithNoAlias(To, Orig); 244 } 245 246 void VPTransformState::addMetadata(Instruction *To, Instruction *From) { 247 propagateMetadata(To, From); 248 addNewMetadata(To, From); 249 } 250 251 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) { 252 for (Value *V : To) { 253 if (Instruction *I = dyn_cast<Instruction>(V)) 254 addMetadata(I, From); 255 } 256 } 257 258 void VPTransformState::setDebugLocFromInst(const Value *V) { 259 const Instruction *Inst = dyn_cast<Instruction>(V); 260 if (!Inst) { 261 Builder.SetCurrentDebugLocation(DebugLoc()); 262 return; 263 } 264 265 const DILocation *DIL = Inst->getDebugLoc(); 266 // When a FSDiscriminator is enabled, we don't need to add the multiply 267 // factors to the discriminators. 268 if (DIL && Inst->getFunction()->shouldEmitDebugInfoForProfiling() && 269 !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) { 270 // FIXME: For scalable vectors, assume vscale=1. 271 auto NewDIL = 272 DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue()); 273 if (NewDIL) 274 Builder.SetCurrentDebugLocation(*NewDIL); 275 else 276 LLVM_DEBUG(dbgs() << "Failed to create new discriminator: " 277 << DIL->getFilename() << " Line: " << DIL->getLine()); 278 } else 279 Builder.SetCurrentDebugLocation(DIL); 280 } 281 282 BasicBlock * 283 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 284 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 285 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 286 BasicBlock *PrevBB = CFG.PrevBB; 287 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 288 PrevBB->getParent(), CFG.ExitBB); 289 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 290 291 // Hook up the new basic block to its predecessors. 292 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 293 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 294 auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors(); 295 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 296 297 assert(PredBB && "Predecessor basic-block not found building successor."); 298 auto *PredBBTerminator = PredBB->getTerminator(); 299 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 300 301 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 302 if (isa<UnreachableInst>(PredBBTerminator)) { 303 assert(PredVPSuccessors.size() == 1 && 304 "Predecessor ending w/o branch must have single successor."); 305 DebugLoc DL = PredBBTerminator->getDebugLoc(); 306 PredBBTerminator->eraseFromParent(); 307 auto *Br = BranchInst::Create(NewBB, PredBB); 308 Br->setDebugLoc(DL); 309 } else if (TermBr && !TermBr->isConditional()) { 310 TermBr->setSuccessor(0, NewBB); 311 } else { 312 // Set each forward successor here when it is created, excluding 313 // backedges. A backward successor is set when the branch is created. 314 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 315 assert(!TermBr->getSuccessor(idx) && 316 "Trying to reset an existing successor block."); 317 TermBr->setSuccessor(idx, NewBB); 318 } 319 } 320 return NewBB; 321 } 322 323 void VPBasicBlock::execute(VPTransformState *State) { 324 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 325 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 326 VPBlockBase *SingleHPred = nullptr; 327 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 328 329 auto IsLoopRegion = [](VPBlockBase *BB) { 330 auto *R = dyn_cast<VPRegionBlock>(BB); 331 return R && !R->isReplicator(); 332 }; 333 334 // 1. Create an IR basic block, or reuse the last one or ExitBB if possible. 335 if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) { 336 // ExitBB can be re-used for the exit block of the Plan. 337 NewBB = State->CFG.ExitBB; 338 State->CFG.PrevBB = NewBB; 339 340 // Update the branch instruction in the predecessor to branch to ExitBB. 341 VPBlockBase *PredVPB = getSingleHierarchicalPredecessor(); 342 VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock(); 343 assert(PredVPB->getSingleSuccessor() == this && 344 "predecessor must have the current block as only successor"); 345 BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB]; 346 // The Exit block of a loop is always set to be successor 0 of the Exiting 347 // block. 348 cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB); 349 } else if (PrevVPBB && /* A */ 350 !((SingleHPred = getSingleHierarchicalPredecessor()) && 351 SingleHPred->getExitingBasicBlock() == PrevVPBB && 352 PrevVPBB->getSingleHierarchicalSuccessor() && 353 (SingleHPred->getParent() == getEnclosingLoopRegion() && 354 !IsLoopRegion(SingleHPred))) && /* B */ 355 !(Replica && getPredecessors().empty())) { /* C */ 356 // The last IR basic block is reused, as an optimization, in three cases: 357 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 358 // B. when the current VPBB has a single (hierarchical) predecessor which 359 // is PrevVPBB and the latter has a single (hierarchical) successor which 360 // both are in the same non-replicator region; and 361 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 362 // is the exiting VPBB of this region from a previous instance, or the 363 // predecessor of this region. 364 365 NewBB = createEmptyBasicBlock(State->CFG); 366 State->Builder.SetInsertPoint(NewBB); 367 // Temporarily terminate with unreachable until CFG is rewired. 368 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 369 // Register NewBB in its loop. In innermost loops its the same for all 370 // BB's. 371 if (State->CurrentVectorLoop) 372 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 373 State->Builder.SetInsertPoint(Terminator); 374 State->CFG.PrevBB = NewBB; 375 } 376 377 // 2. Fill the IR basic block with IR instructions. 378 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 379 << " in BB:" << NewBB->getName() << '\n'); 380 381 State->CFG.VPBB2IRBB[this] = NewBB; 382 State->CFG.PrevVPBB = this; 383 384 for (VPRecipeBase &Recipe : Recipes) 385 Recipe.execute(*State); 386 387 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 388 } 389 390 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 391 for (VPRecipeBase &R : Recipes) { 392 for (auto *Def : R.definedValues()) 393 Def->replaceAllUsesWith(NewValue); 394 395 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 396 R.setOperand(I, NewValue); 397 } 398 } 399 400 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 401 assert((SplitAt == end() || SplitAt->getParent() == this) && 402 "can only split at a position in the same block"); 403 404 SmallVector<VPBlockBase *, 2> Succs(successors()); 405 // First, disconnect the current block from its successors. 406 for (VPBlockBase *Succ : Succs) 407 VPBlockUtils::disconnectBlocks(this, Succ); 408 409 // Create new empty block after the block to split. 410 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 411 VPBlockUtils::insertBlockAfter(SplitBlock, this); 412 413 // Add successors for block to split to new block. 414 for (VPBlockBase *Succ : Succs) 415 VPBlockUtils::connectBlocks(SplitBlock, Succ); 416 417 // Finally, move the recipes starting at SplitAt to new block. 418 for (VPRecipeBase &ToMove : 419 make_early_inc_range(make_range(SplitAt, this->end()))) 420 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 421 422 return SplitBlock; 423 } 424 425 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 426 VPRegionBlock *P = getParent(); 427 if (P && P->isReplicator()) { 428 P = P->getParent(); 429 assert(!cast<VPRegionBlock>(P)->isReplicator() && 430 "unexpected nested replicate regions"); 431 } 432 return P; 433 } 434 435 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 436 if (VPBB->empty()) { 437 assert( 438 VPBB->getNumSuccessors() < 2 && 439 "block with multiple successors doesn't have a recipe as terminator"); 440 return false; 441 } 442 443 const VPRecipeBase *R = &VPBB->back(); 444 auto *VPI = dyn_cast<VPInstruction>(R); 445 bool IsCondBranch = 446 isa<VPBranchOnMaskRecipe>(R) || 447 (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond || 448 VPI->getOpcode() == VPInstruction::BranchOnCount)); 449 (void)IsCondBranch; 450 451 if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) { 452 assert(IsCondBranch && "block with multiple successors not terminated by " 453 "conditional branch recipe"); 454 455 return true; 456 } 457 458 assert( 459 !IsCondBranch && 460 "block with 0 or 1 successors terminated by conditional branch recipe"); 461 return false; 462 } 463 464 VPRecipeBase *VPBasicBlock::getTerminator() { 465 if (hasConditionalTerminator(this)) 466 return &back(); 467 return nullptr; 468 } 469 470 const VPRecipeBase *VPBasicBlock::getTerminator() const { 471 if (hasConditionalTerminator(this)) 472 return &back(); 473 return nullptr; 474 } 475 476 bool VPBasicBlock::isExiting() const { 477 return getParent()->getExitingBasicBlock() == this; 478 } 479 480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 481 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 482 if (getSuccessors().empty()) { 483 O << Indent << "No successors\n"; 484 } else { 485 O << Indent << "Successor(s): "; 486 ListSeparator LS; 487 for (auto *Succ : getSuccessors()) 488 O << LS << Succ->getName(); 489 O << '\n'; 490 } 491 } 492 493 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 494 VPSlotTracker &SlotTracker) const { 495 O << Indent << getName() << ":\n"; 496 497 auto RecipeIndent = Indent + " "; 498 for (const VPRecipeBase &Recipe : *this) { 499 Recipe.print(O, RecipeIndent, SlotTracker); 500 O << '\n'; 501 } 502 503 printSuccessors(O, Indent); 504 } 505 #endif 506 507 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 508 for (VPBlockBase *Block : depth_first(Entry)) 509 // Drop all references in VPBasicBlocks and replace all uses with 510 // DummyValue. 511 Block->dropAllReferences(NewValue); 512 } 513 514 void VPRegionBlock::execute(VPTransformState *State) { 515 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 516 517 if (!isReplicator()) { 518 // Create and register the new vector loop. 519 Loop *PrevLoop = State->CurrentVectorLoop; 520 State->CurrentVectorLoop = State->LI->AllocateLoop(); 521 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 522 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 523 524 // Insert the new loop into the loop nest and register the new basic blocks 525 // before calling any utilities such as SCEV that require valid LoopInfo. 526 if (ParentLoop) 527 ParentLoop->addChildLoop(State->CurrentVectorLoop); 528 else 529 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 530 531 // Visit the VPBlocks connected to "this", starting from it. 532 for (VPBlockBase *Block : RPOT) { 533 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 534 Block->execute(State); 535 } 536 537 State->CurrentVectorLoop = PrevLoop; 538 return; 539 } 540 541 assert(!State->Instance && "Replicating a Region with non-null instance."); 542 543 // Enter replicating mode. 544 State->Instance = VPIteration(0, 0); 545 546 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 547 State->Instance->Part = Part; 548 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 549 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 550 ++Lane) { 551 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 552 // Visit the VPBlocks connected to \p this, starting from it. 553 for (VPBlockBase *Block : RPOT) { 554 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 555 Block->execute(State); 556 } 557 } 558 } 559 560 // Exit replicating mode. 561 State->Instance.reset(); 562 } 563 564 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 565 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 566 VPSlotTracker &SlotTracker) const { 567 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 568 auto NewIndent = Indent + " "; 569 for (auto *BlockBase : depth_first(Entry)) { 570 O << '\n'; 571 BlockBase->print(O, NewIndent, SlotTracker); 572 } 573 O << Indent << "}\n"; 574 575 printSuccessors(O, Indent); 576 } 577 #endif 578 579 VPActiveLaneMaskPHIRecipe *VPlan::getActiveLaneMaskPhi() { 580 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 581 for (VPRecipeBase &R : Header->phis()) { 582 if (isa<VPActiveLaneMaskPHIRecipe>(&R)) 583 return cast<VPActiveLaneMaskPHIRecipe>(&R); 584 } 585 return nullptr; 586 } 587 588 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 589 Value *CanonicalIVStartValue, 590 VPTransformState &State, 591 bool IsEpilogueVectorization) { 592 593 // Check if the trip count is needed, and if so build it. 594 if (TripCount && TripCount->getNumUsers()) { 595 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 596 State.set(TripCount, TripCountV, Part); 597 } 598 599 // Check if the backedge taken count is needed, and if so build it. 600 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 601 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 602 auto *TCMO = Builder.CreateSub(TripCountV, 603 ConstantInt::get(TripCountV->getType(), 1), 604 "trip.count.minus.1"); 605 auto VF = State.VF; 606 Value *VTCMO = 607 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 608 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 609 State.set(BackedgeTakenCount, VTCMO, Part); 610 } 611 612 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 613 State.set(&VectorTripCount, VectorTripCountV, Part); 614 615 // When vectorizing the epilogue loop, the canonical induction start value 616 // needs to be changed from zero to the value after the main vector loop. 617 // FIXME: Improve modeling for canonical IV start values in the epilogue loop. 618 if (CanonicalIVStartValue) { 619 VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue); 620 auto *IV = getCanonicalIV(); 621 assert(all_of(IV->users(), 622 [](const VPUser *U) { 623 if (isa<VPScalarIVStepsRecipe>(U) || 624 isa<VPDerivedIVRecipe>(U)) 625 return true; 626 auto *VPI = cast<VPInstruction>(U); 627 return VPI->getOpcode() == 628 VPInstruction::CanonicalIVIncrement || 629 VPI->getOpcode() == 630 VPInstruction::CanonicalIVIncrementNUW; 631 }) && 632 "the canonical IV should only be used by its increments or " 633 "ScalarIVSteps when " 634 "resetting the start value"); 635 IV->setOperand(0, VPV); 636 } 637 } 638 639 /// Generate the code inside the preheader and body of the vectorized loop. 640 /// Assumes a single pre-header basic-block was created for this. Introduce 641 /// additional basic-blocks as needed, and fill them all. 642 void VPlan::execute(VPTransformState *State) { 643 // Set the reverse mapping from VPValues to Values for code generation. 644 for (auto &Entry : Value2VPValue) 645 State->VPValue2Value[Entry.second] = Entry.first; 646 647 // Initialize CFG state. 648 State->CFG.PrevVPBB = nullptr; 649 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 650 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 651 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 652 653 // Generate code in the loop pre-header and body. 654 for (VPBlockBase *Block : depth_first(Entry)) 655 Block->execute(State); 656 657 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 658 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 659 660 // Fix the latch value of canonical, reduction and first-order recurrences 661 // phis in the vector loop. 662 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 663 for (VPRecipeBase &R : Header->phis()) { 664 // Skip phi-like recipes that generate their backedege values themselves. 665 if (isa<VPWidenPHIRecipe>(&R)) 666 continue; 667 668 if (isa<VPWidenPointerInductionRecipe>(&R) || 669 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 670 PHINode *Phi = nullptr; 671 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 672 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 673 } else { 674 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 675 // TODO: Split off the case that all users of a pointer phi are scalar 676 // from the VPWidenPointerInductionRecipe. 677 if (WidenPhi->onlyScalarsGenerated(State->VF)) 678 continue; 679 680 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 681 Phi = cast<PHINode>(GEP->getPointerOperand()); 682 } 683 684 Phi->setIncomingBlock(1, VectorLatchBB); 685 686 // Move the last step to the end of the latch block. This ensures 687 // consistent placement of all induction updates. 688 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 689 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 690 continue; 691 } 692 693 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 694 // For canonical IV, first-order recurrences and in-order reduction phis, 695 // only a single part is generated, which provides the last part from the 696 // previous iteration. For non-ordered reductions all UF parts are 697 // generated. 698 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 699 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 700 (isa<VPReductionPHIRecipe>(PhiR) && 701 cast<VPReductionPHIRecipe>(PhiR)->isOrdered()); 702 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 703 704 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 705 Value *Phi = State->get(PhiR, Part); 706 Value *Val = State->get(PhiR->getBackedgeValue(), 707 SinglePartNeeded ? State->UF - 1 : Part); 708 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 709 } 710 } 711 712 // We do not attempt to preserve DT for outer loop vectorization currently. 713 if (!EnableVPlanNativePath) { 714 BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header]; 715 State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader); 716 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 717 State->CFG.ExitBB); 718 } 719 } 720 721 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 722 LLVM_DUMP_METHOD 723 void VPlan::print(raw_ostream &O) const { 724 VPSlotTracker SlotTracker(this); 725 726 O << "VPlan '" << getName() << "' {"; 727 728 if (VectorTripCount.getNumUsers() > 0) { 729 O << "\nLive-in "; 730 VectorTripCount.printAsOperand(O, SlotTracker); 731 O << " = vector-trip-count\n"; 732 } 733 734 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 735 O << "\nLive-in "; 736 BackedgeTakenCount->printAsOperand(O, SlotTracker); 737 O << " = backedge-taken count\n"; 738 } 739 740 for (const VPBlockBase *Block : depth_first(getEntry())) { 741 O << '\n'; 742 Block->print(O, "", SlotTracker); 743 } 744 745 if (!LiveOuts.empty()) 746 O << "\n"; 747 for (const auto &KV : LiveOuts) { 748 O << "Live-out "; 749 KV.second->getPhi()->printAsOperand(O); 750 O << " = "; 751 KV.second->getOperand(0)->printAsOperand(O, SlotTracker); 752 O << "\n"; 753 } 754 755 O << "}\n"; 756 } 757 758 std::string VPlan::getName() const { 759 std::string Out; 760 raw_string_ostream RSO(Out); 761 RSO << Name << " for "; 762 if (!VFs.empty()) { 763 RSO << "VF={" << VFs[0]; 764 for (ElementCount VF : drop_begin(VFs)) 765 RSO << "," << VF; 766 RSO << "},"; 767 } 768 769 if (UFs.empty()) { 770 RSO << "UF>=1"; 771 } else { 772 RSO << "UF={" << UFs[0]; 773 for (unsigned UF : drop_begin(UFs)) 774 RSO << "," << UF; 775 RSO << "}"; 776 } 777 778 return Out; 779 } 780 781 LLVM_DUMP_METHOD 782 void VPlan::printDOT(raw_ostream &O) const { 783 VPlanPrinter Printer(O, *this); 784 Printer.dump(); 785 } 786 787 LLVM_DUMP_METHOD 788 void VPlan::dump() const { print(dbgs()); } 789 #endif 790 791 void VPlan::addLiveOut(PHINode *PN, VPValue *V) { 792 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists"); 793 LiveOuts.insert({PN, new VPLiveOut(PN, V)}); 794 } 795 796 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 797 BasicBlock *LoopLatchBB, 798 BasicBlock *LoopExitBB) { 799 // The vector body may be more than a single basic-block by this point. 800 // Update the dominator tree information inside the vector body by propagating 801 // it from header to latch, expecting only triangular control-flow, if any. 802 BasicBlock *PostDomSucc = nullptr; 803 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 804 // Get the list of successors of this block. 805 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 806 assert(Succs.size() <= 2 && 807 "Basic block in vector loop has more than 2 successors."); 808 PostDomSucc = Succs[0]; 809 if (Succs.size() == 1) { 810 assert(PostDomSucc->getSinglePredecessor() && 811 "PostDom successor has more than one predecessor."); 812 DT->addNewBlock(PostDomSucc, BB); 813 continue; 814 } 815 BasicBlock *InterimSucc = Succs[1]; 816 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 817 PostDomSucc = Succs[1]; 818 InterimSucc = Succs[0]; 819 } 820 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 821 "One successor of a basic block does not lead to the other."); 822 assert(InterimSucc->getSinglePredecessor() && 823 "Interim successor has more than one predecessor."); 824 assert(PostDomSucc->hasNPredecessors(2) && 825 "PostDom successor has more than two predecessors."); 826 DT->addNewBlock(InterimSucc, BB); 827 DT->addNewBlock(PostDomSucc, BB); 828 } 829 // Latch block is a new dominator for the loop exit. 830 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 831 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 832 } 833 834 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 835 836 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 837 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 838 Twine(getOrCreateBID(Block)); 839 } 840 841 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 842 const std::string &Name = Block->getName(); 843 if (!Name.empty()) 844 return Name; 845 return "VPB" + Twine(getOrCreateBID(Block)); 846 } 847 848 void VPlanPrinter::dump() { 849 Depth = 1; 850 bumpIndent(0); 851 OS << "digraph VPlan {\n"; 852 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 853 if (!Plan.getName().empty()) 854 OS << "\\n" << DOT::EscapeString(Plan.getName()); 855 if (Plan.BackedgeTakenCount) { 856 OS << ", where:\\n"; 857 Plan.BackedgeTakenCount->print(OS, SlotTracker); 858 OS << " := BackedgeTakenCount"; 859 } 860 OS << "\"]\n"; 861 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 862 OS << "edge [fontname=Courier, fontsize=30]\n"; 863 OS << "compound=true\n"; 864 865 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 866 dumpBlock(Block); 867 868 OS << "}\n"; 869 } 870 871 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 872 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 873 dumpBasicBlock(BasicBlock); 874 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 875 dumpRegion(Region); 876 else 877 llvm_unreachable("Unsupported kind of VPBlock."); 878 } 879 880 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 881 bool Hidden, const Twine &Label) { 882 // Due to "dot" we print an edge between two regions as an edge between the 883 // exiting basic block and the entry basic of the respective regions. 884 const VPBlockBase *Tail = From->getExitingBasicBlock(); 885 const VPBlockBase *Head = To->getEntryBasicBlock(); 886 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 887 OS << " [ label=\"" << Label << '\"'; 888 if (Tail != From) 889 OS << " ltail=" << getUID(From); 890 if (Head != To) 891 OS << " lhead=" << getUID(To); 892 if (Hidden) 893 OS << "; splines=none"; 894 OS << "]\n"; 895 } 896 897 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 898 auto &Successors = Block->getSuccessors(); 899 if (Successors.size() == 1) 900 drawEdge(Block, Successors.front(), false, ""); 901 else if (Successors.size() == 2) { 902 drawEdge(Block, Successors.front(), false, "T"); 903 drawEdge(Block, Successors.back(), false, "F"); 904 } else { 905 unsigned SuccessorNumber = 0; 906 for (auto *Successor : Successors) 907 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 908 } 909 } 910 911 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 912 // Implement dot-formatted dump by performing plain-text dump into the 913 // temporary storage followed by some post-processing. 914 OS << Indent << getUID(BasicBlock) << " [label =\n"; 915 bumpIndent(1); 916 std::string Str; 917 raw_string_ostream SS(Str); 918 // Use no indentation as we need to wrap the lines into quotes ourselves. 919 BasicBlock->print(SS, "", SlotTracker); 920 921 // We need to process each line of the output separately, so split 922 // single-string plain-text dump. 923 SmallVector<StringRef, 0> Lines; 924 StringRef(Str).rtrim('\n').split(Lines, "\n"); 925 926 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 927 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 928 }; 929 930 // Don't need the "+" after the last line. 931 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 932 EmitLine(Line, " +\n"); 933 EmitLine(Lines.back(), "\n"); 934 935 bumpIndent(-1); 936 OS << Indent << "]\n"; 937 938 dumpEdges(BasicBlock); 939 } 940 941 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 942 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 943 bumpIndent(1); 944 OS << Indent << "fontname=Courier\n" 945 << Indent << "label=\"" 946 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 947 << DOT::EscapeString(Region->getName()) << "\"\n"; 948 // Dump the blocks of the region. 949 assert(Region->getEntry() && "Region contains no inner blocks."); 950 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 951 dumpBlock(Block); 952 bumpIndent(-1); 953 OS << Indent << "}\n"; 954 dumpEdges(Region); 955 } 956 957 void VPlanIngredient::print(raw_ostream &O) const { 958 if (auto *Inst = dyn_cast<Instruction>(V)) { 959 if (!Inst->getType()->isVoidTy()) { 960 Inst->printAsOperand(O, false); 961 O << " = "; 962 } 963 O << Inst->getOpcodeName() << " "; 964 unsigned E = Inst->getNumOperands(); 965 if (E > 0) { 966 Inst->getOperand(0)->printAsOperand(O, false); 967 for (unsigned I = 1; I < E; ++I) 968 Inst->getOperand(I)->printAsOperand(O << ", ", false); 969 } 970 } else // !Inst 971 V->printAsOperand(O, false); 972 } 973 974 #endif 975 976 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 977 978 void VPValue::replaceAllUsesWith(VPValue *New) { 979 for (unsigned J = 0; J < getNumUsers();) { 980 VPUser *User = Users[J]; 981 unsigned NumUsers = getNumUsers(); 982 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 983 if (User->getOperand(I) == this) 984 User->setOperand(I, New); 985 // If a user got removed after updating the current user, the next user to 986 // update will be moved to the current position, so we only need to 987 // increment the index if the number of users did not change. 988 if (NumUsers == getNumUsers()) 989 J++; 990 } 991 } 992 993 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 994 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 995 if (const Value *UV = getUnderlyingValue()) { 996 OS << "ir<"; 997 UV->printAsOperand(OS, false); 998 OS << ">"; 999 return; 1000 } 1001 1002 unsigned Slot = Tracker.getSlot(this); 1003 if (Slot == unsigned(-1)) 1004 OS << "<badref>"; 1005 else 1006 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1007 } 1008 1009 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1010 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1011 Op->printAsOperand(O, SlotTracker); 1012 }); 1013 } 1014 #endif 1015 1016 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1017 Old2NewTy &Old2New, 1018 InterleavedAccessInfo &IAI) { 1019 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1020 for (VPBlockBase *Base : RPOT) { 1021 visitBlock(Base, Old2New, IAI); 1022 } 1023 } 1024 1025 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1026 InterleavedAccessInfo &IAI) { 1027 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1028 for (VPRecipeBase &VPI : *VPBB) { 1029 if (isa<VPHeaderPHIRecipe>(&VPI)) 1030 continue; 1031 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1032 auto *VPInst = cast<VPInstruction>(&VPI); 1033 1034 auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue()); 1035 if (!Inst) 1036 continue; 1037 auto *IG = IAI.getInterleaveGroup(Inst); 1038 if (!IG) 1039 continue; 1040 1041 auto NewIGIter = Old2New.find(IG); 1042 if (NewIGIter == Old2New.end()) 1043 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1044 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1045 1046 if (Inst == IG->getInsertPos()) 1047 Old2New[IG]->setInsertPos(VPInst); 1048 1049 InterleaveGroupMap[VPInst] = Old2New[IG]; 1050 InterleaveGroupMap[VPInst]->insertMember( 1051 VPInst, IG->getIndex(Inst), 1052 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1053 : IG->getFactor())); 1054 } 1055 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1056 visitRegion(Region, Old2New, IAI); 1057 else 1058 llvm_unreachable("Unsupported kind of VPBlock."); 1059 } 1060 1061 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1062 InterleavedAccessInfo &IAI) { 1063 Old2NewTy Old2New; 1064 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1065 } 1066 1067 void VPSlotTracker::assignSlot(const VPValue *V) { 1068 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1069 Slots[V] = NextSlot++; 1070 } 1071 1072 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1073 1074 for (const auto &P : Plan.VPExternalDefs) 1075 assignSlot(P.second); 1076 1077 assignSlot(&Plan.VectorTripCount); 1078 if (Plan.BackedgeTakenCount) 1079 assignSlot(Plan.BackedgeTakenCount); 1080 1081 ReversePostOrderTraversal< 1082 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1083 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1084 Plan.getEntry())); 1085 for (const VPBasicBlock *VPBB : 1086 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1087 for (const VPRecipeBase &Recipe : *VPBB) 1088 for (VPValue *Def : Recipe.definedValues()) 1089 assignSlot(Def); 1090 } 1091 1092 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1093 return all_of(Def->users(), 1094 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); }); 1095 } 1096 1097 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 1098 ScalarEvolution &SE) { 1099 if (auto *E = dyn_cast<SCEVConstant>(Expr)) 1100 return Plan.getOrAddExternalDef(E->getValue()); 1101 if (auto *E = dyn_cast<SCEVUnknown>(Expr)) 1102 return Plan.getOrAddExternalDef(E->getValue()); 1103 1104 VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock(); 1105 VPExpandSCEVRecipe *Step = new VPExpandSCEVRecipe(Expr, SE); 1106 Preheader->appendRecipe(Step); 1107 return Step; 1108 } 1109