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