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(successors()); 378 // First, disconnect the current block from its successors. 379 for (VPBlockBase *Succ : Succs) 380 VPBlockUtils::disconnectBlocks(this, Succ); 381 382 // Create new empty block after the block to split. 383 auto *SplitBlock = new VPBasicBlock(getName() + ".split"); 384 VPBlockUtils::insertBlockAfter(SplitBlock, this); 385 386 // Add successors for block to split to new block. 387 for (VPBlockBase *Succ : Succs) 388 VPBlockUtils::connectBlocks(SplitBlock, Succ); 389 390 // Finally, move the recipes starting at SplitAt to new block. 391 for (VPRecipeBase &ToMove : 392 make_early_inc_range(make_range(SplitAt, this->end()))) 393 ToMove.moveBefore(*SplitBlock, SplitBlock->end()); 394 395 return SplitBlock; 396 } 397 398 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 399 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const { 400 if (getSuccessors().empty()) { 401 O << Indent << "No successors\n"; 402 } else { 403 O << Indent << "Successor(s): "; 404 ListSeparator LS; 405 for (auto *Succ : getSuccessors()) 406 O << LS << Succ->getName(); 407 O << '\n'; 408 } 409 } 410 411 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent, 412 VPSlotTracker &SlotTracker) const { 413 O << Indent << getName() << ":\n"; 414 if (const VPValue *Pred = getPredicate()) { 415 O << Indent << "BlockPredicate:"; 416 Pred->printAsOperand(O, SlotTracker); 417 if (const auto *PredInst = dyn_cast<VPInstruction>(Pred)) 418 O << " (" << PredInst->getParent()->getName() << ")"; 419 O << '\n'; 420 } 421 422 auto RecipeIndent = Indent + " "; 423 for (const VPRecipeBase &Recipe : *this) { 424 Recipe.print(O, RecipeIndent, SlotTracker); 425 O << '\n'; 426 } 427 428 printSuccessors(O, Indent); 429 430 if (const VPValue *CBV = getCondBit()) { 431 O << Indent << "CondBit: "; 432 CBV->printAsOperand(O, SlotTracker); 433 if (const auto *CBI = dyn_cast<VPInstruction>(CBV)) 434 O << " (" << CBI->getParent()->getName() << ")"; 435 O << '\n'; 436 } 437 } 438 #endif 439 440 void VPRegionBlock::dropAllReferences(VPValue *NewValue) { 441 for (VPBlockBase *Block : depth_first(Entry)) 442 // Drop all references in VPBasicBlocks and replace all uses with 443 // DummyValue. 444 Block->dropAllReferences(NewValue); 445 } 446 447 void VPRegionBlock::execute(VPTransformState *State) { 448 ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry); 449 450 if (!isReplicator()) { 451 // Visit the VPBlocks connected to "this", starting from it. 452 for (VPBlockBase *Block : RPOT) { 453 if (EnableVPlanNativePath) { 454 // The inner loop vectorization path does not represent loop preheader 455 // and exit blocks as part of the VPlan. In the VPlan-native path, skip 456 // vectorizing loop preheader block. In future, we may replace this 457 // check with the check for loop preheader. 458 if (Block->getNumPredecessors() == 0) 459 continue; 460 461 // Skip vectorizing loop exit block. In future, we may replace this 462 // check with the check for loop exit. 463 if (Block->getNumSuccessors() == 0) 464 continue; 465 } 466 467 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 468 Block->execute(State); 469 } 470 return; 471 } 472 473 assert(!State->Instance && "Replicating a Region with non-null instance."); 474 475 // Enter replicating mode. 476 State->Instance = VPIteration(0, 0); 477 478 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) { 479 State->Instance->Part = Part; 480 assert(!State->VF.isScalable() && "VF is assumed to be non scalable."); 481 for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF; 482 ++Lane) { 483 State->Instance->Lane = VPLane(Lane, VPLane::Kind::First); 484 // Visit the VPBlocks connected to \p this, starting from it. 485 for (VPBlockBase *Block : RPOT) { 486 LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n'); 487 Block->execute(State); 488 } 489 } 490 } 491 492 // Exit replicating mode. 493 State->Instance.reset(); 494 } 495 496 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 497 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent, 498 VPSlotTracker &SlotTracker) const { 499 O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {"; 500 auto NewIndent = Indent + " "; 501 for (auto *BlockBase : depth_first(Entry)) { 502 O << '\n'; 503 BlockBase->print(O, NewIndent, SlotTracker); 504 } 505 O << Indent << "}\n"; 506 507 printSuccessors(O, Indent); 508 } 509 #endif 510 511 bool VPRecipeBase::mayWriteToMemory() const { 512 switch (getVPDefID()) { 513 case VPWidenMemoryInstructionSC: { 514 return cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 515 } 516 case VPReplicateSC: 517 case VPWidenCallSC: 518 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 519 ->mayWriteToMemory(); 520 case VPBranchOnMaskSC: 521 return false; 522 case VPWidenIntOrFpInductionSC: 523 case VPWidenCanonicalIVSC: 524 case VPWidenPHISC: 525 case VPBlendSC: 526 case VPWidenSC: 527 case VPWidenGEPSC: 528 case VPReductionSC: 529 case VPWidenSelectSC: { 530 const Instruction *I = 531 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 532 (void)I; 533 assert((!I || !I->mayWriteToMemory()) && 534 "underlying instruction may write to memory"); 535 return false; 536 } 537 default: 538 return true; 539 } 540 } 541 542 bool VPRecipeBase::mayReadFromMemory() const { 543 switch (getVPDefID()) { 544 case VPWidenMemoryInstructionSC: { 545 return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore(); 546 } 547 case VPReplicateSC: 548 case VPWidenCallSC: 549 return cast<Instruction>(getVPSingleValue()->getUnderlyingValue()) 550 ->mayReadFromMemory(); 551 case VPBranchOnMaskSC: 552 return false; 553 case VPWidenIntOrFpInductionSC: 554 case VPWidenCanonicalIVSC: 555 case VPWidenPHISC: 556 case VPBlendSC: 557 case VPWidenSC: 558 case VPWidenGEPSC: 559 case VPReductionSC: 560 case VPWidenSelectSC: { 561 const Instruction *I = 562 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 563 (void)I; 564 assert((!I || !I->mayReadFromMemory()) && 565 "underlying instruction may read from memory"); 566 return false; 567 } 568 default: 569 return true; 570 } 571 } 572 573 bool VPRecipeBase::mayHaveSideEffects() const { 574 switch (getVPDefID()) { 575 case VPBranchOnMaskSC: 576 return false; 577 case VPWidenIntOrFpInductionSC: 578 case VPWidenCanonicalIVSC: 579 case VPWidenPHISC: 580 case VPBlendSC: 581 case VPWidenSC: 582 case VPWidenGEPSC: 583 case VPReductionSC: 584 case VPWidenSelectSC: { 585 const Instruction *I = 586 dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue()); 587 (void)I; 588 assert((!I || !I->mayHaveSideEffects()) && 589 "underlying instruction has side-effects"); 590 return false; 591 } 592 case VPReplicateSC: { 593 auto *R = cast<VPReplicateRecipe>(this); 594 return R->getUnderlyingInstr()->mayHaveSideEffects(); 595 } 596 default: 597 return true; 598 } 599 } 600 601 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) { 602 assert(!Parent && "Recipe already in some VPBasicBlock"); 603 assert(InsertPos->getParent() && 604 "Insertion position not in any VPBasicBlock"); 605 Parent = InsertPos->getParent(); 606 Parent->getRecipeList().insert(InsertPos->getIterator(), this); 607 } 608 609 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) { 610 assert(!Parent && "Recipe already in some VPBasicBlock"); 611 assert(InsertPos->getParent() && 612 "Insertion position not in any VPBasicBlock"); 613 Parent = InsertPos->getParent(); 614 Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this); 615 } 616 617 void VPRecipeBase::removeFromParent() { 618 assert(getParent() && "Recipe not in any VPBasicBlock"); 619 getParent()->getRecipeList().remove(getIterator()); 620 Parent = nullptr; 621 } 622 623 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() { 624 assert(getParent() && "Recipe not in any VPBasicBlock"); 625 return getParent()->getRecipeList().erase(getIterator()); 626 } 627 628 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) { 629 removeFromParent(); 630 insertAfter(InsertPos); 631 } 632 633 void VPRecipeBase::moveBefore(VPBasicBlock &BB, 634 iplist<VPRecipeBase>::iterator I) { 635 assert(I == BB.end() || I->getParent() == &BB); 636 removeFromParent(); 637 Parent = &BB; 638 BB.getRecipeList().insert(I, this); 639 } 640 641 void VPInstruction::generateInstruction(VPTransformState &State, 642 unsigned Part) { 643 IRBuilder<> &Builder = State.Builder; 644 645 if (Instruction::isBinaryOp(getOpcode())) { 646 Value *A = State.get(getOperand(0), Part); 647 Value *B = State.get(getOperand(1), Part); 648 Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B); 649 State.set(this, V, Part); 650 return; 651 } 652 653 switch (getOpcode()) { 654 case VPInstruction::Not: { 655 Value *A = State.get(getOperand(0), Part); 656 Value *V = Builder.CreateNot(A); 657 State.set(this, V, Part); 658 break; 659 } 660 case VPInstruction::ICmpULE: { 661 Value *IV = State.get(getOperand(0), Part); 662 Value *TC = State.get(getOperand(1), Part); 663 Value *V = Builder.CreateICmpULE(IV, TC); 664 State.set(this, V, Part); 665 break; 666 } 667 case Instruction::Select: { 668 Value *Cond = State.get(getOperand(0), Part); 669 Value *Op1 = State.get(getOperand(1), Part); 670 Value *Op2 = State.get(getOperand(2), Part); 671 Value *V = Builder.CreateSelect(Cond, Op1, Op2); 672 State.set(this, V, Part); 673 break; 674 } 675 case VPInstruction::ActiveLaneMask: { 676 // Get first lane of vector induction variable. 677 Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0)); 678 // Get the original loop tripcount. 679 Value *ScalarTC = State.TripCount; 680 681 auto *Int1Ty = Type::getInt1Ty(Builder.getContext()); 682 auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue()); 683 Instruction *Call = Builder.CreateIntrinsic( 684 Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()}, 685 {VIVElem0, ScalarTC}, nullptr, "active.lane.mask"); 686 State.set(this, Call, Part); 687 break; 688 } 689 case VPInstruction::FirstOrderRecurrenceSplice: { 690 // Generate code to combine the previous and current values in vector v3. 691 // 692 // vector.ph: 693 // v_init = vector(..., ..., ..., a[-1]) 694 // br vector.body 695 // 696 // vector.body 697 // i = phi [0, vector.ph], [i+4, vector.body] 698 // v1 = phi [v_init, vector.ph], [v2, vector.body] 699 // v2 = a[i, i+1, i+2, i+3]; 700 // v3 = vector(v1(3), v2(0, 1, 2)) 701 702 // For the first part, use the recurrence phi (v1), otherwise v2. 703 auto *V1 = State.get(getOperand(0), 0); 704 Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1); 705 if (!PartMinus1->getType()->isVectorTy()) { 706 State.set(this, PartMinus1, Part); 707 } else { 708 Value *V2 = State.get(getOperand(1), Part); 709 State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part); 710 } 711 break; 712 } 713 default: 714 llvm_unreachable("Unsupported opcode for instruction"); 715 } 716 } 717 718 void VPInstruction::execute(VPTransformState &State) { 719 assert(!State.Instance && "VPInstruction executing an Instance"); 720 IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder); 721 State.Builder.setFastMathFlags(FMF); 722 for (unsigned Part = 0; Part < State.UF; ++Part) 723 generateInstruction(State, Part); 724 } 725 726 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 727 void VPInstruction::dump() const { 728 VPSlotTracker SlotTracker(getParent()->getPlan()); 729 print(dbgs(), "", SlotTracker); 730 } 731 732 void VPInstruction::print(raw_ostream &O, const Twine &Indent, 733 VPSlotTracker &SlotTracker) const { 734 O << Indent << "EMIT "; 735 736 if (hasResult()) { 737 printAsOperand(O, SlotTracker); 738 O << " = "; 739 } 740 741 switch (getOpcode()) { 742 case VPInstruction::Not: 743 O << "not"; 744 break; 745 case VPInstruction::ICmpULE: 746 O << "icmp ule"; 747 break; 748 case VPInstruction::SLPLoad: 749 O << "combined load"; 750 break; 751 case VPInstruction::SLPStore: 752 O << "combined store"; 753 break; 754 case VPInstruction::ActiveLaneMask: 755 O << "active lane mask"; 756 break; 757 case VPInstruction::FirstOrderRecurrenceSplice: 758 O << "first-order splice"; 759 break; 760 default: 761 O << Instruction::getOpcodeName(getOpcode()); 762 } 763 764 O << FMF; 765 766 for (const VPValue *Operand : operands()) { 767 O << " "; 768 Operand->printAsOperand(O, SlotTracker); 769 } 770 } 771 #endif 772 773 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) { 774 // Make sure the VPInstruction is a floating-point operation. 775 assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul || 776 Opcode == Instruction::FNeg || Opcode == Instruction::FSub || 777 Opcode == Instruction::FDiv || Opcode == Instruction::FRem || 778 Opcode == Instruction::FCmp) && 779 "this op can't take fast-math flags"); 780 FMF = FMFNew; 781 } 782 783 /// Generate the code inside the body of the vectorized loop. Assumes a single 784 /// LoopVectorBody basic-block was created for this. Introduce additional 785 /// basic-blocks as needed, and fill them all. 786 void VPlan::execute(VPTransformState *State) { 787 // -1. Check if the backedge taken count is needed, and if so build it. 788 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 789 Value *TC = State->TripCount; 790 IRBuilder<> Builder(State->CFG.PrevBB->getTerminator()); 791 auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1), 792 "trip.count.minus.1"); 793 auto VF = State->VF; 794 Value *VTCMO = 795 VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast"); 796 for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) 797 State->set(BackedgeTakenCount, VTCMO, Part); 798 } 799 800 // 0. Set the reverse mapping from VPValues to Values for code generation. 801 for (auto &Entry : Value2VPValue) 802 State->VPValue2Value[Entry.second] = Entry.first; 803 804 BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB; 805 State->CFG.VectorPreHeader = VectorPreHeaderBB; 806 BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor(); 807 assert(VectorHeaderBB && "Loop preheader does not have a single successor."); 808 809 // 1. Make room to generate basic-blocks inside loop body if needed. 810 BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock( 811 VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch"); 812 Loop *L = State->LI->getLoopFor(VectorHeaderBB); 813 L->addBasicBlockToLoop(VectorLatchBB, *State->LI); 814 // Remove the edge between Header and Latch to allow other connections. 815 // Temporarily terminate with unreachable until CFG is rewired. 816 // Note: this asserts the generated code's assumption that 817 // getFirstInsertionPt() can be dereferenced into an Instruction. 818 VectorHeaderBB->getTerminator()->eraseFromParent(); 819 State->Builder.SetInsertPoint(VectorHeaderBB); 820 UnreachableInst *Terminator = State->Builder.CreateUnreachable(); 821 State->Builder.SetInsertPoint(Terminator); 822 823 // 2. Generate code in loop body. 824 State->CFG.PrevVPBB = nullptr; 825 State->CFG.PrevBB = VectorHeaderBB; 826 State->CFG.LastBB = VectorLatchBB; 827 828 for (VPBlockBase *Block : depth_first(Entry)) 829 Block->execute(State); 830 831 // Fix the latch value of reduction and first-order recurrences phis in the 832 // vector loop. 833 VPBasicBlock *Header = Entry->getEntryBasicBlock(); 834 for (VPRecipeBase &R : Header->phis()) { 835 auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R); 836 if (!PhiR || !(isa<VPFirstOrderRecurrencePHIRecipe>(&R) || 837 isa<VPReductionPHIRecipe>(&R))) 838 continue; 839 // For first-order recurrences and in-order reduction phis, only a single 840 // part is generated, which provides the last part from the previous 841 // iteration. Otherwise all UF parts are generated. 842 bool SinglePartNeeded = isa<VPFirstOrderRecurrencePHIRecipe>(&R) || 843 cast<VPReductionPHIRecipe>(&R)->isOrdered(); 844 unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF; 845 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 846 Value *VecPhi = State->get(PhiR, Part); 847 Value *Val = State->get(PhiR->getBackedgeValue(), 848 SinglePartNeeded ? State->UF - 1 : Part); 849 cast<PHINode>(VecPhi)->addIncoming(Val, VectorLatchBB); 850 } 851 } 852 853 // Setup branch terminator successors for VPBBs in VPBBsToFix based on 854 // VPBB's successors. 855 for (auto VPBB : State->CFG.VPBBsToFix) { 856 assert(EnableVPlanNativePath && 857 "Unexpected VPBBsToFix in non VPlan-native path"); 858 BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB]; 859 assert(BB && "Unexpected null basic block for VPBB"); 860 861 unsigned Idx = 0; 862 auto *BBTerminator = BB->getTerminator(); 863 864 for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) { 865 VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock(); 866 BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]); 867 ++Idx; 868 } 869 } 870 871 // 3. Merge the temporary latch created with the last basic-block filled. 872 BasicBlock *LastBB = State->CFG.PrevBB; 873 // Connect LastBB to VectorLatchBB to facilitate their merge. 874 assert((EnableVPlanNativePath || 875 isa<UnreachableInst>(LastBB->getTerminator())) && 876 "Expected InnerLoop VPlan CFG to terminate with unreachable"); 877 assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) && 878 "Expected VPlan CFG to terminate with branch in NativePath"); 879 LastBB->getTerminator()->eraseFromParent(); 880 BranchInst::Create(VectorLatchBB, LastBB); 881 882 // Merge LastBB with Latch. 883 bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI); 884 (void)Merged; 885 assert(Merged && "Could not merge last basic block with latch."); 886 VectorLatchBB = LastBB; 887 888 // We do not attempt to preserve DT for outer loop vectorization currently. 889 if (!EnableVPlanNativePath) 890 updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB, 891 L->getExitBlock()); 892 } 893 894 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 895 LLVM_DUMP_METHOD 896 void VPlan::print(raw_ostream &O) const { 897 VPSlotTracker SlotTracker(this); 898 899 O << "VPlan '" << Name << "' {"; 900 901 if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) { 902 O << "\nLive-in "; 903 BackedgeTakenCount->printAsOperand(O, SlotTracker); 904 O << " = backedge-taken count\n"; 905 } 906 907 for (const VPBlockBase *Block : depth_first(getEntry())) { 908 O << '\n'; 909 Block->print(O, "", SlotTracker); 910 } 911 O << "}\n"; 912 } 913 914 LLVM_DUMP_METHOD 915 void VPlan::printDOT(raw_ostream &O) const { 916 VPlanPrinter Printer(O, *this); 917 Printer.dump(); 918 } 919 920 LLVM_DUMP_METHOD 921 void VPlan::dump() const { print(dbgs()); } 922 #endif 923 924 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB, 925 BasicBlock *LoopLatchBB, 926 BasicBlock *LoopExitBB) { 927 BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor(); 928 assert(LoopHeaderBB && "Loop preheader does not have a single successor."); 929 // The vector body may be more than a single basic-block by this point. 930 // Update the dominator tree information inside the vector body by propagating 931 // it from header to latch, expecting only triangular control-flow, if any. 932 BasicBlock *PostDomSucc = nullptr; 933 for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) { 934 // Get the list of successors of this block. 935 std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB)); 936 assert(Succs.size() <= 2 && 937 "Basic block in vector loop has more than 2 successors."); 938 PostDomSucc = Succs[0]; 939 if (Succs.size() == 1) { 940 assert(PostDomSucc->getSinglePredecessor() && 941 "PostDom successor has more than one predecessor."); 942 DT->addNewBlock(PostDomSucc, BB); 943 continue; 944 } 945 BasicBlock *InterimSucc = Succs[1]; 946 if (PostDomSucc->getSingleSuccessor() == InterimSucc) { 947 PostDomSucc = Succs[1]; 948 InterimSucc = Succs[0]; 949 } 950 assert(InterimSucc->getSingleSuccessor() == PostDomSucc && 951 "One successor of a basic block does not lead to the other."); 952 assert(InterimSucc->getSinglePredecessor() && 953 "Interim successor has more than one predecessor."); 954 assert(PostDomSucc->hasNPredecessors(2) && 955 "PostDom successor has more than two predecessors."); 956 DT->addNewBlock(InterimSucc, BB); 957 DT->addNewBlock(PostDomSucc, BB); 958 } 959 // Latch block is a new dominator for the loop exit. 960 DT->changeImmediateDominator(LoopExitBB, LoopLatchBB); 961 assert(DT->verify(DominatorTree::VerificationLevel::Fast)); 962 } 963 964 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 965 Twine VPlanPrinter::getUID(const VPBlockBase *Block) { 966 return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") + 967 Twine(getOrCreateBID(Block)); 968 } 969 970 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) { 971 const std::string &Name = Block->getName(); 972 if (!Name.empty()) 973 return Name; 974 return "VPB" + Twine(getOrCreateBID(Block)); 975 } 976 977 void VPlanPrinter::dump() { 978 Depth = 1; 979 bumpIndent(0); 980 OS << "digraph VPlan {\n"; 981 OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan"; 982 if (!Plan.getName().empty()) 983 OS << "\\n" << DOT::EscapeString(Plan.getName()); 984 if (Plan.BackedgeTakenCount) { 985 OS << ", where:\\n"; 986 Plan.BackedgeTakenCount->print(OS, SlotTracker); 987 OS << " := BackedgeTakenCount"; 988 } 989 OS << "\"]\n"; 990 OS << "node [shape=rect, fontname=Courier, fontsize=30]\n"; 991 OS << "edge [fontname=Courier, fontsize=30]\n"; 992 OS << "compound=true\n"; 993 994 for (const VPBlockBase *Block : depth_first(Plan.getEntry())) 995 dumpBlock(Block); 996 997 OS << "}\n"; 998 } 999 1000 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) { 1001 if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block)) 1002 dumpBasicBlock(BasicBlock); 1003 else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1004 dumpRegion(Region); 1005 else 1006 llvm_unreachable("Unsupported kind of VPBlock."); 1007 } 1008 1009 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To, 1010 bool Hidden, const Twine &Label) { 1011 // Due to "dot" we print an edge between two regions as an edge between the 1012 // exit basic block and the entry basic of the respective regions. 1013 const VPBlockBase *Tail = From->getExitBasicBlock(); 1014 const VPBlockBase *Head = To->getEntryBasicBlock(); 1015 OS << Indent << getUID(Tail) << " -> " << getUID(Head); 1016 OS << " [ label=\"" << Label << '\"'; 1017 if (Tail != From) 1018 OS << " ltail=" << getUID(From); 1019 if (Head != To) 1020 OS << " lhead=" << getUID(To); 1021 if (Hidden) 1022 OS << "; splines=none"; 1023 OS << "]\n"; 1024 } 1025 1026 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) { 1027 auto &Successors = Block->getSuccessors(); 1028 if (Successors.size() == 1) 1029 drawEdge(Block, Successors.front(), false, ""); 1030 else if (Successors.size() == 2) { 1031 drawEdge(Block, Successors.front(), false, "T"); 1032 drawEdge(Block, Successors.back(), false, "F"); 1033 } else { 1034 unsigned SuccessorNumber = 0; 1035 for (auto *Successor : Successors) 1036 drawEdge(Block, Successor, false, Twine(SuccessorNumber++)); 1037 } 1038 } 1039 1040 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) { 1041 // Implement dot-formatted dump by performing plain-text dump into the 1042 // temporary storage followed by some post-processing. 1043 OS << Indent << getUID(BasicBlock) << " [label =\n"; 1044 bumpIndent(1); 1045 std::string Str; 1046 raw_string_ostream SS(Str); 1047 // Use no indentation as we need to wrap the lines into quotes ourselves. 1048 BasicBlock->print(SS, "", SlotTracker); 1049 1050 // We need to process each line of the output separately, so split 1051 // single-string plain-text dump. 1052 SmallVector<StringRef, 0> Lines; 1053 StringRef(Str).rtrim('\n').split(Lines, "\n"); 1054 1055 auto EmitLine = [&](StringRef Line, StringRef Suffix) { 1056 OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix; 1057 }; 1058 1059 // Don't need the "+" after the last line. 1060 for (auto Line : make_range(Lines.begin(), Lines.end() - 1)) 1061 EmitLine(Line, " +\n"); 1062 EmitLine(Lines.back(), "\n"); 1063 1064 bumpIndent(-1); 1065 OS << Indent << "]\n"; 1066 1067 dumpEdges(BasicBlock); 1068 } 1069 1070 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) { 1071 OS << Indent << "subgraph " << getUID(Region) << " {\n"; 1072 bumpIndent(1); 1073 OS << Indent << "fontname=Courier\n" 1074 << Indent << "label=\"" 1075 << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ") 1076 << DOT::EscapeString(Region->getName()) << "\"\n"; 1077 // Dump the blocks of the region. 1078 assert(Region->getEntry() && "Region contains no inner blocks."); 1079 for (const VPBlockBase *Block : depth_first(Region->getEntry())) 1080 dumpBlock(Block); 1081 bumpIndent(-1); 1082 OS << Indent << "}\n"; 1083 dumpEdges(Region); 1084 } 1085 1086 void VPlanIngredient::print(raw_ostream &O) const { 1087 if (auto *Inst = dyn_cast<Instruction>(V)) { 1088 if (!Inst->getType()->isVoidTy()) { 1089 Inst->printAsOperand(O, false); 1090 O << " = "; 1091 } 1092 O << Inst->getOpcodeName() << " "; 1093 unsigned E = Inst->getNumOperands(); 1094 if (E > 0) { 1095 Inst->getOperand(0)->printAsOperand(O, false); 1096 for (unsigned I = 1; I < E; ++I) 1097 Inst->getOperand(I)->printAsOperand(O << ", ", false); 1098 } 1099 } else // !Inst 1100 V->printAsOperand(O, false); 1101 } 1102 1103 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent, 1104 VPSlotTracker &SlotTracker) const { 1105 O << Indent << "WIDEN-CALL "; 1106 1107 auto *CI = cast<CallInst>(getUnderlyingInstr()); 1108 if (CI->getType()->isVoidTy()) 1109 O << "void "; 1110 else { 1111 printAsOperand(O, SlotTracker); 1112 O << " = "; 1113 } 1114 1115 O << "call @" << CI->getCalledFunction()->getName() << "("; 1116 printOperands(O, SlotTracker); 1117 O << ")"; 1118 } 1119 1120 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent, 1121 VPSlotTracker &SlotTracker) const { 1122 O << Indent << "WIDEN-SELECT "; 1123 printAsOperand(O, SlotTracker); 1124 O << " = select "; 1125 getOperand(0)->printAsOperand(O, SlotTracker); 1126 O << ", "; 1127 getOperand(1)->printAsOperand(O, SlotTracker); 1128 O << ", "; 1129 getOperand(2)->printAsOperand(O, SlotTracker); 1130 O << (InvariantCond ? " (condition is loop invariant)" : ""); 1131 } 1132 1133 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent, 1134 VPSlotTracker &SlotTracker) const { 1135 O << Indent << "WIDEN "; 1136 printAsOperand(O, SlotTracker); 1137 O << " = " << getUnderlyingInstr()->getOpcodeName() << " "; 1138 printOperands(O, SlotTracker); 1139 } 1140 1141 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent, 1142 VPSlotTracker &SlotTracker) const { 1143 O << Indent << "WIDEN-INDUCTION"; 1144 if (getTruncInst()) { 1145 O << "\\l\""; 1146 O << " +\n" << Indent << "\" " << VPlanIngredient(IV) << "\\l\""; 1147 O << " +\n" << Indent << "\" "; 1148 getVPValue(0)->printAsOperand(O, SlotTracker); 1149 } else 1150 O << " " << VPlanIngredient(IV); 1151 } 1152 1153 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent, 1154 VPSlotTracker &SlotTracker) const { 1155 O << Indent << "WIDEN-GEP "; 1156 O << (IsPtrLoopInvariant ? "Inv" : "Var"); 1157 size_t IndicesNumber = IsIndexLoopInvariant.size(); 1158 for (size_t I = 0; I < IndicesNumber; ++I) 1159 O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]"; 1160 1161 O << " "; 1162 printAsOperand(O, SlotTracker); 1163 O << " = getelementptr "; 1164 printOperands(O, SlotTracker); 1165 } 1166 1167 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1168 VPSlotTracker &SlotTracker) const { 1169 O << Indent << "WIDEN-PHI "; 1170 1171 auto *OriginalPhi = cast<PHINode>(getUnderlyingValue()); 1172 // Unless all incoming values are modeled in VPlan print the original PHI 1173 // directly. 1174 // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming 1175 // values as VPValues. 1176 if (getNumOperands() != OriginalPhi->getNumOperands()) { 1177 O << VPlanIngredient(OriginalPhi); 1178 return; 1179 } 1180 1181 printAsOperand(O, SlotTracker); 1182 O << " = phi "; 1183 printOperands(O, SlotTracker); 1184 } 1185 1186 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent, 1187 VPSlotTracker &SlotTracker) const { 1188 O << Indent << "BLEND "; 1189 Phi->printAsOperand(O, false); 1190 O << " ="; 1191 if (getNumIncomingValues() == 1) { 1192 // Not a User of any mask: not really blending, this is a 1193 // single-predecessor phi. 1194 O << " "; 1195 getIncomingValue(0)->printAsOperand(O, SlotTracker); 1196 } else { 1197 for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) { 1198 O << " "; 1199 getIncomingValue(I)->printAsOperand(O, SlotTracker); 1200 O << "/"; 1201 getMask(I)->printAsOperand(O, SlotTracker); 1202 } 1203 } 1204 } 1205 1206 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent, 1207 VPSlotTracker &SlotTracker) const { 1208 O << Indent << "REDUCE "; 1209 printAsOperand(O, SlotTracker); 1210 O << " = "; 1211 getChainOp()->printAsOperand(O, SlotTracker); 1212 O << " +"; 1213 if (isa<FPMathOperator>(getUnderlyingInstr())) 1214 O << getUnderlyingInstr()->getFastMathFlags(); 1215 O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " ("; 1216 getVecOp()->printAsOperand(O, SlotTracker); 1217 if (getCondOp()) { 1218 O << ", "; 1219 getCondOp()->printAsOperand(O, SlotTracker); 1220 } 1221 O << ")"; 1222 } 1223 1224 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent, 1225 VPSlotTracker &SlotTracker) const { 1226 O << Indent << (IsUniform ? "CLONE " : "REPLICATE "); 1227 1228 if (!getUnderlyingInstr()->getType()->isVoidTy()) { 1229 printAsOperand(O, SlotTracker); 1230 O << " = "; 1231 } 1232 O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " "; 1233 printOperands(O, SlotTracker); 1234 1235 if (AlsoPack) 1236 O << " (S->V)"; 1237 } 1238 1239 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1240 VPSlotTracker &SlotTracker) const { 1241 O << Indent << "PHI-PREDICATED-INSTRUCTION "; 1242 printAsOperand(O, SlotTracker); 1243 O << " = "; 1244 printOperands(O, SlotTracker); 1245 } 1246 1247 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent, 1248 VPSlotTracker &SlotTracker) const { 1249 O << Indent << "WIDEN "; 1250 1251 if (!isStore()) { 1252 getVPSingleValue()->printAsOperand(O, SlotTracker); 1253 O << " = "; 1254 } 1255 O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " "; 1256 1257 printOperands(O, SlotTracker); 1258 } 1259 #endif 1260 1261 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) { 1262 Value *CanonicalIV = State.CanonicalIV; 1263 Type *STy = CanonicalIV->getType(); 1264 IRBuilder<> Builder(State.CFG.PrevBB->getTerminator()); 1265 ElementCount VF = State.VF; 1266 assert(!VF.isScalable() && "the code following assumes non scalables ECs"); 1267 Value *VStart = VF.isScalar() 1268 ? CanonicalIV 1269 : Builder.CreateVectorSplat(VF.getKnownMinValue(), 1270 CanonicalIV, "broadcast"); 1271 for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) { 1272 SmallVector<Constant *, 8> Indices; 1273 for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane) 1274 Indices.push_back( 1275 ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane)); 1276 // If VF == 1, there is only one iteration in the loop above, thus the 1277 // element pushed back into Indices is ConstantInt::get(STy, Part) 1278 Constant *VStep = 1279 VF.isScalar() ? Indices.back() : ConstantVector::get(Indices); 1280 // Add the consecutive indices to the vector value. 1281 Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv"); 1282 State.set(this, CanonicalVectorIV, Part); 1283 } 1284 } 1285 1286 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1287 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent, 1288 VPSlotTracker &SlotTracker) const { 1289 O << Indent << "EMIT "; 1290 printAsOperand(O, SlotTracker); 1291 O << " = WIDEN-CANONICAL-INDUCTION"; 1292 } 1293 #endif 1294 1295 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) { 1296 auto &Builder = State.Builder; 1297 // Create a vector from the initial value. 1298 auto *VectorInit = getStartValue()->getLiveInIRValue(); 1299 1300 Type *VecTy = State.VF.isScalar() 1301 ? VectorInit->getType() 1302 : VectorType::get(VectorInit->getType(), State.VF); 1303 1304 if (State.VF.isVector()) { 1305 auto *IdxTy = Builder.getInt32Ty(); 1306 auto *One = ConstantInt::get(IdxTy, 1); 1307 IRBuilder<>::InsertPointGuard Guard(Builder); 1308 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1309 auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF); 1310 auto *LastIdx = Builder.CreateSub(RuntimeVF, One); 1311 VectorInit = Builder.CreateInsertElement( 1312 PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init"); 1313 } 1314 1315 // Create a phi node for the new recurrence. 1316 PHINode *EntryPart = PHINode::Create( 1317 VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt()); 1318 EntryPart->addIncoming(VectorInit, State.CFG.VectorPreHeader); 1319 State.set(this, EntryPart, 0); 1320 } 1321 1322 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1323 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent, 1324 VPSlotTracker &SlotTracker) const { 1325 O << Indent << "FIRST-ORDER-RECURRENCE-PHI "; 1326 printAsOperand(O, SlotTracker); 1327 O << " = phi "; 1328 printOperands(O, SlotTracker); 1329 } 1330 #endif 1331 1332 void VPReductionPHIRecipe::execute(VPTransformState &State) { 1333 PHINode *PN = cast<PHINode>(getUnderlyingValue()); 1334 auto &Builder = State.Builder; 1335 1336 // In order to support recurrences we need to be able to vectorize Phi nodes. 1337 // Phi nodes have cycles, so we need to vectorize them in two stages. This is 1338 // stage #1: We create a new vector PHI node with no incoming edges. We'll use 1339 // this value when we vectorize all of the instructions that use the PHI. 1340 bool ScalarPHI = State.VF.isScalar() || IsInLoop; 1341 Type *VecTy = 1342 ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF); 1343 1344 BasicBlock *HeaderBB = State.CFG.PrevBB; 1345 assert(State.LI->getLoopFor(HeaderBB)->getHeader() == HeaderBB && 1346 "recipe must be in the vector loop header"); 1347 unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF; 1348 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1349 Value *EntryPart = 1350 PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt()); 1351 State.set(this, EntryPart, Part); 1352 } 1353 1354 // Reductions do not have to start at zero. They can start with 1355 // any loop invariant values. 1356 VPValue *StartVPV = getStartValue(); 1357 Value *StartV = StartVPV->getLiveInIRValue(); 1358 1359 Value *Iden = nullptr; 1360 RecurKind RK = RdxDesc.getRecurrenceKind(); 1361 if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) || 1362 RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) { 1363 // MinMax reduction have the start value as their identify. 1364 if (ScalarPHI) { 1365 Iden = StartV; 1366 } else { 1367 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1368 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1369 StartV = Iden = 1370 Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident"); 1371 } 1372 } else { 1373 Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(), 1374 RdxDesc.getFastMathFlags()); 1375 1376 if (!ScalarPHI) { 1377 Iden = Builder.CreateVectorSplat(State.VF, Iden); 1378 IRBuilderBase::InsertPointGuard IPBuilder(Builder); 1379 Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator()); 1380 Constant *Zero = Builder.getInt32(0); 1381 StartV = Builder.CreateInsertElement(Iden, StartV, Zero); 1382 } 1383 } 1384 1385 for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) { 1386 Value *EntryPart = State.get(this, Part); 1387 // Make sure to add the reduction start value only to the 1388 // first unroll part. 1389 Value *StartVal = (Part == 0) ? StartV : Iden; 1390 cast<PHINode>(EntryPart)->addIncoming(StartVal, State.CFG.VectorPreHeader); 1391 } 1392 } 1393 1394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1395 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent, 1396 VPSlotTracker &SlotTracker) const { 1397 O << Indent << "WIDEN-REDUCTION-PHI "; 1398 1399 printAsOperand(O, SlotTracker); 1400 O << " = phi "; 1401 printOperands(O, SlotTracker); 1402 } 1403 #endif 1404 1405 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT); 1406 1407 void VPValue::replaceAllUsesWith(VPValue *New) { 1408 for (unsigned J = 0; J < getNumUsers();) { 1409 VPUser *User = Users[J]; 1410 unsigned NumUsers = getNumUsers(); 1411 for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) 1412 if (User->getOperand(I) == this) 1413 User->setOperand(I, New); 1414 // If a user got removed after updating the current user, the next user to 1415 // update will be moved to the current position, so we only need to 1416 // increment the index if the number of users did not change. 1417 if (NumUsers == getNumUsers()) 1418 J++; 1419 } 1420 } 1421 1422 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1423 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const { 1424 if (const Value *UV = getUnderlyingValue()) { 1425 OS << "ir<"; 1426 UV->printAsOperand(OS, false); 1427 OS << ">"; 1428 return; 1429 } 1430 1431 unsigned Slot = Tracker.getSlot(this); 1432 if (Slot == unsigned(-1)) 1433 OS << "<badref>"; 1434 else 1435 OS << "vp<%" << Tracker.getSlot(this) << ">"; 1436 } 1437 1438 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const { 1439 interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) { 1440 Op->printAsOperand(O, SlotTracker); 1441 }); 1442 } 1443 #endif 1444 1445 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region, 1446 Old2NewTy &Old2New, 1447 InterleavedAccessInfo &IAI) { 1448 ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry()); 1449 for (VPBlockBase *Base : RPOT) { 1450 visitBlock(Base, Old2New, IAI); 1451 } 1452 } 1453 1454 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New, 1455 InterleavedAccessInfo &IAI) { 1456 if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) { 1457 for (VPRecipeBase &VPI : *VPBB) { 1458 if (isa<VPWidenPHIRecipe>(&VPI)) 1459 continue; 1460 assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions"); 1461 auto *VPInst = cast<VPInstruction>(&VPI); 1462 auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue()); 1463 auto *IG = IAI.getInterleaveGroup(Inst); 1464 if (!IG) 1465 continue; 1466 1467 auto NewIGIter = Old2New.find(IG); 1468 if (NewIGIter == Old2New.end()) 1469 Old2New[IG] = new InterleaveGroup<VPInstruction>( 1470 IG->getFactor(), IG->isReverse(), IG->getAlign()); 1471 1472 if (Inst == IG->getInsertPos()) 1473 Old2New[IG]->setInsertPos(VPInst); 1474 1475 InterleaveGroupMap[VPInst] = Old2New[IG]; 1476 InterleaveGroupMap[VPInst]->insertMember( 1477 VPInst, IG->getIndex(Inst), 1478 Align(IG->isReverse() ? (-1) * int(IG->getFactor()) 1479 : IG->getFactor())); 1480 } 1481 } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block)) 1482 visitRegion(Region, Old2New, IAI); 1483 else 1484 llvm_unreachable("Unsupported kind of VPBlock."); 1485 } 1486 1487 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan, 1488 InterleavedAccessInfo &IAI) { 1489 Old2NewTy Old2New; 1490 visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI); 1491 } 1492 1493 void VPSlotTracker::assignSlot(const VPValue *V) { 1494 assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!"); 1495 Slots[V] = NextSlot++; 1496 } 1497 1498 void VPSlotTracker::assignSlots(const VPlan &Plan) { 1499 1500 for (const VPValue *V : Plan.VPExternalDefs) 1501 assignSlot(V); 1502 1503 if (Plan.BackedgeTakenCount) 1504 assignSlot(Plan.BackedgeTakenCount); 1505 1506 ReversePostOrderTraversal< 1507 VPBlockRecursiveTraversalWrapper<const VPBlockBase *>> 1508 RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>( 1509 Plan.getEntry())); 1510 for (const VPBasicBlock *VPBB : 1511 VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT)) 1512 for (const VPRecipeBase &Recipe : *VPBB) 1513 for (VPValue *Def : Recipe.definedValues()) 1514 assignSlot(Def); 1515 } 1516