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/InstrTypes.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 <cassert> 44 #include <iterator> 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(IRBuilder<> &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 249 BasicBlock * 250 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) { 251 // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks. 252 // Pred stands for Predessor. Prev stands for Previous - last visited/created. 253 BasicBlock *PrevBB = CFG.PrevBB; 254 BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(), 255 PrevBB->getParent(), CFG.LastBB); 256 LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n'); 257 258 // Hook up the new basic block to its predecessors. 259 for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) { 260 VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock(); 261 auto &PredVPSuccessors = PredVPBB->getSuccessors(); 262 BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB]; 263 264 // In outer loop vectorization scenario, the predecessor BBlock may not yet 265 // be visited(backedge). Mark the VPBasicBlock for fixup at the end of 266 // vectorization. We do not encounter this case in inner loop vectorization 267 // as we start out by building a loop skeleton with the vector loop header 268 // and latch blocks. As a result, we never enter this function for the 269 // header block in the non VPlan-native path. 270 if (!PredBB) { 271 assert(EnableVPlanNativePath && 272 "Unexpected null predecessor in non VPlan-native path"); 273 CFG.VPBBsToFix.push_back(PredVPBB); 274 continue; 275 } 276 277 assert(PredBB && "Predecessor basic-block not found building successor."); 278 auto *PredBBTerminator = PredBB->getTerminator(); 279 LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n'); 280 if (isa<UnreachableInst>(PredBBTerminator)) { 281 assert(PredVPSuccessors.size() == 1 && 282 "Predecessor ending w/o branch must have single successor."); 283 PredBBTerminator->eraseFromParent(); 284 BranchInst::Create(NewBB, PredBB); 285 } else { 286 assert(PredVPSuccessors.size() == 2 && 287 "Predecessor ending with branch must have two successors."); 288 unsigned idx = PredVPSuccessors.front() == this ? 0 : 1; 289 assert(!PredBBTerminator->getSuccessor(idx) && 290 "Trying to reset an existing successor block."); 291 PredBBTerminator->setSuccessor(idx, NewBB); 292 } 293 } 294 return NewBB; 295 } 296 297 void VPBasicBlock::execute(VPTransformState *State) { 298 bool Replica = State->Instance && !State->Instance->isFirstIteration(); 299 VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB; 300 VPBlockBase *SingleHPred = nullptr; 301 BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible. 302 303 // 1. Create an IR basic block, or reuse the last one if possible. 304 // The last IR basic block is reused, as an optimization, in three cases: 305 // A. the first VPBB reuses the loop header BB - when PrevVPBB is null; 306 // B. when the current VPBB has a single (hierarchical) predecessor which 307 // is PrevVPBB and the latter has a single (hierarchical) successor; and 308 // C. when the current VPBB is an entry of a region replica - where PrevVPBB 309 // is the exit of this region from a previous instance, or the predecessor 310 // of this region. 311 if (PrevVPBB && /* A */ 312 !((SingleHPred = getSingleHierarchicalPredecessor()) && 313 SingleHPred->getExitBasicBlock() == PrevVPBB && 314 PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */ 315 !(Replica && getPredecessors().empty())) { /* C */ 316 NewBB = createEmptyBasicBlock(State->CFG); 317 State->Builder.SetInsertPoint(NewBB); 318 // Temporarily terminate with unreachable until CFG is rewired. 319 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 320 State->Builder.SetInsertPoint(Terminator); 321 // Register NewBB in its loop. In innermost loops its the same for all BB's. 322 Loop *L = State->LI->getLoopFor(State->CFG.LastBB); 323 L->addBasicBlockToLoop(NewBB, *State->LI); 324 State->CFG.PrevBB = NewBB; 325 } 326 327 // 2. Fill the IR basic block with IR instructions. 328 LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName() 329 << " in BB:" << NewBB->getName() << '\n'); 330 331 State->CFG.VPBB2IRBB[this] = NewBB; 332 State->CFG.PrevVPBB = this; 333 334 for (VPRecipeBase &Recipe : Recipes) 335 Recipe.execute(*State); 336 337 VPValue *CBV; 338 if (EnableVPlanNativePath && (CBV = getCondBit())) { 339 assert(CBV->getUnderlyingValue() && 340 "Unexpected null underlying value for condition bit"); 341 342 // Condition bit value in a VPBasicBlock is used as the branch selector. In 343 // the VPlan-native path case, since all branches are uniform we generate a 344 // branch instruction using the condition value from vector lane 0 and dummy 345 // successors. The successors are fixed later when the successor blocks are 346 // visited. 347 Value *NewCond = State->get(CBV, {0, 0}); 348 349 // Replace the temporary unreachable terminator with the new conditional 350 // branch. 351 auto *CurrentTerminator = NewBB->getTerminator(); 352 assert(isa<UnreachableInst>(CurrentTerminator) && 353 "Expected to replace unreachable terminator with conditional " 354 "branch."); 355 auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond); 356 CondBr->setSuccessor(0, nullptr); 357 ReplaceInstWithInst(CurrentTerminator, CondBr); 358 } 359 360 LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB); 361 } 362 363 void VPBasicBlock::dropAllReferences(VPValue *NewValue) { 364 for (VPRecipeBase &R : Recipes) { 365 for (auto *Def : R.definedValues()) 366 Def->replaceAllUsesWith(NewValue); 367 368 for (unsigned I = 0, E = R.getNumOperands(); I != E; I++) 369 R.setOperand(I, NewValue); 370 } 371 } 372 373 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) { 374 assert((SplitAt == end() || SplitAt->getParent() == this) && 375 "can only split at a position in the same block"); 376 377 SmallVector<VPBlockBase *, 2> Succs(getSuccessors().begin(), 378 getSuccessors().end()); 379 // First, disconnect the current block from its successors. 380 for (VPBlockBase *Succ : Succs) 381 VPBlockUtils::disconnectBlocks(this, Succ); 382 383 // Create new empty block after the block to split. 384 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 385 VPBlockUtils::insertBlockAfter(SplitBlock, this); 386 387 // Add successors for block to split to new block. 388 for (VPBlockBase *Succ : Succs) 389 VPBlockUtils::connectBlocks(SplitBlock, Succ); 390 391 // Finally, move the recipes starting at SplitAt to new block. 392 for (VPRecipeBase &ToMove : 393 make_early_inc_range(make_range(SplitAt, this->end()))) 394 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 395 396 return SplitBlock; 397 } 398 399 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 400 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 401 VPSlotTracker &SlotTracker) const { 402 O << Indent << getName() << ":\n"; 403 if (const VPValue *Pred = getPredicate()) { 404 O << Indent << "BlockPredicate:"; 405 Pred->printAsOperand(O, SlotTracker); 406 if (const auto *PredInst = dyn_cast<VPInstruction>(Pred)) 407 O << " (" << PredInst->getParent()->getName() << ")"; 408 O << '\n'; 409 } 410 411 auto RecipeIndent = Indent + " "; 412 for (const VPRecipeBase &Recipe : *this) { 413 Recipe.print(O, RecipeIndent, SlotTracker); 414 O << '\n'; 415 } 416 417 if (getSuccessors().empty()) { 418 O << Indent << "No successors\n"; 419 } else { 420 O << Indent << "Successor(s): "; 421 ListSeparator LS; 422 for (auto *Succ : getSuccessors()) 423 O << LS << Succ->getName(); 424 O << '\n'; 425 } 426 427 if (const VPValue *CBV = getCondBit()) { 428 O << Indent << "CondBit: "; 429 CBV->printAsOperand(O, SlotTracker); 430 if (const auto *CBI = dyn_cast<VPInstruction>(CBV)) 431 O << " (" << CBI->getParent()->getName() << ")"; 432 O << '\n'; 433 } 434 } 435 #endif 436 437 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 438 for (VPBlockBase *Block : depth_first(Entry)) 439 // Drop all references in VPBasicBlocks and replace all uses with 440 // DummyValue. 441 Block->dropAllReferences(NewValue); 442 } 443 444 void VPRegionBlock::execute(VPTransformState *State) { 445 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 446 447 if (!isReplicator()) { 448 // Visit the VPBlocks connected to "this", starting from it. 449 for (VPBlockBase *Block : RPOT) { 450 if (EnableVPlanNativePath) { 451 // The inner loop vectorization path does not represent loop preheader 452 // and exit blocks as part of the VPlan. In the VPlan-native path, skip 453 // vectorizing loop preheader block. In future, we may replace this 454 // check with the check for loop preheader. 455 if (Block->getNumPredecessors() == 0) 456 continue; 457 458 // Skip vectorizing loop exit block. In future, we may replace this 459 // check with the check for loop exit. 460 if (Block->getNumSuccessors() == 0) 461 continue; 462 } 463 464 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 465 Block->execute(State); 466 } 467 return; 468 } 469 470 assert(!State->Instance && "Replicating a Region with non-null instance."); 471 472 // Enter replicating mode. 473 State->Instance = VPIteration(0, 0); 474 475 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 476 State->Instance->Part = Part; 477 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 478 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 479 ++Lane) { 480 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 481 // Visit the VPBlocks connected to \p this, starting from it. 482 for (VPBlockBase *Block : RPOT) { 483 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 484 Block->execute(State); 485 } 486 } 487 } 488 489 // Exit replicating mode. 490 State->Instance.reset(); 491 } 492 493 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 494 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 495 VPSlotTracker &SlotTracker) const { 496 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 497 auto NewIndent = Indent + " "; 498 for (auto *BlockBase : depth_first(Entry)) { 499 O << '\n'; 500 BlockBase->print(O, NewIndent, SlotTracker); 501 } 502 O << Indent << "}\n"; 503 } 504 #endif 505 506 bool VPRecipeBase::mayWriteToMemory() const { 507 switch (getVPDefID()) { 508 case VPWidenMemoryInstructionSC: { 509 return cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 510 } 511 case VPReplicateSC: 512 case VPWidenCallSC: 513 return cast<Instruction>(getVPValue()->getUnderlyingValue()) 514 ->mayWriteToMemory(); 515 case VPBranchOnMaskSC: 516 return false; 517 case VPWidenIntOrFpInductionSC: 518 case VPWidenCanonicalIVSC: 519 case VPWidenPHISC: 520 case VPBlendSC: 521 case VPWidenSC: 522 case VPWidenGEPSC: 523 case VPReductionSC: 524 case VPWidenSelectSC: { 525 const Instruction *I = 526 dyn_cast_or_null<Instruction>(getVPValue()->getUnderlyingValue()); 527 (void)I; 528 assert((!I || !I->mayWriteToMemory()) && 529 "underlying instruction may write to memory"); 530 return false; 531 } 532 default: 533 return true; 534 } 535 } 536 537 bool VPRecipeBase::mayReadFromMemory() const { 538 switch (getVPDefID()) { 539 case VPWidenMemoryInstructionSC: { 540 return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 541 } 542 case VPReplicateSC: 543 case VPWidenCallSC: 544 return cast<Instruction>(getVPValue()->getUnderlyingValue()) 545 ->mayReadFromMemory(); 546 case VPBranchOnMaskSC: 547 return false; 548 case VPWidenIntOrFpInductionSC: 549 case VPWidenCanonicalIVSC: 550 case VPWidenPHISC: 551 case VPBlendSC: 552 case VPWidenSC: 553 case VPWidenGEPSC: 554 case VPReductionSC: 555 case VPWidenSelectSC: { 556 const Instruction *I = 557 dyn_cast_or_null<Instruction>(getVPValue()->getUnderlyingValue()); 558 (void)I; 559 assert((!I || !I->mayReadFromMemory()) && 560 "underlying instruction may read from memory"); 561 return false; 562 } 563 default: 564 return true; 565 } 566 } 567 568 bool VPRecipeBase::mayHaveSideEffects() const { 569 switch (getVPDefID()) { 570 case VPBranchOnMaskSC: 571 return false; 572 case VPWidenIntOrFpInductionSC: 573 case VPWidenCanonicalIVSC: 574 case VPWidenPHISC: 575 case VPBlendSC: 576 case VPWidenSC: 577 case VPWidenGEPSC: 578 case VPReductionSC: 579 case VPWidenSelectSC: { 580 const Instruction *I = 581 dyn_cast_or_null<Instruction>(getVPValue()->getUnderlyingValue()); 582 (void)I; 583 assert((!I || !I->mayHaveSideEffects()) && 584 "underlying instruction has side-effects"); 585 return false; 586 } 587 case VPReplicateSC: { 588 auto *R = cast<VPReplicateRecipe>(this); 589 return R->getUnderlyingInstr()->mayHaveSideEffects(); 590 } 591 default: 592 return true; 593 } 594 } 595 596 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 597 assert(!Parent && "Recipe already in some VPBasicBlock"); 598 assert(InsertPos->getParent() && 599 "Insertion position not in any VPBasicBlock"); 600 Parent = InsertPos->getParent(); 601 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 602 } 603 604 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 605 assert(!Parent && "Recipe already in some VPBasicBlock"); 606 assert(InsertPos->getParent() && 607 "Insertion position not in any VPBasicBlock"); 608 Parent = InsertPos->getParent(); 609 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 610 } 611 612 void VPRecipeBase::removeFromParent() { 613 assert(getParent() && "Recipe not in any VPBasicBlock"); 614 getParent()->getRecipeList().remove(getIterator()); 615 Parent = nullptr; 616 } 617 618 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 619 assert(getParent() && "Recipe not in any VPBasicBlock"); 620 return getParent()->getRecipeList().erase(getIterator()); 621 } 622 623 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 624 removeFromParent(); 625 insertAfter(InsertPos); 626 } 627 628 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 629 iplist<VPRecipeBase>::iterator I) { 630 assert(I == BB.end() || I->getParent() == &BB); 631 removeFromParent(); 632 Parent = &BB; 633 BB.getRecipeList().insert(I, this); 634 } 635 636 void VPInstruction::generateInstruction(VPTransformState &State, 637 unsigned Part) { 638 IRBuilder<> &Builder = State.Builder; 639 640 if (Instruction::isBinaryOp(getOpcode())) { 641 Value *A = State.get(getOperand(0), Part); 642 Value *B = State.get(getOperand(1), Part); 643 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 644 State.set(this, V, Part); 645 return; 646 } 647 648 switch (getOpcode()) { 649 case VPInstruction::Not: { 650 Value *A = State.get(getOperand(0), Part); 651 Value *V = Builder.CreateNot(A); 652 State.set(this, V, Part); 653 break; 654 } 655 case VPInstruction::ICmpULE: { 656 Value *IV = State.get(getOperand(0), Part); 657 Value *TC = State.get(getOperand(1), Part); 658 Value *V = Builder.CreateICmpULE(IV, TC); 659 State.set(this, V, Part); 660 break; 661 } 662 case Instruction::Select: { 663 Value *Cond = State.get(getOperand(0), Part); 664 Value *Op1 = State.get(getOperand(1), Part); 665 Value *Op2 = State.get(getOperand(2), Part); 666 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 667 State.set(this, V, Part); 668 break; 669 } 670 case VPInstruction::ActiveLaneMask: { 671 // Get first lane of vector induction variable. 672 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 673 // Get the original loop tripcount. 674 Value *ScalarTC = State.TripCount; 675 676 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 677 auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue()); 678 Instruction *Call = Builder.CreateIntrinsic( 679 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 680 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 681 State.set(this, Call, Part); 682 break; 683 } 684 default: 685 llvm_unreachable("Unsupported opcode for instruction"); 686 } 687 } 688 689 void VPInstruction::execute(VPTransformState &State) { 690 assert(!State.Instance && "VPInstruction executing an Instance"); 691 for (unsigned Part = 0; Part < State.UF; ++Part) 692 generateInstruction(State, Part); 693 } 694 695 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 696 void VPInstruction::dump() const { 697 VPSlotTracker SlotTracker(getParent()->getPlan()); 698 print(dbgs(), "", SlotTracker); 699 } 700 701 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 702 VPSlotTracker &SlotTracker) const { 703 O << Indent << "EMIT "; 704 705 if (hasResult()) { 706 printAsOperand(O, SlotTracker); 707 O << " = "; 708 } 709 710 switch (getOpcode()) { 711 case VPInstruction::Not: 712 O << "not"; 713 break; 714 case VPInstruction::ICmpULE: 715 O << "icmp ule"; 716 break; 717 case VPInstruction::SLPLoad: 718 O << "combined load"; 719 break; 720 case VPInstruction::SLPStore: 721 O << "combined store"; 722 break; 723 case VPInstruction::ActiveLaneMask: 724 O << "active lane mask"; 725 break; 726 727 default: 728 O << Instruction::getOpcodeName(getOpcode()); 729 } 730 731 for (const VPValue *Operand : operands()) { 732 O << " "; 733 Operand->printAsOperand(O, SlotTracker); 734 } 735 } 736 #endif 737 738 /// Generate the code inside the body of the vectorized loop. Assumes a single 739 /// LoopVectorBody basic-block was created for this. Introduce additional 740 /// basic-blocks as needed, and fill them all. 741 void VPlan::execute(VPTransformState *State) { 742 // -1. Check if the backedge taken count is needed, and if so build it. 743 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 744 Value *TC = State->TripCount; 745 IRBuilder<> Builder(State->CFG.PrevBB->getTerminator()); 746 auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1), 747 "trip.count.minus.1"); 748 auto VF = State->VF; 749 Value *VTCMO = 750 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 751 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) 752 State->set(BackedgeTakenCount, VTCMO, Part); 753 } 754 755 // 0. Set the reverse mapping from VPValues to Values for code generation. 756 for (auto &Entry : Value2VPValue) 757 State->VPValue2Value[Entry.second] = Entry.first; 758 759 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB; 760 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor(); 761 assert(VectorHeaderBB && "Loop preheader does not have a single successor."); 762 763 // 1. Make room to generate basic-blocks inside loop body if needed. 764 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock( 765 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch"); 766 Loop *L = State->LI->getLoopFor(VectorHeaderBB); 767 L->addBasicBlockToLoop(VectorLatchBB, *State->LI); 768 // Remove the edge between Header and Latch to allow other connections. 769 // Temporarily terminate with unreachable until CFG is rewired. 770 // Note: this asserts the generated code's assumption that 771 // getFirstInsertionPt() can be dereferenced into an Instruction. 772 VectorHeaderBB->getTerminator()->eraseFromParent(); 773 State->Builder.SetInsertPoint(VectorHeaderBB); 774 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 775 State->Builder.SetInsertPoint(Terminator); 776 777 // 2. Generate code in loop body. 778 State->CFG.PrevVPBB = nullptr; 779 State->CFG.PrevBB = VectorHeaderBB; 780 State->CFG.LastBB = VectorLatchBB; 781 782 for (VPBlockBase *Block : depth_first(Entry)) 783 Block->execute(State); 784 785 // Setup branch terminator successors for VPBBs in VPBBsToFix based on 786 // VPBB's successors. 787 for (auto VPBB : State->CFG.VPBBsToFix) { 788 assert(EnableVPlanNativePath && 789 "Unexpected VPBBsToFix in non VPlan-native path"); 790 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB]; 791 assert(BB && "Unexpected null basic block for VPBB"); 792 793 unsigned Idx = 0; 794 auto *BBTerminator = BB->getTerminator(); 795 796 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) { 797 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock(); 798 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]); 799 ++Idx; 800 } 801 } 802 803 // 3. Merge the temporary latch created with the last basic-block filled. 804 BasicBlock *LastBB = State->CFG.PrevBB; 805 // Connect LastBB to VectorLatchBB to facilitate their merge. 806 assert((EnableVPlanNativePath || 807 isa<UnreachableInst>(LastBB->getTerminator())) && 808 "Expected InnerLoop VPlan CFG to terminate with unreachable"); 809 assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) && 810 "Expected VPlan CFG to terminate with branch in NativePath"); 811 LastBB->getTerminator()->eraseFromParent(); 812 BranchInst::Create(VectorLatchBB, LastBB); 813 814 // Merge LastBB with Latch. 815 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI); 816 (void)Merged; 817 assert(Merged && "Could not merge last basic block with latch."); 818 VectorLatchBB = LastBB; 819 820 // We do not attempt to preserve DT for outer loop vectorization currently. 821 if (!EnableVPlanNativePath) 822 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB, 823 L->getExitBlock()); 824 } 825 826 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 827 LLVM_DUMP_METHOD 828 void VPlan::print(raw_ostream &O) const { 829 VPSlotTracker SlotTracker(this); 830 831 O << "VPlan '" << Name << "' {"; 832 for (const VPBlockBase *Block : depth_first(getEntry())) { 833 O << '\n'; 834 Block->print(O, "", SlotTracker); 835 } 836 O << "}\n"; 837 } 838 839 LLVM_DUMP_METHOD 840 void VPlan::printDOT(raw_ostream &O) const { 841 VPlanPrinter Printer(O, *this); 842 Printer.dump(); 843 } 844 845 LLVM_DUMP_METHOD 846 void VPlan::dump() const { print(dbgs()); } 847 #endif 848 849 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB, 850 BasicBlock *LoopLatchBB, 851 BasicBlock *LoopExitBB) { 852 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor(); 853 assert(LoopHeaderBB && "Loop preheader does not have a single successor."); 854 // The vector body may be more than a single basic-block by this point. 855 // Update the dominator tree information inside the vector body by propagating 856 // it from header to latch, expecting only triangular control-flow, if any. 857 BasicBlock *PostDomSucc = nullptr; 858 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 859 // Get the list of successors of this block. 860 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 861 assert(Succs.size() <= 2 && 862 "Basic block in vector loop has more than 2 successors."); 863 PostDomSucc = Succs[0]; 864 if (Succs.size() == 1) { 865 assert(PostDomSucc->getSinglePredecessor() && 866 "PostDom successor has more than one predecessor."); 867 DT->addNewBlock(PostDomSucc, BB); 868 continue; 869 } 870 BasicBlock *InterimSucc = Succs[1]; 871 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 872 PostDomSucc = Succs[1]; 873 InterimSucc = Succs[0]; 874 } 875 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 876 "One successor of a basic block does not lead to the other."); 877 assert(InterimSucc->getSinglePredecessor() && 878 "Interim successor has more than one predecessor."); 879 assert(PostDomSucc->hasNPredecessors(2) && 880 "PostDom successor has more than two predecessors."); 881 DT->addNewBlock(InterimSucc, BB); 882 DT->addNewBlock(PostDomSucc, BB); 883 } 884 // Latch block is a new dominator for the loop exit. 885 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 886 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 887 } 888 889 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 890 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 891 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 892 Twine(getOrCreateBID(Block)); 893 } 894 895 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 896 const std::string &Name = Block->getName(); 897 if (!Name.empty()) 898 return Name; 899 return "VPB" + Twine(getOrCreateBID(Block)); 900 } 901 902 void VPlanPrinter::dump() { 903 Depth = 1; 904 bumpIndent(0); 905 OS << "digraph VPlan {\n"; 906 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 907 if (!Plan.getName().empty()) 908 OS << "\\n" << DOT::EscapeString(Plan.getName()); 909 if (Plan.BackedgeTakenCount) { 910 OS << ", where:\\n"; 911 Plan.BackedgeTakenCount->print(OS, SlotTracker); 912 OS << " := BackedgeTakenCount"; 913 } 914 OS << "\"]\n"; 915 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 916 OS << "edge [fontname=Courier, fontsize=30]\n"; 917 OS << "compound=true\n"; 918 919 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 920 dumpBlock(Block); 921 922 OS << "}\n"; 923 } 924 925 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 926 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 927 dumpBasicBlock(BasicBlock); 928 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 929 dumpRegion(Region); 930 else 931 llvm_unreachable("Unsupported kind of VPBlock."); 932 } 933 934 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 935 bool Hidden, const Twine &Label) { 936 // Due to "dot" we print an edge between two regions as an edge between the 937 // exit basic block and the entry basic of the respective regions. 938 const VPBlockBase *Tail = From->getExitBasicBlock(); 939 const VPBlockBase *Head = To->getEntryBasicBlock(); 940 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 941 OS << " [ label=\"" << Label << '\"'; 942 if (Tail != From) 943 OS << " ltail=" << getUID(From); 944 if (Head != To) 945 OS << " lhead=" << getUID(To); 946 if (Hidden) 947 OS << "; splines=none"; 948 OS << "]\n"; 949 } 950 951 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 952 auto &Successors = Block->getSuccessors(); 953 if (Successors.size() == 1) 954 drawEdge(Block, Successors.front(), false, ""); 955 else if (Successors.size() == 2) { 956 drawEdge(Block, Successors.front(), false, "T"); 957 drawEdge(Block, Successors.back(), false, "F"); 958 } else { 959 unsigned SuccessorNumber = 0; 960 for (auto *Successor : Successors) 961 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 962 } 963 } 964 965 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 966 // Implement dot-formatted dump by performing plain-text dump into the 967 // temporary storage followed by some post-processing. 968 OS << Indent << getUID(BasicBlock) << " [label =\n"; 969 bumpIndent(1); 970 std::string Str; 971 raw_string_ostream SS(Str); 972 // Use no indentation as we need to wrap the lines into quotes ourselves. 973 BasicBlock->print(SS, "", SlotTracker); 974 975 // We need to process each line of the output separately, so split 976 // single-string plain-text dump. 977 SmallVector<StringRef, 0> Lines; 978 StringRef(Str).rtrim('\n').split(Lines, "\n"); 979 980 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 981 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 982 }; 983 984 // Don't need the "+" after the last line. 985 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 986 EmitLine(Line, " +\n"); 987 EmitLine(Lines.back(), "\n"); 988 989 bumpIndent(-1); 990 OS << Indent << "]\n"; 991 992 dumpEdges(BasicBlock); 993 } 994 995 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 996 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 997 bumpIndent(1); 998 OS << Indent << "fontname=Courier\n" 999 << Indent << "label=\"" 1000 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1001 << DOT::EscapeString(Region->getName()) << "\"\n"; 1002 // Dump the blocks of the region. 1003 assert(Region->getEntry() && "Region contains no inner blocks."); 1004 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 1005 dumpBlock(Block); 1006 bumpIndent(-1); 1007 OS << Indent << "}\n"; 1008 dumpEdges(Region); 1009 } 1010 1011 void VPlanIngredient::print(raw_ostream &O) const { 1012 if (auto *Inst = dyn_cast<Instruction>(V)) { 1013 if (!Inst->getType()->isVoidTy()) { 1014 Inst->printAsOperand(O, false); 1015 O << " = "; 1016 } 1017 O << Inst->getOpcodeName() << " "; 1018 unsigned E = Inst->getNumOperands(); 1019 if (E > 0) { 1020 Inst->getOperand(0)->printAsOperand(O, false); 1021 for (unsigned I = 1; I < E; ++I) 1022 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1023 } 1024 } else // !Inst 1025 V->printAsOperand(O, false); 1026 } 1027 1028 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 1029 VPSlotTracker &SlotTracker) const { 1030 O << Indent << "WIDEN-CALL "; 1031 1032 auto *CI = cast<CallInst>(getUnderlyingInstr()); 1033 if (CI->getType()->isVoidTy()) 1034 O << "void "; 1035 else { 1036 printAsOperand(O, SlotTracker); 1037 O << " = "; 1038 } 1039 1040 O << "call @" << CI->getCalledFunction()->getName() << "("; 1041 printOperands(O, SlotTracker); 1042 O << ")"; 1043 } 1044 1045 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 1046 VPSlotTracker &SlotTracker) const { 1047 O << Indent << "WIDEN-SELECT "; 1048 printAsOperand(O, SlotTracker); 1049 O << " = select "; 1050 getOperand(0)->printAsOperand(O, SlotTracker); 1051 O << ", "; 1052 getOperand(1)->printAsOperand(O, SlotTracker); 1053 O << ", "; 1054 getOperand(2)->printAsOperand(O, SlotTracker); 1055 O << (InvariantCond ? " (condition is loop invariant)" : ""); 1056 } 1057 1058 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 1059 VPSlotTracker &SlotTracker) const { 1060 O << Indent << "WIDEN "; 1061 printAsOperand(O, SlotTracker); 1062 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 1063 printOperands(O, SlotTracker); 1064 } 1065 1066 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1067 VPSlotTracker &SlotTracker) const { 1068 O << Indent << "WIDEN-INDUCTION"; 1069 if (getTruncInst()) { 1070 O << "\\l\""; 1071 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 1072 O << " +\n" << Indent << "\" "; 1073 getVPValue(0)->printAsOperand(O, SlotTracker); 1074 } else 1075 O << " " << VPlanIngredient(IV); 1076 } 1077 1078 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 1079 VPSlotTracker &SlotTracker) const { 1080 O << Indent << "WIDEN-GEP "; 1081 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 1082 size_t IndicesNumber = IsIndexLoopInvariant.size(); 1083 for (size_t I = 0; I < IndicesNumber; ++I) 1084 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 1085 1086 O << " "; 1087 printAsOperand(O, SlotTracker); 1088 O << " = getelementptr "; 1089 printOperands(O, SlotTracker); 1090 } 1091 1092 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1093 VPSlotTracker &SlotTracker) const { 1094 O << Indent << "WIDEN-PHI "; 1095 1096 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue()); 1097 // Unless all incoming values are modeled in VPlan print the original PHI 1098 // directly. 1099 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming 1100 // values as VPValues. 1101 if (getNumOperands() != OriginalPhi->getNumOperands()) { 1102 O << VPlanIngredient(OriginalPhi); 1103 return; 1104 } 1105 1106 printAsOperand(O, SlotTracker); 1107 O << " = phi "; 1108 printOperands(O, SlotTracker); 1109 } 1110 1111 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 1112 VPSlotTracker &SlotTracker) const { 1113 O << Indent << "BLEND "; 1114 Phi->printAsOperand(O, false); 1115 O << " ="; 1116 if (getNumIncomingValues() == 1) { 1117 // Not a User of any mask: not really blending, this is a 1118 // single-predecessor phi. 1119 O << " "; 1120 getIncomingValue(0)->printAsOperand(O, SlotTracker); 1121 } else { 1122 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 1123 O << " "; 1124 getIncomingValue(I)->printAsOperand(O, SlotTracker); 1125 O << "/"; 1126 getMask(I)->printAsOperand(O, SlotTracker); 1127 } 1128 } 1129 } 1130 1131 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 1132 VPSlotTracker &SlotTracker) const { 1133 O << Indent << "REDUCE "; 1134 printAsOperand(O, SlotTracker); 1135 O << " = "; 1136 getChainOp()->printAsOperand(O, SlotTracker); 1137 O << " + reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) 1138 << " ("; 1139 getVecOp()->printAsOperand(O, SlotTracker); 1140 if (getCondOp()) { 1141 O << ", "; 1142 getCondOp()->printAsOperand(O, SlotTracker); 1143 } 1144 O << ")"; 1145 } 1146 1147 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 1148 VPSlotTracker &SlotTracker) const { 1149 O << Indent << (IsUniform ? "CLONE " : "REPLICATE "); 1150 1151 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 1152 printAsOperand(O, SlotTracker); 1153 O << " = "; 1154 } 1155 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 1156 printOperands(O, SlotTracker); 1157 1158 if (AlsoPack) 1159 O << " (S->V)"; 1160 } 1161 1162 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1163 VPSlotTracker &SlotTracker) const { 1164 O << Indent << "PHI-PREDICATED-INSTRUCTION "; 1165 printAsOperand(O, SlotTracker); 1166 O << " = "; 1167 printOperands(O, SlotTracker); 1168 } 1169 1170 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 1171 VPSlotTracker &SlotTracker) const { 1172 O << Indent << "WIDEN "; 1173 1174 if (!isStore()) { 1175 getVPValue()->printAsOperand(O, SlotTracker); 1176 O << " = "; 1177 } 1178 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 1179 1180 printOperands(O, SlotTracker); 1181 } 1182 #endif 1183 1184 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 1185 Value *CanonicalIV = State.CanonicalIV; 1186 Type *STy = CanonicalIV->getType(); 1187 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 1188 ElementCount VF = State.VF; 1189 assert(!VF.isScalable() && "the code following assumes non scalables ECs"); 1190 Value *VStart = VF.isScalar() 1191 ? CanonicalIV 1192 : Builder.CreateVectorSplat(VF.getKnownMinValue(), 1193 CanonicalIV, "broadcast"); 1194 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 1195 SmallVector<Constant *, 8> Indices; 1196 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane) 1197 Indices.push_back( 1198 ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane)); 1199 // If VF == 1, there is only one iteration in the loop above, thus the 1200 // element pushed back into Indices is ConstantInt::get(STy, Part) 1201 Constant *VStep = 1202 VF.isScalar() ? Indices.back() : ConstantVector::get(Indices); 1203 // Add the consecutive indices to the vector value. 1204 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1205 State.set(getVPSingleValue(), CanonicalVectorIV, Part); 1206 } 1207 } 1208 1209 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1210 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1211 VPSlotTracker &SlotTracker) const { 1212 O << Indent << "EMIT "; 1213 getVPValue()->printAsOperand(O, SlotTracker); 1214 O << " = WIDEN-CANONICAL-INDUCTION"; 1215 } 1216 #endif 1217 1218 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1219 1220 void VPValue::replaceAllUsesWith(VPValue *New) { 1221 for (unsigned J = 0; J < getNumUsers();) { 1222 VPUser *User = Users[J]; 1223 unsigned NumUsers = getNumUsers(); 1224 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1225 if (User->getOperand(I) == this) 1226 User->setOperand(I, New); 1227 // If a user got removed after updating the current user, the next user to 1228 // update will be moved to the current position, so we only need to 1229 // increment the index if the number of users did not change. 1230 if (NumUsers == getNumUsers()) 1231 J++; 1232 } 1233 } 1234 1235 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1236 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1237 if (const Value *UV = getUnderlyingValue()) { 1238 OS << "ir<"; 1239 UV->printAsOperand(OS, false); 1240 OS << ">"; 1241 return; 1242 } 1243 1244 unsigned Slot = Tracker.getSlot(this); 1245 if (Slot == unsigned(-1)) 1246 OS << "<badref>"; 1247 else 1248 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1249 } 1250 1251 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1252 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1253 Op->printAsOperand(O, SlotTracker); 1254 }); 1255 } 1256 #endif 1257 1258 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1259 Old2NewTy &Old2New, 1260 InterleavedAccessInfo &IAI) { 1261 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1262 for (VPBlockBase *Base : RPOT) { 1263 visitBlock(Base, Old2New, IAI); 1264 } 1265 } 1266 1267 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1268 InterleavedAccessInfo &IAI) { 1269 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1270 for (VPRecipeBase &VPI : *VPBB) { 1271 if (isa<VPWidenPHIRecipe>(&VPI)) 1272 continue; 1273 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1274 auto *VPInst = cast<VPInstruction>(&VPI); 1275 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1276 auto *IG = IAI.getInterleaveGroup(Inst); 1277 if (!IG) 1278 continue; 1279 1280 auto NewIGIter = Old2New.find(IG); 1281 if (NewIGIter == Old2New.end()) 1282 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1283 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1284 1285 if (Inst == IG->getInsertPos()) 1286 Old2New[IG]->setInsertPos(VPInst); 1287 1288 InterleaveGroupMap[VPInst] = Old2New[IG]; 1289 InterleaveGroupMap[VPInst]->insertMember( 1290 VPInst, IG->getIndex(Inst), 1291 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1292 : IG->getFactor())); 1293 } 1294 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1295 visitRegion(Region, Old2New, IAI); 1296 else 1297 llvm_unreachable("Unsupported kind of VPBlock."); 1298 } 1299 1300 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1301 InterleavedAccessInfo &IAI) { 1302 Old2NewTy Old2New; 1303 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI); 1304 } 1305 1306 void VPSlotTracker::assignSlot(const VPValue *V) { 1307 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1308 Slots[V] = NextSlot++; 1309 } 1310 1311 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1312 1313 for (const VPValue *V : Plan.VPExternalDefs) 1314 assignSlot(V); 1315 1316 if (Plan.BackedgeTakenCount) 1317 assignSlot(Plan.BackedgeTakenCount); 1318 1319 ReversePostOrderTraversal< 1320 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1321 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1322 Plan.getEntry())); 1323 for (const VPBasicBlock *VPBB : 1324 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1325 for (const VPRecipeBase &Recipe : *VPBB) 1326 for (VPValue *Def : Recipe.definedValues()) 1327 assignSlot(Def); 1328 } 1329