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