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   // Builder of the VPlan instruction-level representation.
46   VPBuilder VPIRBuilder;
47 
48   // NOTE: The following maps are intentionally destroyed after the plain CFG
49   // construction because subsequent VPlan-to-VPlan transformation may
50   // invalidate them.
51   // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
52   DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
53   // Map incoming Value definitions to their newly-created VPValues.
54   DenseMap<Value *, VPValue *> IRDef2VPValue;
55 
56   // Hold phi node's that need to be fixed once the plain CFG has been built.
57   SmallVector<PHINode *, 8> PhisToFix;
58 
59   /// Maps loops in the original IR to their corresponding region.
60   DenseMap<Loop *, VPRegionBlock *> Loop2Region;
61 
62   // Utility functions.
63   void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
64   void fixPhiNodes();
65   VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
66 #ifndef NDEBUG
67   bool isExternalDef(Value *Val);
68 #endif
69   VPValue *getOrCreateVPOperand(Value *IRVal);
70   void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
71 
72 public:
73   PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
74       : TheLoop(Lp), LI(LI), Plan(P) {}
75 
76   /// Build plain CFG for TheLoop  and connects it to Plan's entry.
77   void buildPlainCFG();
78 };
79 } // anonymous namespace
80 
81 // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
82 // must have no predecessors.
83 void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
84   SmallVector<VPBlockBase *, 8> VPBBPreds;
85   // Collect VPBB predecessors.
86   for (BasicBlock *Pred : predecessors(BB))
87     VPBBPreds.push_back(getOrCreateVPBB(Pred));
88 
89   VPBB->setPredecessors(VPBBPreds);
90 }
91 
92 // Add operands to VPInstructions representing phi nodes from the input IR.
93 void PlainCFGBuilder::fixPhiNodes() {
94   for (auto *Phi : PhisToFix) {
95     assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
96     VPValue *VPVal = IRDef2VPValue[Phi];
97     assert(isa<VPWidenPHIRecipe>(VPVal) &&
98            "Expected WidenPHIRecipe for phi node.");
99     auto *VPPhi = cast<VPWidenPHIRecipe>(VPVal);
100     assert(VPPhi->getNumOperands() == 0 &&
101            "Expected VPInstruction with no operands.");
102 
103     for (unsigned I = 0; I != Phi->getNumOperands(); ++I)
104       VPPhi->addIncoming(getOrCreateVPOperand(Phi->getIncomingValue(I)),
105                          BB2VPBB[Phi->getIncomingBlock(I)]);
106   }
107 }
108 
109 // Create a new empty VPBasicBlock for an incoming BasicBlock in the region
110 // corresponding to the containing loop  or retrieve an existing one if it was
111 // already created. If no region exists yet for the loop containing \p BB, a new
112 // one is created.
113 VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
114   auto BlockIt = BB2VPBB.find(BB);
115   if (BlockIt != BB2VPBB.end())
116     // Retrieve existing VPBB.
117     return BlockIt->second;
118 
119   // Get or create a region for the loop containing BB.
120   Loop *CurrentLoop = LI->getLoopFor(BB);
121   VPRegionBlock *ParentR = nullptr;
122   if (CurrentLoop) {
123     auto Iter = Loop2Region.insert({CurrentLoop, nullptr});
124     if (Iter.second)
125       Iter.first->second = new VPRegionBlock(
126           CurrentLoop->getHeader()->getName().str(), false /*isReplicator*/);
127     ParentR = Iter.first->second;
128   }
129 
130   // Create new VPBB.
131   LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n");
132   VPBasicBlock *VPBB = new VPBasicBlock(BB->getName());
133   BB2VPBB[BB] = VPBB;
134   VPBB->setParent(ParentR);
135   return VPBB;
136 }
137 
138 #ifndef NDEBUG
139 // Return true if \p Val is considered an external definition. An external
140 // definition is either:
141 // 1. A Value that is not an Instruction. This will be refined in the future.
142 // 2. An Instruction that is outside of the CFG snippet represented in VPlan,
143 // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
144 // outermost loop exits.
145 bool PlainCFGBuilder::isExternalDef(Value *Val) {
146   // All the Values that are not Instructions are considered external
147   // definitions for now.
148   Instruction *Inst = dyn_cast<Instruction>(Val);
149   if (!Inst)
150     return true;
151 
152   BasicBlock *InstParent = Inst->getParent();
153   assert(InstParent && "Expected instruction parent.");
154 
155   // Check whether Instruction definition is in loop PH.
156   BasicBlock *PH = TheLoop->getLoopPreheader();
157   assert(PH && "Expected loop pre-header.");
158 
159   if (InstParent == PH)
160     // Instruction definition is in outermost loop PH.
161     return false;
162 
163   // Check whether Instruction definition is in the loop exit.
164   BasicBlock *Exit = TheLoop->getUniqueExitBlock();
165   assert(Exit && "Expected loop with single exit.");
166   if (InstParent == Exit) {
167     // Instruction definition is in outermost loop exit.
168     return false;
169   }
170 
171   // Check whether Instruction definition is in loop body.
172   return !TheLoop->contains(Inst);
173 }
174 #endif
175 
176 // Create a new VPValue or retrieve an existing one for the Instruction's
177 // operand \p IRVal. This function must only be used to create/retrieve VPValues
178 // for *Instruction's operands* and not to create regular VPInstruction's. For
179 // the latter, please, look at 'createVPInstructionsForVPBB'.
180 VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
181   auto VPValIt = IRDef2VPValue.find(IRVal);
182   if (VPValIt != IRDef2VPValue.end())
183     // Operand has an associated VPInstruction or VPValue that was previously
184     // created.
185     return VPValIt->second;
186 
187   // Operand doesn't have a previously created VPInstruction/VPValue. This
188   // means that operand is:
189   //   A) a definition external to VPlan,
190   //   B) any other Value without specific representation in VPlan.
191   // For now, we use VPValue to represent A and B and classify both as external
192   // definitions. We may introduce specific VPValue subclasses for them in the
193   // future.
194   assert(isExternalDef(IRVal) && "Expected external definition as operand.");
195 
196   // A and B: Create VPValue and add it to the pool of external definitions and
197   // to the Value->VPValue map.
198   VPValue *NewVPVal = Plan.getVPValueOrAddLiveIn(IRVal);
199   IRDef2VPValue[IRVal] = NewVPVal;
200   return NewVPVal;
201 }
202 
203 // Create new VPInstructions in a VPBasicBlock, given its BasicBlock
204 // counterpart. This function must be invoked in RPO so that the operands of a
205 // VPInstruction in \p BB have been visited before (except for Phi nodes).
206 void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
207                                                   BasicBlock *BB) {
208   VPIRBuilder.setInsertPoint(VPBB);
209   for (Instruction &InstRef : *BB) {
210     Instruction *Inst = &InstRef;
211 
212     // There shouldn't be any VPValue for Inst at this point. Otherwise, we
213     // visited Inst when we shouldn't, breaking the RPO traversal order.
214     assert(!IRDef2VPValue.count(Inst) &&
215            "Instruction shouldn't have been visited.");
216 
217     if (auto *Br = dyn_cast<BranchInst>(Inst)) {
218       // Conditional branch instruction are represented using BranchOnCond
219       // recipes.
220       if (Br->isConditional()) {
221         VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
222         VPBB->appendRecipe(
223             new VPInstruction(VPInstruction::BranchOnCond, {Cond}));
224       }
225 
226       // Skip the rest of the Instruction processing for Branch instructions.
227       continue;
228     }
229 
230     VPValue *NewVPV;
231     if (auto *Phi = dyn_cast<PHINode>(Inst)) {
232       // Phi node's operands may have not been visited at this point. We create
233       // an empty VPInstruction that we will fix once the whole plain CFG has
234       // been built.
235       NewVPV = new VPWidenPHIRecipe(Phi);
236       VPBB->appendRecipe(cast<VPWidenPHIRecipe>(NewVPV));
237       PhisToFix.push_back(Phi);
238     } else {
239       // Translate LLVM-IR operands into VPValue operands and set them in the
240       // new VPInstruction.
241       SmallVector<VPValue *, 4> VPOperands;
242       for (Value *Op : Inst->operands())
243         VPOperands.push_back(getOrCreateVPOperand(Op));
244 
245       // Build VPInstruction for any arbitrary Instruction without specific
246       // representation in VPlan.
247       NewVPV = cast<VPInstruction>(
248           VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
249     }
250 
251     IRDef2VPValue[Inst] = NewVPV;
252   }
253 }
254 
255 // Main interface to build the plain CFG.
256 void PlainCFGBuilder::buildPlainCFG() {
257   // 1. Scan the body of the loop in a topological order to visit each basic
258   // block after having visited its predecessor basic blocks. Create a VPBB for
259   // each BB and link it to its successor and predecessor VPBBs. Note that
260   // predecessors must be set in the same order as they are in the incomming IR.
261   // Otherwise, there might be problems with existing phi nodes and algorithm
262   // based on predecessors traversal.
263 
264   // Loop PH needs to be explicitly visited since it's not taken into account by
265   // LoopBlocksDFS.
266   BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
267   assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
268          "Unexpected loop preheader");
269   VPBasicBlock *ThePreheaderVPBB = Plan.getEntry();
270   BB2VPBB[ThePreheaderBB] = ThePreheaderVPBB;
271   ThePreheaderVPBB->setName("vector.ph");
272   for (auto &I : *ThePreheaderBB) {
273     if (I.getType()->isVoidTy())
274       continue;
275     IRDef2VPValue[&I] = Plan.getVPValueOrAddLiveIn(&I);
276   }
277   // Create empty VPBB for Loop H so that we can link PH->H.
278   VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader());
279   HeaderVPBB->setName("vector.body");
280   ThePreheaderVPBB->setOneSuccessor(HeaderVPBB);
281 
282   LoopBlocksRPO RPO(TheLoop);
283   RPO.perform(LI);
284 
285   for (BasicBlock *BB : RPO) {
286     // Create or retrieve the VPBasicBlock for this BB and create its
287     // VPInstructions.
288     VPBasicBlock *VPBB = getOrCreateVPBB(BB);
289     createVPInstructionsForVPBB(VPBB, BB);
290 
291     // Set VPBB successors. We create empty VPBBs for successors if they don't
292     // exist already. Recipes will be created when the successor is visited
293     // during the RPO traversal.
294     Instruction *TI = BB->getTerminator();
295     assert(TI && "Terminator expected.");
296     unsigned NumSuccs = TI->getNumSuccessors();
297 
298     if (NumSuccs == 1) {
299       VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0));
300       assert(SuccVPBB && "VPBB Successor not found.");
301       VPBB->setOneSuccessor(SuccVPBB);
302     } else if (NumSuccs == 2) {
303       VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0));
304       assert(SuccVPBB0 && "Successor 0 not found.");
305       VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1));
306       assert(SuccVPBB1 && "Successor 1 not found.");
307 
308       // Get VPBB's condition bit.
309       assert(isa<BranchInst>(TI) && "Unsupported terminator!");
310       // Look up the branch condition to get the corresponding VPValue
311       // representing the condition bit in VPlan (which may be in another VPBB).
312       assert(IRDef2VPValue.count(cast<BranchInst>(TI)->getCondition()) &&
313              "Missing condition bit in IRDef2VPValue!");
314 
315       // Link successors.
316       VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1);
317     } else
318       llvm_unreachable("Number of successors not supported.");
319 
320     // Set VPBB predecessors in the same order as they are in the incoming BB.
321     setVPBBPredsFromBB(VPBB, BB);
322   }
323 
324   // 2. Process outermost loop exit. We created an empty VPBB for the loop
325   // single exit BB during the RPO traversal of the loop body but Instructions
326   // weren't visited because it's not part of the the loop.
327   BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
328   assert(LoopExitBB && "Loops with multiple exits are not supported.");
329   VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB];
330   // Loop exit was already set as successor of the loop exiting BB.
331   // We only set its predecessor VPBB now.
332   setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB);
333 
334   // 3. Fix up region blocks for loops. For each loop,
335   //   * use the header block as entry to the corresponding region,
336   //   * use the latch block as exit of the corresponding region,
337   //   * set the region as successor of the loop pre-header, and
338   //   * set the exit block as successor to the region.
339   SmallVector<Loop *> LoopWorkList;
340   LoopWorkList.push_back(TheLoop);
341   while (!LoopWorkList.empty()) {
342     Loop *L = LoopWorkList.pop_back_val();
343     BasicBlock *Header = L->getHeader();
344     BasicBlock *Exiting = L->getLoopLatch();
345     assert(Exiting == L->getExitingBlock() &&
346            "Latch must be the only exiting block");
347     VPRegionBlock *Region = Loop2Region[L];
348     VPBasicBlock *HeaderVPBB = getOrCreateVPBB(Header);
349     VPBasicBlock *ExitingVPBB = getOrCreateVPBB(Exiting);
350 
351     // Disconnect backedge and pre-header from header.
352     VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(L->getLoopPreheader());
353     VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPBB);
354     VPBlockUtils::disconnectBlocks(ExitingVPBB, HeaderVPBB);
355 
356     Region->setParent(PreheaderVPBB->getParent());
357     Region->setEntry(HeaderVPBB);
358     VPBlockUtils::connectBlocks(PreheaderVPBB, Region);
359 
360     // Disconnect exit block from exiting (=latch) block, set exiting block and
361     // connect region to exit block.
362     VPBasicBlock *ExitVPBB = getOrCreateVPBB(L->getExitBlock());
363     VPBlockUtils::disconnectBlocks(ExitingVPBB, ExitVPBB);
364     Region->setExiting(ExitingVPBB);
365     VPBlockUtils::connectBlocks(Region, ExitVPBB);
366 
367     // Queue sub-loops for processing.
368     LoopWorkList.append(L->begin(), L->end());
369   }
370   // 4. The whole CFG has been built at this point so all the input Values must
371   // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
372   // VPlan operands.
373   fixPhiNodes();
374 }
375 
376 void VPlanHCFGBuilder::buildPlainCFG() {
377   PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
378   PCFGBuilder.buildPlainCFG();
379 }
380 
381 // Public interface to build a H-CFG.
382 void VPlanHCFGBuilder::buildHierarchicalCFG() {
383   // Build Top Region enclosing the plain CFG.
384   buildPlainCFG();
385   LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);
386 
387   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
388   Verifier.verifyHierarchicalCFG(TopRegion);
389 
390   // Compute plain CFG dom tree for VPLInfo.
391   VPDomTree.recalculate(Plan);
392   LLVM_DEBUG(dbgs() << "Dominator Tree after building the plain CFG.\n";
393              VPDomTree.print(dbgs()));
394 }
395