VPlanHCFGBuilder.cpp 14 KB

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