VPlanHCFGBuilder.cpp 14 KB

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