1 //===-- VPlanHCFGBuilder.cpp ----------------------------------------------===// 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 file implements the construction of a VPlan-based Hierarchical CFG 11 /// (H-CFG) for an incoming IR. This construction comprises the following 12 /// components and steps: 13 // 14 /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that 15 /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top 16 /// Region) is created to enclose and serve as parent of all the VPBasicBlocks 17 /// in the plain CFG. 18 /// NOTE: At this point, there is a direct correspondence between all the 19 /// VPBasicBlocks created for the initial plain CFG and the incoming 20 /// BasicBlocks. However, this might change in the future. 21 /// 22 //===----------------------------------------------------------------------===// 23 24 #include "VPlanHCFGBuilder.h" 25 #include "LoopVectorizationPlanner.h" 26 #include "llvm/Analysis/LoopIterator.h" 27 28 #define DEBUG_TYPE "loop-vectorize" 29 30 using namespace llvm; 31 32 namespace { 33 // Class that is used to build the plain CFG for the incoming IR. 34 class PlainCFGBuilder { 35 private: 36 // The outermost loop of the input loop nest considered for vectorization. 37 Loop *TheLoop; 38 39 // Loop Info analysis. 40 LoopInfo *LI; 41 42 // Vectorization plan that we are working on. 43 VPlan &Plan; 44 45 // Output Top Region. 46 VPRegionBlock *TopRegion = nullptr; 47 48 // Builder of the VPlan instruction-level representation. 49 VPBuilder VPIRBuilder; 50 51 // NOTE: The following maps are intentionally destroyed after the plain CFG 52 // construction because subsequent VPlan-to-VPlan transformation may 53 // invalidate them. 54 // Map incoming BasicBlocks to their newly-created VPBasicBlocks. 55 DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB; 56 // Map incoming Value definitions to their newly-created VPValues. 57 DenseMap<Value *, VPValue *> IRDef2VPValue; 58 59 // Hold phi node's that need to be fixed once the plain CFG has been built. 60 SmallVector<PHINode *, 8> PhisToFix; 61 62 // Utility functions. 63 void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB); 64 void fixPhiNodes(); 65 VPBasicBlock *getOrCreateVPBB(BasicBlock *BB); 66 bool isExternalDef(Value *Val); 67 VPValue *getOrCreateVPOperand(Value *IRVal); 68 void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB); 69 70 public: 71 PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P) 72 : TheLoop(Lp), LI(LI), Plan(P) {} 73 74 // Build the plain CFG and return its Top Region. 75 VPRegionBlock *buildPlainCFG(); 76 }; 77 } // anonymous namespace 78 79 // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB 80 // must have no predecessors. 81 void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) { 82 SmallVector<VPBlockBase *, 8> VPBBPreds; 83 // Collect VPBB predecessors. 84 for (BasicBlock *Pred : predecessors(BB)) 85 VPBBPreds.push_back(getOrCreateVPBB(Pred)); 86 87 VPBB->setPredecessors(VPBBPreds); 88 } 89 90 // Add operands to VPInstructions representing phi nodes from the input IR. 91 void PlainCFGBuilder::fixPhiNodes() { 92 for (auto *Phi : PhisToFix) { 93 assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode."); 94 VPValue *VPVal = IRDef2VPValue[Phi]; 95 assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node."); 96 auto *VPPhi = cast<VPInstruction>(VPVal); 97 assert(VPPhi->getNumOperands() == 0 && 98 "Expected VPInstruction with no operands."); 99 100 for (Value *Op : Phi->operands()) 101 VPPhi->addOperand(getOrCreateVPOperand(Op)); 102 } 103 } 104 105 // Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an 106 // existing one if it was already created. 107 VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) { 108 auto BlockIt = BB2VPBB.find(BB); 109 if (BlockIt != BB2VPBB.end()) 110 // Retrieve existing VPBB. 111 return BlockIt->second; 112 113 // Create new VPBB. 114 LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n"); 115 VPBasicBlock *VPBB = new VPBasicBlock(BB->getName()); 116 BB2VPBB[BB] = VPBB; 117 VPBB->setParent(TopRegion); 118 return VPBB; 119 } 120 121 // Return true if \p Val is considered an external definition. An external 122 // definition is either: 123 // 1. A Value that is not an Instruction. This will be refined in the future. 124 // 2. An Instruction that is outside of the CFG snippet represented in VPlan, 125 // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c) 126 // outermost loop exits. 127 bool PlainCFGBuilder::isExternalDef(Value *Val) { 128 // All the Values that are not Instructions are considered external 129 // definitions for now. 130 Instruction *Inst = dyn_cast<Instruction>(Val); 131 if (!Inst) 132 return true; 133 134 BasicBlock *InstParent = Inst->getParent(); 135 assert(InstParent && "Expected instruction parent."); 136 137 // Check whether Instruction definition is in loop PH. 138 BasicBlock *PH = TheLoop->getLoopPreheader(); 139 assert(PH && "Expected loop pre-header."); 140 141 if (InstParent == PH) 142 // Instruction definition is in outermost loop PH. 143 return false; 144 145 // Check whether Instruction definition is in the loop exit. 146 BasicBlock *Exit = TheLoop->getUniqueExitBlock(); 147 assert(Exit && "Expected loop with single exit."); 148 if (InstParent == Exit) { 149 // Instruction definition is in outermost loop exit. 150 return false; 151 } 152 153 // Check whether Instruction definition is in loop body. 154 return !TheLoop->contains(Inst); 155 } 156 157 // Create a new VPValue or retrieve an existing one for the Instruction's 158 // operand \p IRVal. This function must only be used to create/retrieve VPValues 159 // for *Instruction's operands* and not to create regular VPInstruction's. For 160 // the latter, please, look at 'createVPInstructionsForVPBB'. 161 VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) { 162 auto VPValIt = IRDef2VPValue.find(IRVal); 163 if (VPValIt != IRDef2VPValue.end()) 164 // Operand has an associated VPInstruction or VPValue that was previously 165 // created. 166 return VPValIt->second; 167 168 // Operand doesn't have a previously created VPInstruction/VPValue. This 169 // means that operand is: 170 // A) a definition external to VPlan, 171 // B) any other Value without specific representation in VPlan. 172 // For now, we use VPValue to represent A and B and classify both as external 173 // definitions. We may introduce specific VPValue subclasses for them in the 174 // future. 175 assert(isExternalDef(IRVal) && "Expected external definition as operand."); 176 177 // A and B: Create VPValue and add it to the pool of external definitions and 178 // to the Value->VPValue map. 179 VPValue *NewVPVal = new VPValue(IRVal); 180 Plan.addExternalDef(NewVPVal); 181 IRDef2VPValue[IRVal] = NewVPVal; 182 return NewVPVal; 183 } 184 185 // Create new VPInstructions in a VPBasicBlock, given its BasicBlock 186 // counterpart. This function must be invoked in RPO so that the operands of a 187 // VPInstruction in \p BB have been visited before (except for Phi nodes). 188 void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB, 189 BasicBlock *BB) { 190 VPIRBuilder.setInsertPoint(VPBB); 191 for (Instruction &InstRef : *BB) { 192 Instruction *Inst = &InstRef; 193 194 // There shouldn't be any VPValue for Inst at this point. Otherwise, we 195 // visited Inst when we shouldn't, breaking the RPO traversal order. 196 assert(!IRDef2VPValue.count(Inst) && 197 "Instruction shouldn't have been visited."); 198 199 if (auto *Br = dyn_cast<BranchInst>(Inst)) { 200 // Branch instruction is not explicitly represented in VPlan but we need 201 // to represent its condition bit when it's conditional. 202 if (Br->isConditional()) 203 getOrCreateVPOperand(Br->getCondition()); 204 205 // Skip the rest of the Instruction processing for Branch instructions. 206 continue; 207 } 208 209 VPInstruction *NewVPInst; 210 if (auto *Phi = dyn_cast<PHINode>(Inst)) { 211 // Phi node's operands may have not been visited at this point. We create 212 // an empty VPInstruction that we will fix once the whole plain CFG has 213 // been built. 214 NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp( 215 Inst->getOpcode(), {} /*No operands*/, Inst)); 216 PhisToFix.push_back(Phi); 217 } else { 218 // Translate LLVM-IR operands into VPValue operands and set them in the 219 // new VPInstruction. 220 SmallVector<VPValue *, 4> VPOperands; 221 for (Value *Op : Inst->operands()) 222 VPOperands.push_back(getOrCreateVPOperand(Op)); 223 224 // Build VPInstruction for any arbitraty Instruction without specific 225 // representation in VPlan. 226 NewVPInst = cast<VPInstruction>( 227 VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst)); 228 } 229 230 IRDef2VPValue[Inst] = NewVPInst; 231 } 232 } 233 234 // Main interface to build the plain CFG. 235 VPRegionBlock *PlainCFGBuilder::buildPlainCFG() { 236 // 1. Create the Top Region. It will be the parent of all VPBBs. 237 TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/); 238 239 // 2. Scan the body of the loop in a topological order to visit each basic 240 // block after having visited its predecessor basic blocks. Create a VPBB for 241 // each BB and link it to its successor and predecessor VPBBs. Note that 242 // predecessors must be set in the same order as they are in the incomming IR. 243 // Otherwise, there might be problems with existing phi nodes and algorithm 244 // based on predecessors traversal. 245 246 // Loop PH needs to be explicitly visited since it's not taken into account by 247 // LoopBlocksDFS. 248 BasicBlock *PreheaderBB = TheLoop->getLoopPreheader(); 249 assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) && 250 "Unexpected loop preheader"); 251 VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB); 252 createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB); 253 // Create empty VPBB for Loop H so that we can link PH->H. 254 VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader()); 255 // Preheader's predecessors will be set during the loop RPO traversal below. 256 PreheaderVPBB->setOneSuccessor(HeaderVPBB); 257 258 LoopBlocksRPO RPO(TheLoop); 259 RPO.perform(LI); 260 261 for (BasicBlock *BB : RPO) { 262 // Create or retrieve the VPBasicBlock for this BB and create its 263 // VPInstructions. 264 VPBasicBlock *VPBB = getOrCreateVPBB(BB); 265 createVPInstructionsForVPBB(VPBB, BB); 266 267 // Set VPBB successors. We create empty VPBBs for successors if they don't 268 // exist already. Recipes will be created when the successor is visited 269 // during the RPO traversal. 270 Instruction *TI = BB->getTerminator(); 271 assert(TI && "Terminator expected."); 272 unsigned NumSuccs = TI->getNumSuccessors(); 273 274 if (NumSuccs == 1) { 275 VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0)); 276 assert(SuccVPBB && "VPBB Successor not found."); 277 VPBB->setOneSuccessor(SuccVPBB); 278 } else if (NumSuccs == 2) { 279 VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0)); 280 assert(SuccVPBB0 && "Successor 0 not found."); 281 VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1)); 282 assert(SuccVPBB1 && "Successor 1 not found."); 283 284 // Get VPBB's condition bit. 285 assert(isa<BranchInst>(TI) && "Unsupported terminator!"); 286 auto *Br = cast<BranchInst>(TI); 287 Value *BrCond = Br->getCondition(); 288 // Look up the branch condition to get the corresponding VPValue 289 // representing the condition bit in VPlan (which may be in another VPBB). 290 assert(IRDef2VPValue.count(BrCond) && 291 "Missing condition bit in IRDef2VPValue!"); 292 VPValue *VPCondBit = IRDef2VPValue[BrCond]; 293 294 // Link successors using condition bit. 295 VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1, VPCondBit); 296 } else 297 llvm_unreachable("Number of successors not supported."); 298 299 // Set VPBB predecessors in the same order as they are in the incoming BB. 300 setVPBBPredsFromBB(VPBB, BB); 301 } 302 303 // 3. Process outermost loop exit. We created an empty VPBB for the loop 304 // single exit BB during the RPO traversal of the loop body but Instructions 305 // weren't visited because it's not part of the the loop. 306 BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock(); 307 assert(LoopExitBB && "Loops with multiple exits are not supported."); 308 VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB]; 309 createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB); 310 // Loop exit was already set as successor of the loop exiting BB. 311 // We only set its predecessor VPBB now. 312 setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB); 313 314 // 4. The whole CFG has been built at this point so all the input Values must 315 // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding 316 // VPlan operands. 317 fixPhiNodes(); 318 319 // 5. Final Top Region setup. Set outermost loop pre-header and single exit as 320 // Top Region entry and exit. 321 TopRegion->setEntry(PreheaderVPBB); 322 TopRegion->setExit(LoopExitVPBB); 323 return TopRegion; 324 } 325 326 VPRegionBlock *VPlanHCFGBuilder::buildPlainCFG() { 327 PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan); 328 return PCFGBuilder.buildPlainCFG(); 329 } 330 331 // Public interface to build a H-CFG. 332 void VPlanHCFGBuilder::buildHierarchicalCFG() { 333 // Build Top Region enclosing the plain CFG and set it as VPlan entry. 334 VPRegionBlock *TopRegion = buildPlainCFG(); 335 Plan.setEntry(TopRegion); 336 LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan); 337 338 Verifier.verifyHierarchicalCFG(TopRegion); 339 340 // Compute plain CFG dom tree for VPLInfo. 341 VPDomTree.recalculate(*TopRegion); 342 LLVM_DEBUG(dbgs() << "Dominator Tree after building the plain CFG.\n"; 343 VPDomTree.print(dbgs())); 344 345 // Compute VPLInfo and keep it in Plan. 346 VPLoopInfo &VPLInfo = Plan.getVPLoopInfo(); 347 VPLInfo.analyze(VPDomTree); 348 LLVM_DEBUG(dbgs() << "VPLoop Info After buildPlainCFG:\n"; 349 VPLInfo.print(dbgs())); 350 } 351