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