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/IVDescriptors.h" 27 #include "llvm/Analysis/LoopInfo.h" 28 #include "llvm/IR/BasicBlock.h" 29 #include "llvm/IR/CFG.h" 30 #include "llvm/IR/IRBuilder.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/Support/Casting.h" 36 #include "llvm/Support/CommandLine.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/GenericDomTreeConstruction.h" 40 #include "llvm/Support/GraphWriter.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 43 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h" 44 #include <cassert> 45 #include <string> 46 #include <vector> 47 48 using namespace llvm; 49 extern cl::opt<bool> EnableVPlanNativePath; 50 51 #define DEBUG_TYPE "vplan" 52 53 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 54 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) { 55 const VPInstruction *Instr = dyn_cast<VPInstruction>(&V); 56 VPSlotTracker SlotTracker( 57 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 58 V.print(OS, SlotTracker); 59 return OS; 60 } 61 #endif 62 63 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder, 64 const ElementCount &VF) const { 65 switch (LaneKind) { 66 case VPLane::Kind::ScalableLast: 67 // Lane = RuntimeVF - VF.getKnownMinValue() + Lane 68 return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF), 69 Builder.getInt32(VF.getKnownMinValue() - Lane)); 70 case VPLane::Kind::First: 71 return Builder.getInt32(Lane); 72 } 73 llvm_unreachable("Unknown lane kind"); 74 } 75 76 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def) 77 : SubclassID(SC), UnderlyingVal(UV), Def(Def) { 78 if (Def) 79 Def->addDefinedValue(this); 80 } 81 82 VPValue::~VPValue() { 83 assert(Users.empty() && "trying to delete a VPValue with remaining users"); 84 if (Def) 85 Def->removeDefinedValue(this); 86 } 87 88 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 89 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const { 90 if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def)) 91 R->print(OS, "", SlotTracker); 92 else 93 printAsOperand(OS, SlotTracker); 94 } 95 96 void VPValue::dump() const { 97 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def); 98 VPSlotTracker SlotTracker( 99 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 100 print(dbgs(), SlotTracker); 101 dbgs() << "\n"; 102 } 103 104 void VPDef::dump() const { 105 const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this); 106 VPSlotTracker SlotTracker( 107 (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr); 108 print(dbgs(), "", SlotTracker); 109 dbgs() << "\n"; 110 } 111 #endif 112 113 // Get the top-most entry block of \p Start. This is the entry block of the 114 // containing VPlan. This function is templated to support both const and non-const blocks 115 template <typename T> static T *getPlanEntry(T *Start) { 116 T *Next = Start; 117 T *Current = Start; 118 while ((Next = Next->getParent())) 119 Current = Next; 120 121 SmallSetVector<T *, 8> WorkList; 122 WorkList.insert(Current); 123 124 for (unsigned i = 0; i < WorkList.size(); i++) { 125 T *Current = WorkList[i]; 126 if (Current->getNumPredecessors() == 0) 127 return Current; 128 auto &Predecessors = Current->getPredecessors(); 129 WorkList.insert(Predecessors.begin(), Predecessors.end()); 130 } 131 132 llvm_unreachable("VPlan without any entry node without predecessors"); 133 } 134 135 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; } 136 137 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; } 138 139 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly. 140 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const { 141 const VPBlockBase *Block = this; 142 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 143 Block = Region->getEntry(); 144 return cast<VPBasicBlock>(Block); 145 } 146 147 VPBasicBlock *VPBlockBase::getEntryBasicBlock() { 148 VPBlockBase *Block = this; 149 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 150 Block = Region->getEntry(); 151 return cast<VPBasicBlock>(Block); 152 } 153 154 void VPBlockBase::setPlan(VPlan *ParentPlan) { 155 assert(ParentPlan->getEntry() == this && 156 "Can only set plan on its entry block."); 157 Plan = ParentPlan; 158 } 159 160 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly. 161 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const { 162 const VPBlockBase *Block = this; 163 while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 164 Block = Region->getExiting(); 165 return cast<VPBasicBlock>(Block); 166 } 167 168 VPBasicBlock *VPBlockBase::getExitingBasicBlock() { 169 VPBlockBase *Block = this; 170 while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 171 Block = Region->getExiting(); 172 return cast<VPBasicBlock>(Block); 173 } 174 175 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() { 176 if (!Successors.empty() || !Parent) 177 return this; 178 assert(Parent->getExiting() == this && 179 "Block w/o successors not the exiting block of its parent."); 180 return Parent->getEnclosingBlockWithSuccessors(); 181 } 182 183 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() { 184 if (!Predecessors.empty() || !Parent) 185 return this; 186 assert(Parent->getEntry() == this && 187 "Block w/o predecessors not the entry of its parent."); 188 return Parent->getEnclosingBlockWithPredecessors(); 189 } 190 191 void VPBlockBase::deleteCFG(VPBlockBase *Entry) { 192 SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry)); 193 194 for (VPBlockBase *Block : Blocks) 195 delete Block; 196 } 197 198 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() { 199 iterator It = begin(); 200 while (It != end() && It->isPhi()) 201 It++; 202 return It; 203 } 204 205 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) { 206 if (!Def->getDef()) 207 return Def->getLiveInIRValue(); 208 209 if (hasScalarValue(Def, Instance)) { 210 return Data 211 .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)]; 212 } 213 214 assert(hasVectorValue(Def, Instance.Part)); 215 auto *VecPart = Data.PerPartOutput[Def][Instance.Part]; 216 if (!VecPart->getType()->isVectorTy()) { 217 assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar"); 218 return VecPart; 219 } 220 // TODO: Cache created scalar values. 221 Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF); 222 auto *Extract = Builder.CreateExtractElement(VecPart, Lane); 223 // set(Def, Extract, Instance); 224 return Extract; 225 } 226 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) { 227 VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion(); 228 return VPBB2IRBB[LoopRegion->getPreheaderVPBB()]; 229 } 230 231 BasicBlock * 232 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 233 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 234 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 235 BasicBlock *PrevBB = CFG.PrevBB; 236 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 237 PrevBB->getParent(), CFG.ExitBB); 238 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 239 240 // Hook up the new basic block to its predecessors. 241 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 242 VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock(); 243 auto &PredVPSuccessors = PredVPBB->getSuccessors(); 244 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 245 246 assert(PredBB && "Predecessor basic-block not found building successor."); 247 auto *PredBBTerminator = PredBB->getTerminator(); 248 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 249 250 auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator); 251 if (isa<UnreachableInst>(PredBBTerminator)) { 252 assert(PredVPSuccessors.size() == 1 && 253 "Predecessor ending w/o branch must have single successor."); 254 DebugLoc DL = PredBBTerminator->getDebugLoc(); 255 PredBBTerminator->eraseFromParent(); 256 auto *Br = BranchInst::Create(NewBB, PredBB); 257 Br->setDebugLoc(DL); 258 } else if (TermBr && !TermBr->isConditional()) { 259 TermBr->setSuccessor(0, NewBB); 260 } else if (PredVPSuccessors.size() == 2) { 261 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 262 assert(!PredBBTerminator->getSuccessor(idx) && 263 "Trying to reset an existing successor block."); 264 PredBBTerminator->setSuccessor(idx, NewBB); 265 } else { 266 // PredVPBB is the exiting block of a loop region. Connect its successor 267 // outside the region. 268 auto *LoopRegion = cast<VPRegionBlock>(PredVPBB->getParent()); 269 assert(!LoopRegion->isReplicator() && 270 "predecessor must be in a loop region"); 271 assert(PredVPSuccessors.empty() && 272 LoopRegion->getExitingBasicBlock() == PredVPBB && 273 "PredVPBB must be the exiting block of its parent region"); 274 assert(this == LoopRegion->getSingleSuccessor() && 275 "the current block must be the single successor of the region"); 276 PredBBTerminator->setSuccessor(0, NewBB); 277 PredBBTerminator->setSuccessor( 278 1, CFG.VPBB2IRBB[LoopRegion->getEntryBasicBlock()]); 279 } 280 } 281 return NewBB; 282 } 283 284 void VPBasicBlock::execute(VPTransformState *State) { 285 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 286 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 287 VPBlockBase *SingleHPred = nullptr; 288 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 289 290 auto IsLoopRegion = [](VPBlockBase *BB) { 291 auto *R = dyn_cast<VPRegionBlock>(BB); 292 return R && !R->isReplicator(); 293 }; 294 295 // 1. Create an IR basic block, or reuse the last one or ExitBB if possible. 296 if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) { 297 // ExitBB can be re-used for the exit block of the Plan. 298 NewBB = State->CFG.ExitBB; 299 State->CFG.PrevBB = NewBB; 300 } else if (PrevVPBB && /* A */ 301 !((SingleHPred = getSingleHierarchicalPredecessor()) && 302 SingleHPred->getExitingBasicBlock() == PrevVPBB && 303 PrevVPBB->getSingleHierarchicalSuccessor() && 304 (SingleHPred->getParent() == getEnclosingLoopRegion() && 305 !IsLoopRegion(SingleHPred))) && /* B */ 306 !(Replica && getPredecessors().empty())) { /* C */ 307 // The last IR basic block is reused, as an optimization, in three cases: 308 // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null; 309 // B. when the current VPBB has a single (hierarchical) predecessor which 310 // is PrevVPBB and the latter has a single (hierarchical) successor which 311 // both are in the same non-replicator region; and 312 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 313 // is the exiting VPBB of this region from a previous instance, or the 314 // predecessor of this region. 315 316 NewBB = createEmptyBasicBlock(State->CFG); 317 State->Builder.SetInsertPoint(NewBB); 318 // Temporarily terminate with unreachable until CFG is rewired. 319 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 320 // Register NewBB in its loop. In innermost loops its the same for all 321 // BB's. 322 if (State->CurrentVectorLoop) 323 State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI); 324 State->Builder.SetInsertPoint(Terminator); 325 State->CFG.PrevBB = NewBB; 326 } 327 328 // 2. Fill the IR basic block with IR instructions. 329 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 330 << " in BB:" << NewBB->getName() << '\n'); 331 332 State->CFG.VPBB2IRBB[this] = NewBB; 333 State->CFG.PrevVPBB = this; 334 335 for (VPRecipeBase &Recipe : Recipes) 336 Recipe.execute(*State); 337 338 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 339 } 340 341 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 342 for (VPRecipeBase &R : Recipes) { 343 for (auto *Def : R.definedValues()) 344 Def->replaceAllUsesWith(NewValue); 345 346 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 347 R.setOperand(I, NewValue); 348 } 349 } 350 351 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 352 assert((SplitAt == end() || SplitAt->getParent() == this) && 353 "can only split at a position in the same block"); 354 355 SmallVector<VPBlockBase *, 2> Succs(successors()); 356 // First, disconnect the current block from its successors. 357 for (VPBlockBase *Succ : Succs) 358 VPBlockUtils::disconnectBlocks(this, Succ); 359 360 // Create new empty block after the block to split. 361 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 362 VPBlockUtils::insertBlockAfter(SplitBlock, this); 363 364 // Add successors for block to split to new block. 365 for (VPBlockBase *Succ : Succs) 366 VPBlockUtils::connectBlocks(SplitBlock, Succ); 367 368 // Finally, move the recipes starting at SplitAt to new block. 369 for (VPRecipeBase &ToMove : 370 make_early_inc_range(make_range(SplitAt, this->end()))) 371 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 372 373 return SplitBlock; 374 } 375 376 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() { 377 VPRegionBlock *P = getParent(); 378 if (P && P->isReplicator()) { 379 P = P->getParent(); 380 assert(!cast<VPRegionBlock>(P)->isReplicator() && 381 "unexpected nested replicate regions"); 382 } 383 return P; 384 } 385 386 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) { 387 if (VPBB->empty()) { 388 assert( 389 VPBB->getNumSuccessors() < 2 && 390 "block with multiple successors doesn't have a recipe as terminator"); 391 return false; 392 } 393 394 const VPRecipeBase *R = &VPBB->back(); 395 auto *VPI = dyn_cast<VPInstruction>(R); 396 bool IsCondBranch = 397 isa<VPBranchOnMaskRecipe>(R) || 398 (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond || 399 VPI->getOpcode() == VPInstruction::BranchOnCount)); 400 401 if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) { 402 assert(IsCondBranch && "block with multiple successors not terminated by " 403 "conditional branch recipe"); 404 405 return true; 406 } 407 408 assert( 409 !IsCondBranch && 410 "block with 0 or 1 successors terminated by conditional branch recipe"); 411 return false; 412 } 413 414 VPRecipeBase *VPBasicBlock::getTerminator() { 415 if (hasConditionalTerminator(this)) 416 return &back(); 417 return nullptr; 418 } 419 420 const VPRecipeBase *VPBasicBlock::getTerminator() const { 421 if (hasConditionalTerminator(this)) 422 return &back(); 423 return nullptr; 424 } 425 426 bool VPBasicBlock::isExiting() const { 427 return getParent()->getExitingBasicBlock() == this; 428 } 429 430 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 431 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 432 if (getSuccessors().empty()) { 433 O << Indent << "No successors\n"; 434 } else { 435 O << Indent << "Successor(s): "; 436 ListSeparator LS; 437 for (auto *Succ : getSuccessors()) 438 O << LS << Succ->getName(); 439 O << '\n'; 440 } 441 } 442 443 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 444 VPSlotTracker &SlotTracker) const { 445 O << Indent << getName() << ":\n"; 446 447 auto RecipeIndent = Indent + " "; 448 for (const VPRecipeBase &Recipe : *this) { 449 Recipe.print(O, RecipeIndent, SlotTracker); 450 O << '\n'; 451 } 452 453 printSuccessors(O, Indent); 454 } 455 #endif 456 457 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 458 for (VPBlockBase *Block : depth_first(Entry)) 459 // Drop all references in VPBasicBlocks and replace all uses with 460 // DummyValue. 461 Block->dropAllReferences(NewValue); 462 } 463 464 void VPRegionBlock::execute(VPTransformState *State) { 465 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 466 467 if (!isReplicator()) { 468 // Create and register the new vector loop. 469 Loop *PrevLoop = State->CurrentVectorLoop; 470 State->CurrentVectorLoop = State->LI->AllocateLoop(); 471 BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()]; 472 Loop *ParentLoop = State->LI->getLoopFor(VectorPH); 473 474 // Insert the new loop into the loop nest and register the new basic blocks 475 // before calling any utilities such as SCEV that require valid LoopInfo. 476 if (ParentLoop) 477 ParentLoop->addChildLoop(State->CurrentVectorLoop); 478 else 479 State->LI->addTopLevelLoop(State->CurrentVectorLoop); 480 481 // Visit the VPBlocks connected to "this", starting from it. 482 for (VPBlockBase *Block : RPOT) { 483 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 484 Block->execute(State); 485 } 486 487 State->CurrentVectorLoop = PrevLoop; 488 return; 489 } 490 491 assert(!State->Instance && "Replicating a Region with non-null instance."); 492 493 // Enter replicating mode. 494 State->Instance = VPIteration(0, 0); 495 496 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 497 State->Instance->Part = Part; 498 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 499 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 500 ++Lane) { 501 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 502 // Visit the VPBlocks connected to \p this, starting from it. 503 for (VPBlockBase *Block : RPOT) { 504 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 505 Block->execute(State); 506 } 507 } 508 } 509 510 // Exit replicating mode. 511 State->Instance.reset(); 512 } 513 514 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 515 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 516 VPSlotTracker &SlotTracker) const { 517 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 518 auto NewIndent = Indent + " "; 519 for (auto *BlockBase : depth_first(Entry)) { 520 O << '\n'; 521 BlockBase->print(O, NewIndent, SlotTracker); 522 } 523 O << Indent << "}\n"; 524 525 printSuccessors(O, Indent); 526 } 527 #endif 528 529 bool VPRecipeBase::mayWriteToMemory() const { 530 switch (getVPDefID()) { 531 case VPWidenMemoryInstructionSC: { 532 return cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 533 } 534 case VPReplicateSC: 535 case VPWidenCallSC: 536 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 537 ->mayWriteToMemory(); 538 case VPBranchOnMaskSC: 539 return false; 540 case VPWidenIntOrFpInductionSC: 541 case VPWidenCanonicalIVSC: 542 case VPWidenPHISC: 543 case VPBlendSC: 544 case VPWidenSC: 545 case VPWidenGEPSC: 546 case VPReductionSC: 547 case VPWidenSelectSC: { 548 const Instruction *I = 549 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 550 (void)I; 551 assert((!I || !I->mayWriteToMemory()) && 552 "underlying instruction may write to memory"); 553 return false; 554 } 555 default: 556 return true; 557 } 558 } 559 560 bool VPRecipeBase::mayReadFromMemory() const { 561 switch (getVPDefID()) { 562 case VPWidenMemoryInstructionSC: { 563 return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 564 } 565 case VPReplicateSC: 566 case VPWidenCallSC: 567 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 568 ->mayReadFromMemory(); 569 case VPBranchOnMaskSC: 570 return false; 571 case VPWidenIntOrFpInductionSC: 572 case VPWidenCanonicalIVSC: 573 case VPWidenPHISC: 574 case VPBlendSC: 575 case VPWidenSC: 576 case VPWidenGEPSC: 577 case VPReductionSC: 578 case VPWidenSelectSC: { 579 const Instruction *I = 580 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 581 (void)I; 582 assert((!I || !I->mayReadFromMemory()) && 583 "underlying instruction may read from memory"); 584 return false; 585 } 586 default: 587 return true; 588 } 589 } 590 591 bool VPRecipeBase::mayHaveSideEffects() const { 592 switch (getVPDefID()) { 593 case VPBranchOnMaskSC: 594 return false; 595 case VPWidenIntOrFpInductionSC: 596 case VPWidenPointerInductionSC: 597 case VPWidenCanonicalIVSC: 598 case VPWidenPHISC: 599 case VPBlendSC: 600 case VPWidenSC: 601 case VPWidenGEPSC: 602 case VPReductionSC: 603 case VPWidenSelectSC: 604 case VPScalarIVStepsSC: { 605 const Instruction *I = 606 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 607 (void)I; 608 assert((!I || !I->mayHaveSideEffects()) && 609 "underlying instruction has side-effects"); 610 return false; 611 } 612 case VPReplicateSC: { 613 auto *R = cast<VPReplicateRecipe>(this); 614 return R->getUnderlyingInstr()->mayHaveSideEffects(); 615 } 616 default: 617 return true; 618 } 619 } 620 621 void VPLiveOut::fixPhi(VPlan &Plan, VPTransformState &State) { 622 auto Lane = VPLane::getLastLaneForVF(State.VF); 623 VPValue *ExitValue = getOperand(0); 624 if (Plan.isUniformAfterVectorization(ExitValue)) 625 Lane = VPLane::getFirstLane(); 626 Phi->addIncoming(State.get(ExitValue, VPIteration(State.UF - 1, Lane)), 627 State.Builder.GetInsertBlock()); 628 } 629 630 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 631 assert(!Parent && "Recipe already in some VPBasicBlock"); 632 assert(InsertPos->getParent() && 633 "Insertion position not in any VPBasicBlock"); 634 Parent = InsertPos->getParent(); 635 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 636 } 637 638 void VPRecipeBase::insertBefore(VPBasicBlock &BB, 639 iplist<VPRecipeBase>::iterator I) { 640 assert(!Parent && "Recipe already in some VPBasicBlock"); 641 assert(I == BB.end() || I->getParent() == &BB); 642 Parent = &BB; 643 BB.getRecipeList().insert(I, this); 644 } 645 646 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 647 assert(!Parent && "Recipe already in some VPBasicBlock"); 648 assert(InsertPos->getParent() && 649 "Insertion position not in any VPBasicBlock"); 650 Parent = InsertPos->getParent(); 651 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 652 } 653 654 void VPRecipeBase::removeFromParent() { 655 assert(getParent() && "Recipe not in any VPBasicBlock"); 656 getParent()->getRecipeList().remove(getIterator()); 657 Parent = nullptr; 658 } 659 660 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 661 assert(getParent() && "Recipe not in any VPBasicBlock"); 662 return getParent()->getRecipeList().erase(getIterator()); 663 } 664 665 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 666 removeFromParent(); 667 insertAfter(InsertPos); 668 } 669 670 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 671 iplist<VPRecipeBase>::iterator I) { 672 removeFromParent(); 673 insertBefore(BB, I); 674 } 675 676 void VPInstruction::generateInstruction(VPTransformState &State, 677 unsigned Part) { 678 IRBuilderBase &Builder = State.Builder; 679 Builder.SetCurrentDebugLocation(DL); 680 681 if (Instruction::isBinaryOp(getOpcode())) { 682 Value *A = State.get(getOperand(0), Part); 683 Value *B = State.get(getOperand(1), Part); 684 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 685 State.set(this, V, Part); 686 return; 687 } 688 689 switch (getOpcode()) { 690 case VPInstruction::Not: { 691 Value *A = State.get(getOperand(0), Part); 692 Value *V = Builder.CreateNot(A); 693 State.set(this, V, Part); 694 break; 695 } 696 case VPInstruction::ICmpULE: { 697 Value *IV = State.get(getOperand(0), Part); 698 Value *TC = State.get(getOperand(1), Part); 699 Value *V = Builder.CreateICmpULE(IV, TC); 700 State.set(this, V, Part); 701 break; 702 } 703 case Instruction::Select: { 704 Value *Cond = State.get(getOperand(0), Part); 705 Value *Op1 = State.get(getOperand(1), Part); 706 Value *Op2 = State.get(getOperand(2), Part); 707 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 708 State.set(this, V, Part); 709 break; 710 } 711 case VPInstruction::ActiveLaneMask: { 712 // Get first lane of vector induction variable. 713 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 714 // Get the original loop tripcount. 715 Value *ScalarTC = State.get(getOperand(1), Part); 716 717 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 718 auto *PredTy = VectorType::get(Int1Ty, State.VF); 719 Instruction *Call = Builder.CreateIntrinsic( 720 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 721 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 722 State.set(this, Call, Part); 723 break; 724 } 725 case VPInstruction::FirstOrderRecurrenceSplice: { 726 // Generate code to combine the previous and current values in vector v3. 727 // 728 // vector.ph: 729 // v_init = vector(..., ..., ..., a[-1]) 730 // br vector.body 731 // 732 // vector.body 733 // i = phi [0, vector.ph], [i+4, vector.body] 734 // v1 = phi [v_init, vector.ph], [v2, vector.body] 735 // v2 = a[i, i+1, i+2, i+3]; 736 // v3 = vector(v1(3), v2(0, 1, 2)) 737 738 // For the first part, use the recurrence phi (v1), otherwise v2. 739 auto *V1 = State.get(getOperand(0), 0); 740 Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1); 741 if (!PartMinus1->getType()->isVectorTy()) { 742 State.set(this, PartMinus1, Part); 743 } else { 744 Value *V2 = State.get(getOperand(1), Part); 745 State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part); 746 } 747 break; 748 } 749 750 case VPInstruction::CanonicalIVIncrement: 751 case VPInstruction::CanonicalIVIncrementNUW: { 752 Value *Next = nullptr; 753 if (Part == 0) { 754 bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW; 755 auto *Phi = State.get(getOperand(0), 0); 756 // The loop step is equal to the vectorization factor (num of SIMD 757 // elements) times the unroll factor (num of SIMD instructions). 758 Value *Step = 759 createStepForVF(Builder, Phi->getType(), State.VF, State.UF); 760 Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false); 761 } else { 762 Next = State.get(this, 0); 763 } 764 765 State.set(this, Next, Part); 766 break; 767 } 768 case VPInstruction::BranchOnCond: { 769 if (Part != 0) 770 break; 771 Value *Cond = State.get(getOperand(0), VPIteration(Part, 0)); 772 VPRegionBlock *ParentRegion = getParent()->getParent(); 773 VPBasicBlock *Header = ParentRegion->getEntryBasicBlock(); 774 775 // Replace the temporary unreachable terminator with a new conditional 776 // branch, hooking it up to backward destination for exiting blocks now and 777 // to forward destination(s) later when they are created. 778 BranchInst *CondBr = 779 Builder.CreateCondBr(Cond, Builder.GetInsertBlock(), nullptr); 780 781 if (getParent()->isExiting()) 782 CondBr->setSuccessor(1, State.CFG.VPBB2IRBB[Header]); 783 784 CondBr->setSuccessor(0, nullptr); 785 Builder.GetInsertBlock()->getTerminator()->eraseFromParent(); 786 break; 787 } 788 case VPInstruction::BranchOnCount: { 789 if (Part != 0) 790 break; 791 // First create the compare. 792 Value *IV = State.get(getOperand(0), Part); 793 Value *TC = State.get(getOperand(1), Part); 794 Value *Cond = Builder.CreateICmpEQ(IV, TC); 795 796 // Now create the branch. 797 auto *Plan = getParent()->getPlan(); 798 VPRegionBlock *TopRegion = Plan->getVectorLoopRegion(); 799 VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock(); 800 // TODO: Once the exit block is modeled in VPlan, use it instead of going 801 // through State.CFG.ExitBB. 802 BasicBlock *Exit = State.CFG.ExitBB; 803 804 Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]); 805 Builder.GetInsertBlock()->getTerminator()->eraseFromParent(); 806 break; 807 } 808 default: 809 llvm_unreachable("Unsupported opcode for instruction"); 810 } 811 } 812 813 void VPInstruction::execute(VPTransformState &State) { 814 assert(!State.Instance && "VPInstruction executing an Instance"); 815 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder); 816 State.Builder.setFastMathFlags(FMF); 817 for (unsigned Part = 0; Part < State.UF; ++Part) 818 generateInstruction(State, Part); 819 } 820 821 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 822 void VPInstruction::dump() const { 823 VPSlotTracker SlotTracker(getParent()->getPlan()); 824 print(dbgs(), "", SlotTracker); 825 } 826 827 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 828 VPSlotTracker &SlotTracker) const { 829 O << Indent << "EMIT "; 830 831 if (hasResult()) { 832 printAsOperand(O, SlotTracker); 833 O << " = "; 834 } 835 836 switch (getOpcode()) { 837 case VPInstruction::Not: 838 O << "not"; 839 break; 840 case VPInstruction::ICmpULE: 841 O << "icmp ule"; 842 break; 843 case VPInstruction::SLPLoad: 844 O << "combined load"; 845 break; 846 case VPInstruction::SLPStore: 847 O << "combined store"; 848 break; 849 case VPInstruction::ActiveLaneMask: 850 O << "active lane mask"; 851 break; 852 case VPInstruction::FirstOrderRecurrenceSplice: 853 O << "first-order splice"; 854 break; 855 case VPInstruction::CanonicalIVIncrement: 856 O << "VF * UF + "; 857 break; 858 case VPInstruction::CanonicalIVIncrementNUW: 859 O << "VF * UF +(nuw) "; 860 break; 861 case VPInstruction::BranchOnCond: 862 O << "branch-on-cond"; 863 break; 864 case VPInstruction::BranchOnCount: 865 O << "branch-on-count "; 866 break; 867 default: 868 O << Instruction::getOpcodeName(getOpcode()); 869 } 870 871 O << FMF; 872 873 for (const VPValue *Operand : operands()) { 874 O << " "; 875 Operand->printAsOperand(O, SlotTracker); 876 } 877 878 if (DL) { 879 O << ", !dbg "; 880 DL.print(O); 881 } 882 } 883 #endif 884 885 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) { 886 // Make sure the VPInstruction is a floating-point operation. 887 assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul || 888 Opcode == Instruction::FNeg || Opcode == Instruction::FSub || 889 Opcode == Instruction::FDiv || Opcode == Instruction::FRem || 890 Opcode == Instruction::FCmp) && 891 "this op can't take fast-math flags"); 892 FMF = FMFNew; 893 } 894 895 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV, 896 Value *CanonicalIVStartValue, 897 VPTransformState &State) { 898 // Check if the trip count is needed, and if so build it. 899 if (TripCount && TripCount->getNumUsers()) { 900 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 901 State.set(TripCount, TripCountV, Part); 902 } 903 904 // Check if the backedge taken count is needed, and if so build it. 905 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 906 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 907 auto *TCMO = Builder.CreateSub(TripCountV, 908 ConstantInt::get(TripCountV->getType(), 1), 909 "trip.count.minus.1"); 910 auto VF = State.VF; 911 Value *VTCMO = 912 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 913 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 914 State.set(BackedgeTakenCount, VTCMO, Part); 915 } 916 917 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 918 State.set(&VectorTripCount, VectorTripCountV, Part); 919 920 // When vectorizing the epilogue loop, the canonical induction start value 921 // needs to be changed from zero to the value after the main vector loop. 922 if (CanonicalIVStartValue) { 923 VPValue *VPV = getOrAddExternalDef(CanonicalIVStartValue); 924 auto *IV = getCanonicalIV(); 925 assert(all_of(IV->users(), 926 [](const VPUser *U) { 927 if (isa<VPScalarIVStepsRecipe>(U)) 928 return true; 929 auto *VPI = cast<VPInstruction>(U); 930 return VPI->getOpcode() == 931 VPInstruction::CanonicalIVIncrement || 932 VPI->getOpcode() == 933 VPInstruction::CanonicalIVIncrementNUW; 934 }) && 935 "the canonical IV should only be used by its increments or " 936 "ScalarIVSteps when " 937 "resetting the start value"); 938 IV->setOperand(0, VPV); 939 } 940 } 941 942 /// Generate the code inside the preheader and body of the vectorized loop. 943 /// Assumes a single pre-header basic-block was created for this. Introduce 944 /// additional basic-blocks as needed, and fill them all. 945 void VPlan::execute(VPTransformState *State) { 946 // Set the reverse mapping from VPValues to Values for code generation. 947 for (auto &Entry : Value2VPValue) 948 State->VPValue2Value[Entry.second] = Entry.first; 949 950 // Initialize CFG state. 951 State->CFG.PrevVPBB = nullptr; 952 State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor(); 953 BasicBlock *VectorPreHeader = State->CFG.PrevBB; 954 State->Builder.SetInsertPoint(VectorPreHeader->getTerminator()); 955 956 // Generate code in the loop pre-header and body. 957 for (VPBlockBase *Block : depth_first(Entry)) 958 Block->execute(State); 959 960 VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock(); 961 BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB]; 962 963 // Fix the latch value of canonical, reduction and first-order recurrences 964 // phis in the vector loop. 965 VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock(); 966 for (VPRecipeBase &R : Header->phis()) { 967 // Skip phi-like recipes that generate their backedege values themselves. 968 if (isa<VPWidenPHIRecipe>(&R)) 969 continue; 970 971 if (isa<VPWidenPointerInductionRecipe>(&R) || 972 isa<VPWidenIntOrFpInductionRecipe>(&R)) { 973 PHINode *Phi = nullptr; 974 if (isa<VPWidenIntOrFpInductionRecipe>(&R)) { 975 Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0)); 976 } else { 977 auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R); 978 // TODO: Split off the case that all users of a pointer phi are scalar 979 // from the VPWidenPointerInductionRecipe. 980 if (WidenPhi->onlyScalarsGenerated(State->VF)) 981 continue; 982 983 auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0)); 984 Phi = cast<PHINode>(GEP->getPointerOperand()); 985 } 986 987 Phi->setIncomingBlock(1, VectorLatchBB); 988 989 // Move the last step to the end of the latch block. This ensures 990 // consistent placement of all induction updates. 991 Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1)); 992 Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode()); 993 continue; 994 } 995 996 auto *PhiR = cast<VPHeaderPHIRecipe>(&R); 997 // For canonical IV, first-order recurrences and in-order reduction phis, 998 // only a single part is generated, which provides the last part from the 999 // previous iteration. For non-ordered reductions all UF parts are 1000 // generated. 1001 bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) || 1002 isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) || 1003 cast<VPReductionPHIRecipe>(PhiR)->isOrdered(); 1004 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 1005 1006 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1007 Value *Phi = State->get(PhiR, Part); 1008 Value *Val = State->get(PhiR->getBackedgeValue(), 1009 SinglePartNeeded ? State->UF - 1 : Part); 1010 cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB); 1011 } 1012 } 1013 1014 // We do not attempt to preserve DT for outer loop vectorization currently. 1015 if (!EnableVPlanNativePath) { 1016 BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header]; 1017 State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader); 1018 updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB, 1019 State->CFG.ExitBB); 1020 } 1021 } 1022 1023 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1024 LLVM_DUMP_METHOD 1025 void VPlan::print(raw_ostream &O) const { 1026 VPSlotTracker SlotTracker(this); 1027 1028 O << "VPlan '" << Name << "' {"; 1029 1030 if (VectorTripCount.getNumUsers() > 0) { 1031 O << "\nLive-in "; 1032 VectorTripCount.printAsOperand(O, SlotTracker); 1033 O << " = vector-trip-count\n"; 1034 } 1035 1036 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 1037 O << "\nLive-in "; 1038 BackedgeTakenCount->printAsOperand(O, SlotTracker); 1039 O << " = backedge-taken count\n"; 1040 } 1041 1042 for (const VPBlockBase *Block : depth_first(getEntry())) { 1043 O << '\n'; 1044 Block->print(O, "", SlotTracker); 1045 } 1046 1047 if (!LiveOuts.empty()) 1048 O << "\n"; 1049 for (auto &KV : LiveOuts) { 1050 O << "Live-out "; 1051 KV.second->getPhi()->printAsOperand(O); 1052 O << " = "; 1053 KV.second->getOperand(0)->printAsOperand(O, SlotTracker); 1054 O << "\n"; 1055 } 1056 1057 O << "}\n"; 1058 } 1059 1060 LLVM_DUMP_METHOD 1061 void VPlan::printDOT(raw_ostream &O) const { 1062 VPlanPrinter Printer(O, *this); 1063 Printer.dump(); 1064 } 1065 1066 LLVM_DUMP_METHOD 1067 void VPlan::dump() const { print(dbgs()); } 1068 #endif 1069 1070 void VPlan::addLiveOut(PHINode *PN, VPValue *V) { 1071 assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists"); 1072 LiveOuts.insert({PN, new VPLiveOut(PN, V)}); 1073 } 1074 1075 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB, 1076 BasicBlock *LoopLatchBB, 1077 BasicBlock *LoopExitBB) { 1078 // The vector body may be more than a single basic-block by this point. 1079 // Update the dominator tree information inside the vector body by propagating 1080 // it from header to latch, expecting only triangular control-flow, if any. 1081 BasicBlock *PostDomSucc = nullptr; 1082 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 1083 // Get the list of successors of this block. 1084 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 1085 assert(Succs.size() <= 2 && 1086 "Basic block in vector loop has more than 2 successors."); 1087 PostDomSucc = Succs[0]; 1088 if (Succs.size() == 1) { 1089 assert(PostDomSucc->getSinglePredecessor() && 1090 "PostDom successor has more than one predecessor."); 1091 DT->addNewBlock(PostDomSucc, BB); 1092 continue; 1093 } 1094 BasicBlock *InterimSucc = Succs[1]; 1095 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 1096 PostDomSucc = Succs[1]; 1097 InterimSucc = Succs[0]; 1098 } 1099 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 1100 "One successor of a basic block does not lead to the other."); 1101 assert(InterimSucc->getSinglePredecessor() && 1102 "Interim successor has more than one predecessor."); 1103 assert(PostDomSucc->hasNPredecessors(2) && 1104 "PostDom successor has more than two predecessors."); 1105 DT->addNewBlock(InterimSucc, BB); 1106 DT->addNewBlock(PostDomSucc, BB); 1107 } 1108 // Latch block is a new dominator for the loop exit. 1109 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 1110 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 1111 } 1112 1113 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1114 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 1115 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 1116 Twine(getOrCreateBID(Block)); 1117 } 1118 1119 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 1120 const std::string &Name = Block->getName(); 1121 if (!Name.empty()) 1122 return Name; 1123 return "VPB" + Twine(getOrCreateBID(Block)); 1124 } 1125 1126 void VPlanPrinter::dump() { 1127 Depth = 1; 1128 bumpIndent(0); 1129 OS << "digraph VPlan {\n"; 1130 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 1131 if (!Plan.getName().empty()) 1132 OS << "\\n" << DOT::EscapeString(Plan.getName()); 1133 if (Plan.BackedgeTakenCount) { 1134 OS << ", where:\\n"; 1135 Plan.BackedgeTakenCount->print(OS, SlotTracker); 1136 OS << " := BackedgeTakenCount"; 1137 } 1138 OS << "\"]\n"; 1139 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 1140 OS << "edge [fontname=Courier, fontsize=30]\n"; 1141 OS << "compound=true\n"; 1142 1143 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 1144 dumpBlock(Block); 1145 1146 OS << "}\n"; 1147 } 1148 1149 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1150 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1151 dumpBasicBlock(BasicBlock); 1152 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1153 dumpRegion(Region); 1154 else 1155 llvm_unreachable("Unsupported kind of VPBlock."); 1156 } 1157 1158 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1159 bool Hidden, const Twine &Label) { 1160 // Due to "dot" we print an edge between two regions as an edge between the 1161 // exiting basic block and the entry basic of the respective regions. 1162 const VPBlockBase *Tail = From->getExitingBasicBlock(); 1163 const VPBlockBase *Head = To->getEntryBasicBlock(); 1164 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1165 OS << " [ label=\"" << Label << '\"'; 1166 if (Tail != From) 1167 OS << " ltail=" << getUID(From); 1168 if (Head != To) 1169 OS << " lhead=" << getUID(To); 1170 if (Hidden) 1171 OS << "; splines=none"; 1172 OS << "]\n"; 1173 } 1174 1175 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1176 auto &Successors = Block->getSuccessors(); 1177 if (Successors.size() == 1) 1178 drawEdge(Block, Successors.front(), false, ""); 1179 else if (Successors.size() == 2) { 1180 drawEdge(Block, Successors.front(), false, "T"); 1181 drawEdge(Block, Successors.back(), false, "F"); 1182 } else { 1183 unsigned SuccessorNumber = 0; 1184 for (auto *Successor : Successors) 1185 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1186 } 1187 } 1188 1189 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1190 // Implement dot-formatted dump by performing plain-text dump into the 1191 // temporary storage followed by some post-processing. 1192 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1193 bumpIndent(1); 1194 std::string Str; 1195 raw_string_ostream SS(Str); 1196 // Use no indentation as we need to wrap the lines into quotes ourselves. 1197 BasicBlock->print(SS, "", SlotTracker); 1198 1199 // We need to process each line of the output separately, so split 1200 // single-string plain-text dump. 1201 SmallVector<StringRef, 0> Lines; 1202 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1203 1204 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1205 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1206 }; 1207 1208 // Don't need the "+" after the last line. 1209 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1210 EmitLine(Line, " +\n"); 1211 EmitLine(Lines.back(), "\n"); 1212 1213 bumpIndent(-1); 1214 OS << Indent << "]\n"; 1215 1216 dumpEdges(BasicBlock); 1217 } 1218 1219 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1220 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1221 bumpIndent(1); 1222 OS << Indent << "fontname=Courier\n" 1223 << Indent << "label=\"" 1224 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1225 << DOT::EscapeString(Region->getName()) << "\"\n"; 1226 // Dump the blocks of the region. 1227 assert(Region->getEntry() && "Region contains no inner blocks."); 1228 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 1229 dumpBlock(Block); 1230 bumpIndent(-1); 1231 OS << Indent << "}\n"; 1232 dumpEdges(Region); 1233 } 1234 1235 void VPlanIngredient::print(raw_ostream &O) const { 1236 if (auto *Inst = dyn_cast<Instruction>(V)) { 1237 if (!Inst->getType()->isVoidTy()) { 1238 Inst->printAsOperand(O, false); 1239 O << " = "; 1240 } 1241 O << Inst->getOpcodeName() << " "; 1242 unsigned E = Inst->getNumOperands(); 1243 if (E > 0) { 1244 Inst->getOperand(0)->printAsOperand(O, false); 1245 for (unsigned I = 1; I < E; ++I) 1246 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1247 } 1248 } else // !Inst 1249 V->printAsOperand(O, false); 1250 } 1251 1252 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 1253 VPSlotTracker &SlotTracker) const { 1254 O << Indent << "WIDEN-CALL "; 1255 1256 auto *CI = cast<CallInst>(getUnderlyingInstr()); 1257 if (CI->getType()->isVoidTy()) 1258 O << "void "; 1259 else { 1260 printAsOperand(O, SlotTracker); 1261 O << " = "; 1262 } 1263 1264 O << "call @" << CI->getCalledFunction()->getName() << "("; 1265 printOperands(O, SlotTracker); 1266 O << ")"; 1267 } 1268 1269 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 1270 VPSlotTracker &SlotTracker) const { 1271 O << Indent << "WIDEN-SELECT "; 1272 printAsOperand(O, SlotTracker); 1273 O << " = select "; 1274 getOperand(0)->printAsOperand(O, SlotTracker); 1275 O << ", "; 1276 getOperand(1)->printAsOperand(O, SlotTracker); 1277 O << ", "; 1278 getOperand(2)->printAsOperand(O, SlotTracker); 1279 O << (InvariantCond ? " (condition is loop invariant)" : ""); 1280 } 1281 1282 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 1283 VPSlotTracker &SlotTracker) const { 1284 O << Indent << "WIDEN "; 1285 printAsOperand(O, SlotTracker); 1286 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 1287 printOperands(O, SlotTracker); 1288 } 1289 1290 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1291 VPSlotTracker &SlotTracker) const { 1292 O << Indent << "WIDEN-INDUCTION"; 1293 if (getTruncInst()) { 1294 O << "\\l\""; 1295 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 1296 O << " +\n" << Indent << "\" "; 1297 getVPValue(0)->printAsOperand(O, SlotTracker); 1298 } else 1299 O << " " << VPlanIngredient(IV); 1300 1301 O << ", "; 1302 getStepValue()->printAsOperand(O, SlotTracker); 1303 } 1304 1305 void VPWidenPointerInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1306 VPSlotTracker &SlotTracker) const { 1307 O << Indent << "EMIT "; 1308 printAsOperand(O, SlotTracker); 1309 O << " = WIDEN-POINTER-INDUCTION "; 1310 getStartValue()->printAsOperand(O, SlotTracker); 1311 O << ", " << *IndDesc.getStep(); 1312 } 1313 1314 #endif 1315 1316 bool VPWidenIntOrFpInductionRecipe::isCanonical() const { 1317 auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue()); 1318 auto *StepC = dyn_cast<SCEVConstant>(getInductionDescriptor().getStep()); 1319 return StartC && StartC->isZero() && StepC && StepC->isOne(); 1320 } 1321 1322 VPCanonicalIVPHIRecipe *VPScalarIVStepsRecipe::getCanonicalIV() const { 1323 return cast<VPCanonicalIVPHIRecipe>(getOperand(0)); 1324 } 1325 1326 bool VPScalarIVStepsRecipe::isCanonical() const { 1327 auto *CanIV = getCanonicalIV(); 1328 // The start value of the steps-recipe must match the start value of the 1329 // canonical induction and it must step by 1. 1330 if (CanIV->getStartValue() != getStartValue()) 1331 return false; 1332 auto *StepVPV = getStepValue(); 1333 if (StepVPV->getDef()) 1334 return false; 1335 auto *StepC = dyn_cast_or_null<ConstantInt>(StepVPV->getLiveInIRValue()); 1336 return StepC && StepC->isOne(); 1337 } 1338 1339 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1340 void VPScalarIVStepsRecipe::print(raw_ostream &O, const Twine &Indent, 1341 VPSlotTracker &SlotTracker) const { 1342 O << Indent; 1343 printAsOperand(O, SlotTracker); 1344 O << Indent << "= SCALAR-STEPS "; 1345 printOperands(O, SlotTracker); 1346 } 1347 1348 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 1349 VPSlotTracker &SlotTracker) const { 1350 O << Indent << "WIDEN-GEP "; 1351 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 1352 size_t IndicesNumber = IsIndexLoopInvariant.size(); 1353 for (size_t I = 0; I < IndicesNumber; ++I) 1354 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 1355 1356 O << " "; 1357 printAsOperand(O, SlotTracker); 1358 O << " = getelementptr "; 1359 printOperands(O, SlotTracker); 1360 } 1361 1362 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1363 VPSlotTracker &SlotTracker) const { 1364 O << Indent << "WIDEN-PHI "; 1365 1366 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue()); 1367 // Unless all incoming values are modeled in VPlan print the original PHI 1368 // directly. 1369 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming 1370 // values as VPValues. 1371 if (getNumOperands() != OriginalPhi->getNumOperands()) { 1372 O << VPlanIngredient(OriginalPhi); 1373 return; 1374 } 1375 1376 printAsOperand(O, SlotTracker); 1377 O << " = phi "; 1378 printOperands(O, SlotTracker); 1379 } 1380 1381 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 1382 VPSlotTracker &SlotTracker) const { 1383 O << Indent << "BLEND "; 1384 Phi->printAsOperand(O, false); 1385 O << " ="; 1386 if (getNumIncomingValues() == 1) { 1387 // Not a User of any mask: not really blending, this is a 1388 // single-predecessor phi. 1389 O << " "; 1390 getIncomingValue(0)->printAsOperand(O, SlotTracker); 1391 } else { 1392 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 1393 O << " "; 1394 getIncomingValue(I)->printAsOperand(O, SlotTracker); 1395 O << "/"; 1396 getMask(I)->printAsOperand(O, SlotTracker); 1397 } 1398 } 1399 } 1400 1401 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 1402 VPSlotTracker &SlotTracker) const { 1403 O << Indent << "REDUCE "; 1404 printAsOperand(O, SlotTracker); 1405 O << " = "; 1406 getChainOp()->printAsOperand(O, SlotTracker); 1407 O << " +"; 1408 if (isa<FPMathOperator>(getUnderlyingInstr())) 1409 O << getUnderlyingInstr()->getFastMathFlags(); 1410 O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " ("; 1411 getVecOp()->printAsOperand(O, SlotTracker); 1412 if (getCondOp()) { 1413 O << ", "; 1414 getCondOp()->printAsOperand(O, SlotTracker); 1415 } 1416 O << ")"; 1417 if (RdxDesc->IntermediateStore) 1418 O << " (with final reduction value stored in invariant address sank " 1419 "outside of loop)"; 1420 } 1421 1422 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 1423 VPSlotTracker &SlotTracker) const { 1424 O << Indent << (IsUniform ? "CLONE " : "REPLICATE "); 1425 1426 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 1427 printAsOperand(O, SlotTracker); 1428 O << " = "; 1429 } 1430 if (auto *CB = dyn_cast<CallBase>(getUnderlyingInstr())) { 1431 O << "call @" << CB->getCalledFunction()->getName() << "("; 1432 interleaveComma(make_range(op_begin(), op_begin() + (getNumOperands() - 1)), 1433 O, [&O, &SlotTracker](VPValue *Op) { 1434 Op->printAsOperand(O, SlotTracker); 1435 }); 1436 O << ")"; 1437 } else { 1438 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 1439 printOperands(O, SlotTracker); 1440 } 1441 1442 if (AlsoPack) 1443 O << " (S->V)"; 1444 } 1445 1446 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1447 VPSlotTracker &SlotTracker) const { 1448 O << Indent << "PHI-PREDICATED-INSTRUCTION "; 1449 printAsOperand(O, SlotTracker); 1450 O << " = "; 1451 printOperands(O, SlotTracker); 1452 } 1453 1454 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 1455 VPSlotTracker &SlotTracker) const { 1456 O << Indent << "WIDEN "; 1457 1458 if (!isStore()) { 1459 getVPSingleValue()->printAsOperand(O, SlotTracker); 1460 O << " = "; 1461 } 1462 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 1463 1464 printOperands(O, SlotTracker); 1465 } 1466 #endif 1467 1468 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) { 1469 Value *Start = getStartValue()->getLiveInIRValue(); 1470 PHINode *EntryPart = PHINode::Create( 1471 Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt()); 1472 1473 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this); 1474 EntryPart->addIncoming(Start, VectorPH); 1475 EntryPart->setDebugLoc(DL); 1476 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 1477 State.set(this, EntryPart, Part); 1478 } 1479 1480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1481 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1482 VPSlotTracker &SlotTracker) const { 1483 O << Indent << "EMIT "; 1484 printAsOperand(O, SlotTracker); 1485 O << " = CANONICAL-INDUCTION"; 1486 } 1487 #endif 1488 1489 bool VPWidenPointerInductionRecipe::onlyScalarsGenerated(ElementCount VF) { 1490 bool IsUniform = vputils::onlyFirstLaneUsed(this); 1491 return all_of(users(), 1492 [&](const VPUser *U) { return U->usesScalars(this); }) && 1493 (IsUniform || !VF.isScalable()); 1494 } 1495 1496 void VPExpandSCEVRecipe::execute(VPTransformState &State) { 1497 assert(!State.Instance && "cannot be used in per-lane"); 1498 const DataLayout &DL = State.CFG.PrevBB->getModule()->getDataLayout(); 1499 SCEVExpander Exp(SE, DL, "induction"); 1500 1501 Value *Res = Exp.expandCodeFor(Expr, Expr->getType(), 1502 &*State.Builder.GetInsertPoint()); 1503 1504 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) 1505 State.set(this, Res, Part); 1506 } 1507 1508 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1509 void VPExpandSCEVRecipe::print(raw_ostream &O, const Twine &Indent, 1510 VPSlotTracker &SlotTracker) const { 1511 O << Indent << "EMIT "; 1512 getVPSingleValue()->printAsOperand(O, SlotTracker); 1513 O << " = EXPAND SCEV " << *Expr; 1514 } 1515 #endif 1516 1517 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 1518 Value *CanonicalIV = State.get(getOperand(0), 0); 1519 Type *STy = CanonicalIV->getType(); 1520 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 1521 ElementCount VF = State.VF; 1522 Value *VStart = VF.isScalar() 1523 ? CanonicalIV 1524 : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast"); 1525 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 1526 Value *VStep = createStepForVF(Builder, STy, VF, Part); 1527 if (VF.isVector()) { 1528 VStep = Builder.CreateVectorSplat(VF, VStep); 1529 VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType())); 1530 } 1531 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1532 State.set(this, CanonicalVectorIV, Part); 1533 } 1534 } 1535 1536 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1537 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1538 VPSlotTracker &SlotTracker) const { 1539 O << Indent << "EMIT "; 1540 printAsOperand(O, SlotTracker); 1541 O << " = WIDEN-CANONICAL-INDUCTION "; 1542 printOperands(O, SlotTracker); 1543 } 1544 #endif 1545 1546 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) { 1547 auto &Builder = State.Builder; 1548 // Create a vector from the initial value. 1549 auto *VectorInit = getStartValue()->getLiveInIRValue(); 1550 1551 Type *VecTy = State.VF.isScalar() 1552 ? VectorInit->getType() 1553 : VectorType::get(VectorInit->getType(), State.VF); 1554 1555 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this); 1556 if (State.VF.isVector()) { 1557 auto *IdxTy = Builder.getInt32Ty(); 1558 auto *One = ConstantInt::get(IdxTy, 1); 1559 IRBuilder<>::InsertPointGuard Guard(Builder); 1560 Builder.SetInsertPoint(VectorPH->getTerminator()); 1561 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF); 1562 auto *LastIdx = Builder.CreateSub(RuntimeVF, One); 1563 VectorInit = Builder.CreateInsertElement( 1564 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init"); 1565 } 1566 1567 // Create a phi node for the new recurrence. 1568 PHINode *EntryPart = PHINode::Create( 1569 VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt()); 1570 EntryPart->addIncoming(VectorInit, VectorPH); 1571 State.set(this, EntryPart, 0); 1572 } 1573 1574 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1575 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent, 1576 VPSlotTracker &SlotTracker) const { 1577 O << Indent << "FIRST-ORDER-RECURRENCE-PHI "; 1578 printAsOperand(O, SlotTracker); 1579 O << " = phi "; 1580 printOperands(O, SlotTracker); 1581 } 1582 #endif 1583 1584 void VPReductionPHIRecipe::execute(VPTransformState &State) { 1585 PHINode *PN = cast<PHINode>(getUnderlyingValue()); 1586 auto &Builder = State.Builder; 1587 1588 // In order to support recurrences we need to be able to vectorize Phi nodes. 1589 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 1590 // stage #1: We create a new vector PHI node with no incoming edges. We'll use 1591 // this value when we vectorize all of the instructions that use the PHI. 1592 bool ScalarPHI = State.VF.isScalar() || IsInLoop; 1593 Type *VecTy = 1594 ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF); 1595 1596 BasicBlock *HeaderBB = State.CFG.PrevBB; 1597 assert(State.CurrentVectorLoop->getHeader() == HeaderBB && 1598 "recipe must be in the vector loop header"); 1599 unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF; 1600 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1601 Value *EntryPart = 1602 PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt()); 1603 State.set(this, EntryPart, Part); 1604 } 1605 1606 BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this); 1607 1608 // Reductions do not have to start at zero. They can start with 1609 // any loop invariant values. 1610 VPValue *StartVPV = getStartValue(); 1611 Value *StartV = StartVPV->getLiveInIRValue(); 1612 1613 Value *Iden = nullptr; 1614 RecurKind RK = RdxDesc.getRecurrenceKind(); 1615 if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) || 1616 RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) { 1617 // MinMax reduction have the start value as their identify. 1618 if (ScalarPHI) { 1619 Iden = StartV; 1620 } else { 1621 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1622 Builder.SetInsertPoint(VectorPH->getTerminator()); 1623 StartV = Iden = 1624 Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident"); 1625 } 1626 } else { 1627 Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(), 1628 RdxDesc.getFastMathFlags()); 1629 1630 if (!ScalarPHI) { 1631 Iden = Builder.CreateVectorSplat(State.VF, Iden); 1632 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1633 Builder.SetInsertPoint(VectorPH->getTerminator()); 1634 Constant *Zero = Builder.getInt32(0); 1635 StartV = Builder.CreateInsertElement(Iden, StartV, Zero); 1636 } 1637 } 1638 1639 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1640 Value *EntryPart = State.get(this, Part); 1641 // Make sure to add the reduction start value only to the 1642 // first unroll part. 1643 Value *StartVal = (Part == 0) ? StartV : Iden; 1644 cast<PHINode>(EntryPart)->addIncoming(StartVal, VectorPH); 1645 } 1646 } 1647 1648 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1649 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1650 VPSlotTracker &SlotTracker) const { 1651 O << Indent << "WIDEN-REDUCTION-PHI "; 1652 1653 printAsOperand(O, SlotTracker); 1654 O << " = phi "; 1655 printOperands(O, SlotTracker); 1656 } 1657 #endif 1658 1659 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1660 1661 void VPValue::replaceAllUsesWith(VPValue *New) { 1662 for (unsigned J = 0; J < getNumUsers();) { 1663 VPUser *User = Users[J]; 1664 unsigned NumUsers = getNumUsers(); 1665 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1666 if (User->getOperand(I) == this) 1667 User->setOperand(I, New); 1668 // If a user got removed after updating the current user, the next user to 1669 // update will be moved to the current position, so we only need to 1670 // increment the index if the number of users did not change. 1671 if (NumUsers == getNumUsers()) 1672 J++; 1673 } 1674 } 1675 1676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1677 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1678 if (const Value *UV = getUnderlyingValue()) { 1679 OS << "ir<"; 1680 UV->printAsOperand(OS, false); 1681 OS << ">"; 1682 return; 1683 } 1684 1685 unsigned Slot = Tracker.getSlot(this); 1686 if (Slot == unsigned(-1)) 1687 OS << "<badref>"; 1688 else 1689 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1690 } 1691 1692 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1693 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1694 Op->printAsOperand(O, SlotTracker); 1695 }); 1696 } 1697 #endif 1698 1699 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1700 Old2NewTy &Old2New, 1701 InterleavedAccessInfo &IAI) { 1702 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1703 for (VPBlockBase *Base : RPOT) { 1704 visitBlock(Base, Old2New, IAI); 1705 } 1706 } 1707 1708 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1709 InterleavedAccessInfo &IAI) { 1710 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1711 for (VPRecipeBase &VPI : *VPBB) { 1712 if (isa<VPHeaderPHIRecipe>(&VPI)) 1713 continue; 1714 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1715 auto *VPInst = cast<VPInstruction>(&VPI); 1716 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1717 auto *IG = IAI.getInterleaveGroup(Inst); 1718 if (!IG) 1719 continue; 1720 1721 auto NewIGIter = Old2New.find(IG); 1722 if (NewIGIter == Old2New.end()) 1723 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1724 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1725 1726 if (Inst == IG->getInsertPos()) 1727 Old2New[IG]->setInsertPos(VPInst); 1728 1729 InterleaveGroupMap[VPInst] = Old2New[IG]; 1730 InterleaveGroupMap[VPInst]->insertMember( 1731 VPInst, IG->getIndex(Inst), 1732 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1733 : IG->getFactor())); 1734 } 1735 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1736 visitRegion(Region, Old2New, IAI); 1737 else 1738 llvm_unreachable("Unsupported kind of VPBlock."); 1739 } 1740 1741 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1742 InterleavedAccessInfo &IAI) { 1743 Old2NewTy Old2New; 1744 visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI); 1745 } 1746 1747 void VPSlotTracker::assignSlot(const VPValue *V) { 1748 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1749 Slots[V] = NextSlot++; 1750 } 1751 1752 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1753 1754 for (const auto &P : Plan.VPExternalDefs) 1755 assignSlot(P.second); 1756 1757 assignSlot(&Plan.VectorTripCount); 1758 if (Plan.BackedgeTakenCount) 1759 assignSlot(Plan.BackedgeTakenCount); 1760 1761 ReversePostOrderTraversal< 1762 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1763 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1764 Plan.getEntry())); 1765 for (const VPBasicBlock *VPBB : 1766 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1767 for (const VPRecipeBase &Recipe : *VPBB) 1768 for (VPValue *Def : Recipe.definedValues()) 1769 assignSlot(Def); 1770 } 1771 1772 bool vputils::onlyFirstLaneUsed(VPValue *Def) { 1773 return all_of(Def->users(), 1774 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); }); 1775 } 1776 1777 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr, 1778 ScalarEvolution &SE) { 1779 if (auto *E = dyn_cast<SCEVConstant>(Expr)) 1780 return Plan.getOrAddExternalDef(E->getValue()); 1781 if (auto *E = dyn_cast<SCEVUnknown>(Expr)) 1782 return Plan.getOrAddExternalDef(E->getValue()); 1783 1784 VPBasicBlock *Preheader = Plan.getEntry()->getEntryBasicBlock(); 1785 VPValue *Step = new VPExpandSCEVRecipe(Expr, SE); 1786 Preheader->appendRecipe(cast<VPRecipeBase>(Step->getDef())); 1787 return Step; 1788 } 1789