xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===-- VPlanHCFGBuilder.cpp ----------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file implements the construction of a VPlan-based Hierarchical CFG
110b57cec5SDimitry Andric /// (H-CFG) for an incoming IR. This construction comprises the following
120b57cec5SDimitry Andric /// components and steps:
130b57cec5SDimitry Andric //
140b57cec5SDimitry Andric /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that
150b57cec5SDimitry Andric /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top
160b57cec5SDimitry Andric /// Region) is created to enclose and serve as parent of all the VPBasicBlocks
170b57cec5SDimitry Andric /// in the plain CFG.
180b57cec5SDimitry Andric /// NOTE: At this point, there is a direct correspondence between all the
190b57cec5SDimitry Andric /// VPBasicBlocks created for the initial plain CFG and the incoming
200b57cec5SDimitry Andric /// BasicBlocks. However, this might change in the future.
210b57cec5SDimitry Andric ///
220b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric #include "VPlanHCFGBuilder.h"
250b57cec5SDimitry Andric #include "LoopVectorizationPlanner.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric #define DEBUG_TYPE "loop-vectorize"
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric using namespace llvm;
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric namespace {
330b57cec5SDimitry Andric // Class that is used to build the plain CFG for the incoming IR.
340b57cec5SDimitry Andric class PlainCFGBuilder {
350b57cec5SDimitry Andric private:
360b57cec5SDimitry Andric   // The outermost loop of the input loop nest considered for vectorization.
370b57cec5SDimitry Andric   Loop *TheLoop;
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric   // Loop Info analysis.
400b57cec5SDimitry Andric   LoopInfo *LI;
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric   // Vectorization plan that we are working on.
430b57cec5SDimitry Andric   VPlan &Plan;
440b57cec5SDimitry Andric 
450b57cec5SDimitry Andric   // Builder of the VPlan instruction-level representation.
460b57cec5SDimitry Andric   VPBuilder VPIRBuilder;
470b57cec5SDimitry Andric 
480b57cec5SDimitry Andric   // NOTE: The following maps are intentionally destroyed after the plain CFG
490b57cec5SDimitry Andric   // construction because subsequent VPlan-to-VPlan transformation may
500b57cec5SDimitry Andric   // invalidate them.
510b57cec5SDimitry Andric   // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
520b57cec5SDimitry Andric   DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
530b57cec5SDimitry Andric   // Map incoming Value definitions to their newly-created VPValues.
540b57cec5SDimitry Andric   DenseMap<Value *, VPValue *> IRDef2VPValue;
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric   // Hold phi node's that need to be fixed once the plain CFG has been built.
570b57cec5SDimitry Andric   SmallVector<PHINode *, 8> PhisToFix;
580b57cec5SDimitry Andric 
5981ad6265SDimitry Andric   /// Maps loops in the original IR to their corresponding region.
6081ad6265SDimitry Andric   DenseMap<Loop *, VPRegionBlock *> Loop2Region;
6181ad6265SDimitry Andric 
620b57cec5SDimitry Andric   // Utility functions.
630b57cec5SDimitry Andric   void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
645f757f3fSDimitry Andric   void setRegionPredsFromBB(VPRegionBlock *VPBB, BasicBlock *BB);
650b57cec5SDimitry Andric   void fixPhiNodes();
660b57cec5SDimitry Andric   VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
670b57cec5SDimitry Andric #ifndef NDEBUG
680b57cec5SDimitry Andric   bool isExternalDef(Value *Val);
690b57cec5SDimitry Andric #endif
700b57cec5SDimitry Andric   VPValue *getOrCreateVPOperand(Value *IRVal);
710b57cec5SDimitry Andric   void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric public:
740b57cec5SDimitry Andric   PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
750b57cec5SDimitry Andric       : TheLoop(Lp), LI(LI), Plan(P) {}
760b57cec5SDimitry Andric 
7706c3fb27SDimitry Andric   /// Build plain CFG for TheLoop  and connects it to Plan's entry.
7806c3fb27SDimitry Andric   void buildPlainCFG();
790b57cec5SDimitry Andric };
800b57cec5SDimitry Andric } // anonymous namespace
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
830b57cec5SDimitry Andric // must have no predecessors.
840b57cec5SDimitry Andric void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
855f757f3fSDimitry Andric   auto GetLatchOfExit = [this](BasicBlock *BB) -> BasicBlock * {
865f757f3fSDimitry Andric     auto *SinglePred = BB->getSinglePredecessor();
875f757f3fSDimitry Andric     Loop *LoopForBB = LI->getLoopFor(BB);
885f757f3fSDimitry Andric     if (!SinglePred || LI->getLoopFor(SinglePred) == LoopForBB)
895f757f3fSDimitry Andric       return nullptr;
905f757f3fSDimitry Andric     // The input IR must be in loop-simplify form, ensuring a single predecessor
915f757f3fSDimitry Andric     // for exit blocks.
925f757f3fSDimitry Andric     assert(SinglePred == LI->getLoopFor(SinglePred)->getLoopLatch() &&
935f757f3fSDimitry Andric            "SinglePred must be the only loop latch");
945f757f3fSDimitry Andric     return SinglePred;
955f757f3fSDimitry Andric   };
965f757f3fSDimitry Andric   if (auto *LatchBB = GetLatchOfExit(BB)) {
975f757f3fSDimitry Andric     auto *PredRegion = getOrCreateVPBB(LatchBB)->getParent();
985f757f3fSDimitry Andric     assert(VPBB == cast<VPBasicBlock>(PredRegion->getSingleSuccessor()) &&
995f757f3fSDimitry Andric            "successor must already be set for PredRegion; it must have VPBB "
1005f757f3fSDimitry Andric            "as single successor");
1015f757f3fSDimitry Andric     VPBB->setPredecessors({PredRegion});
1025f757f3fSDimitry Andric     return;
1035f757f3fSDimitry Andric   }
1040b57cec5SDimitry Andric   // Collect VPBB predecessors.
1055f757f3fSDimitry Andric   SmallVector<VPBlockBase *, 2> VPBBPreds;
1060b57cec5SDimitry Andric   for (BasicBlock *Pred : predecessors(BB))
1070b57cec5SDimitry Andric     VPBBPreds.push_back(getOrCreateVPBB(Pred));
1080b57cec5SDimitry Andric   VPBB->setPredecessors(VPBBPreds);
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric 
1115f757f3fSDimitry Andric static bool isHeaderBB(BasicBlock *BB, Loop *L) {
1125f757f3fSDimitry Andric   return L && BB == L->getHeader();
1135f757f3fSDimitry Andric }
1145f757f3fSDimitry Andric 
1155f757f3fSDimitry Andric void PlainCFGBuilder::setRegionPredsFromBB(VPRegionBlock *Region,
1165f757f3fSDimitry Andric                                            BasicBlock *BB) {
1175f757f3fSDimitry Andric   // BB is a loop header block. Connect the region to the loop preheader.
1185f757f3fSDimitry Andric   Loop *LoopOfBB = LI->getLoopFor(BB);
1195f757f3fSDimitry Andric   Region->setPredecessors({getOrCreateVPBB(LoopOfBB->getLoopPredecessor())});
1205f757f3fSDimitry Andric }
1215f757f3fSDimitry Andric 
1220b57cec5SDimitry Andric // Add operands to VPInstructions representing phi nodes from the input IR.
1230b57cec5SDimitry Andric void PlainCFGBuilder::fixPhiNodes() {
1240b57cec5SDimitry Andric   for (auto *Phi : PhisToFix) {
1250b57cec5SDimitry Andric     assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
1260b57cec5SDimitry Andric     VPValue *VPVal = IRDef2VPValue[Phi];
127fe6060f1SDimitry Andric     assert(isa<VPWidenPHIRecipe>(VPVal) &&
128fe6060f1SDimitry Andric            "Expected WidenPHIRecipe for phi node.");
129fe6060f1SDimitry Andric     auto *VPPhi = cast<VPWidenPHIRecipe>(VPVal);
1300b57cec5SDimitry Andric     assert(VPPhi->getNumOperands() == 0 &&
1310b57cec5SDimitry Andric            "Expected VPInstruction with no operands.");
1320b57cec5SDimitry Andric 
1335f757f3fSDimitry Andric     Loop *L = LI->getLoopFor(Phi->getParent());
1345f757f3fSDimitry Andric     if (isHeaderBB(Phi->getParent(), L)) {
1355f757f3fSDimitry Andric       // For header phis, make sure the incoming value from the loop
1365f757f3fSDimitry Andric       // predecessor is the first operand of the recipe.
1375f757f3fSDimitry Andric       assert(Phi->getNumOperands() == 2);
1385f757f3fSDimitry Andric       BasicBlock *LoopPred = L->getLoopPredecessor();
1395f757f3fSDimitry Andric       VPPhi->addIncoming(
1405f757f3fSDimitry Andric           getOrCreateVPOperand(Phi->getIncomingValueForBlock(LoopPred)),
1415f757f3fSDimitry Andric           BB2VPBB[LoopPred]);
1425f757f3fSDimitry Andric       BasicBlock *LoopLatch = L->getLoopLatch();
1435f757f3fSDimitry Andric       VPPhi->addIncoming(
1445f757f3fSDimitry Andric           getOrCreateVPOperand(Phi->getIncomingValueForBlock(LoopLatch)),
1455f757f3fSDimitry Andric           BB2VPBB[LoopLatch]);
1465f757f3fSDimitry Andric       continue;
1475f757f3fSDimitry Andric     }
1485f757f3fSDimitry Andric 
149fe6060f1SDimitry Andric     for (unsigned I = 0; I != Phi->getNumOperands(); ++I)
150fe6060f1SDimitry Andric       VPPhi->addIncoming(getOrCreateVPOperand(Phi->getIncomingValue(I)),
151fe6060f1SDimitry Andric                          BB2VPBB[Phi->getIncomingBlock(I)]);
1520b57cec5SDimitry Andric   }
1530b57cec5SDimitry Andric }
1540b57cec5SDimitry Andric 
1555f757f3fSDimitry Andric static bool isHeaderVPBB(VPBasicBlock *VPBB) {
1565f757f3fSDimitry Andric   return VPBB->getParent() && VPBB->getParent()->getEntry() == VPBB;
1575f757f3fSDimitry Andric }
1585f757f3fSDimitry Andric 
1595f757f3fSDimitry Andric /// Return true of \p L loop is contained within \p OuterLoop.
1605f757f3fSDimitry Andric static bool doesContainLoop(const Loop *L, const Loop *OuterLoop) {
1615f757f3fSDimitry Andric   if (L->getLoopDepth() < OuterLoop->getLoopDepth())
1625f757f3fSDimitry Andric     return false;
1635f757f3fSDimitry Andric   const Loop *P = L;
1645f757f3fSDimitry Andric   while (P) {
1655f757f3fSDimitry Andric     if (P == OuterLoop)
1665f757f3fSDimitry Andric       return true;
1675f757f3fSDimitry Andric     P = P->getParentLoop();
1685f757f3fSDimitry Andric   }
1695f757f3fSDimitry Andric   return false;
1705f757f3fSDimitry Andric }
1715f757f3fSDimitry Andric 
17281ad6265SDimitry Andric // Create a new empty VPBasicBlock for an incoming BasicBlock in the region
17381ad6265SDimitry Andric // corresponding to the containing loop  or retrieve an existing one if it was
17481ad6265SDimitry Andric // already created. If no region exists yet for the loop containing \p BB, a new
17581ad6265SDimitry Andric // one is created.
1760b57cec5SDimitry Andric VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
1775f757f3fSDimitry Andric   if (auto *VPBB = BB2VPBB.lookup(BB)) {
1780b57cec5SDimitry Andric     // Retrieve existing VPBB.
1795f757f3fSDimitry Andric     return VPBB;
18081ad6265SDimitry Andric   }
18181ad6265SDimitry Andric 
1820b57cec5SDimitry Andric   // Create new VPBB.
1835f757f3fSDimitry Andric   StringRef Name = isHeaderBB(BB, TheLoop) ? "vector.body" : BB->getName();
1845f757f3fSDimitry Andric   LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << Name << "\n");
1855f757f3fSDimitry Andric   VPBasicBlock *VPBB = new VPBasicBlock(Name);
1860b57cec5SDimitry Andric   BB2VPBB[BB] = VPBB;
1875f757f3fSDimitry Andric 
1885f757f3fSDimitry Andric   // Get or create a region for the loop containing BB.
1895f757f3fSDimitry Andric   Loop *LoopOfBB = LI->getLoopFor(BB);
1905f757f3fSDimitry Andric   if (!LoopOfBB || !doesContainLoop(LoopOfBB, TheLoop))
1915f757f3fSDimitry Andric     return VPBB;
1925f757f3fSDimitry Andric 
1935f757f3fSDimitry Andric   auto *RegionOfVPBB = Loop2Region.lookup(LoopOfBB);
1945f757f3fSDimitry Andric   if (!isHeaderBB(BB, LoopOfBB)) {
1955f757f3fSDimitry Andric     assert(RegionOfVPBB &&
1965f757f3fSDimitry Andric            "Region should have been created by visiting header earlier");
1975f757f3fSDimitry Andric     VPBB->setParent(RegionOfVPBB);
1985f757f3fSDimitry Andric     return VPBB;
1995f757f3fSDimitry Andric   }
2005f757f3fSDimitry Andric 
2015f757f3fSDimitry Andric   assert(!RegionOfVPBB &&
2025f757f3fSDimitry Andric          "First visit of a header basic block expects to register its region.");
2035f757f3fSDimitry Andric   // Handle a header - take care of its Region.
2045f757f3fSDimitry Andric   if (LoopOfBB == TheLoop) {
2055f757f3fSDimitry Andric     RegionOfVPBB = Plan.getVectorLoopRegion();
2065f757f3fSDimitry Andric   } else {
2075f757f3fSDimitry Andric     RegionOfVPBB = new VPRegionBlock(Name.str(), false /*isReplicator*/);
2085f757f3fSDimitry Andric     RegionOfVPBB->setParent(Loop2Region[LoopOfBB->getParentLoop()]);
2095f757f3fSDimitry Andric   }
2105f757f3fSDimitry Andric   RegionOfVPBB->setEntry(VPBB);
2115f757f3fSDimitry Andric   Loop2Region[LoopOfBB] = RegionOfVPBB;
2120b57cec5SDimitry Andric   return VPBB;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric #ifndef NDEBUG
2160b57cec5SDimitry Andric // Return true if \p Val is considered an external definition. An external
2170b57cec5SDimitry Andric // definition is either:
2180b57cec5SDimitry Andric // 1. A Value that is not an Instruction. This will be refined in the future.
2190b57cec5SDimitry Andric // 2. An Instruction that is outside of the CFG snippet represented in VPlan,
2200b57cec5SDimitry Andric // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
2210b57cec5SDimitry Andric // outermost loop exits.
2220b57cec5SDimitry Andric bool PlainCFGBuilder::isExternalDef(Value *Val) {
2230b57cec5SDimitry Andric   // All the Values that are not Instructions are considered external
2240b57cec5SDimitry Andric   // definitions for now.
2250b57cec5SDimitry Andric   Instruction *Inst = dyn_cast<Instruction>(Val);
2260b57cec5SDimitry Andric   if (!Inst)
2270b57cec5SDimitry Andric     return true;
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric   BasicBlock *InstParent = Inst->getParent();
2300b57cec5SDimitry Andric   assert(InstParent && "Expected instruction parent.");
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric   // Check whether Instruction definition is in loop PH.
2330b57cec5SDimitry Andric   BasicBlock *PH = TheLoop->getLoopPreheader();
2340b57cec5SDimitry Andric   assert(PH && "Expected loop pre-header.");
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric   if (InstParent == PH)
2370b57cec5SDimitry Andric     // Instruction definition is in outermost loop PH.
2380b57cec5SDimitry Andric     return false;
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric   // Check whether Instruction definition is in the loop exit.
2410b57cec5SDimitry Andric   BasicBlock *Exit = TheLoop->getUniqueExitBlock();
2420b57cec5SDimitry Andric   assert(Exit && "Expected loop with single exit.");
2430b57cec5SDimitry Andric   if (InstParent == Exit) {
2440b57cec5SDimitry Andric     // Instruction definition is in outermost loop exit.
2450b57cec5SDimitry Andric     return false;
2460b57cec5SDimitry Andric   }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric   // Check whether Instruction definition is in loop body.
2490b57cec5SDimitry Andric   return !TheLoop->contains(Inst);
2500b57cec5SDimitry Andric }
2510b57cec5SDimitry Andric #endif
2520b57cec5SDimitry Andric 
2530b57cec5SDimitry Andric // Create a new VPValue or retrieve an existing one for the Instruction's
2540b57cec5SDimitry Andric // operand \p IRVal. This function must only be used to create/retrieve VPValues
2550b57cec5SDimitry Andric // for *Instruction's operands* and not to create regular VPInstruction's. For
2560b57cec5SDimitry Andric // the latter, please, look at 'createVPInstructionsForVPBB'.
2570b57cec5SDimitry Andric VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
2580b57cec5SDimitry Andric   auto VPValIt = IRDef2VPValue.find(IRVal);
2590b57cec5SDimitry Andric   if (VPValIt != IRDef2VPValue.end())
2600b57cec5SDimitry Andric     // Operand has an associated VPInstruction or VPValue that was previously
2610b57cec5SDimitry Andric     // created.
2620b57cec5SDimitry Andric     return VPValIt->second;
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   // Operand doesn't have a previously created VPInstruction/VPValue. This
2650b57cec5SDimitry Andric   // means that operand is:
2660b57cec5SDimitry Andric   //   A) a definition external to VPlan,
2670b57cec5SDimitry Andric   //   B) any other Value without specific representation in VPlan.
2680b57cec5SDimitry Andric   // For now, we use VPValue to represent A and B and classify both as external
2690b57cec5SDimitry Andric   // definitions. We may introduce specific VPValue subclasses for them in the
2700b57cec5SDimitry Andric   // future.
2710b57cec5SDimitry Andric   assert(isExternalDef(IRVal) && "Expected external definition as operand.");
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric   // A and B: Create VPValue and add it to the pool of external definitions and
2740b57cec5SDimitry Andric   // to the Value->VPValue map.
275*0fca6ea1SDimitry Andric   VPValue *NewVPVal = Plan.getOrAddLiveIn(IRVal);
2760b57cec5SDimitry Andric   IRDef2VPValue[IRVal] = NewVPVal;
2770b57cec5SDimitry Andric   return NewVPVal;
2780b57cec5SDimitry Andric }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric // Create new VPInstructions in a VPBasicBlock, given its BasicBlock
2810b57cec5SDimitry Andric // counterpart. This function must be invoked in RPO so that the operands of a
2820b57cec5SDimitry Andric // VPInstruction in \p BB have been visited before (except for Phi nodes).
2830b57cec5SDimitry Andric void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
2840b57cec5SDimitry Andric                                                   BasicBlock *BB) {
2850b57cec5SDimitry Andric   VPIRBuilder.setInsertPoint(VPBB);
2867a6dacacSDimitry Andric   for (Instruction &InstRef : BB->instructionsWithoutDebug(false)) {
2870b57cec5SDimitry Andric     Instruction *Inst = &InstRef;
2880b57cec5SDimitry Andric 
2890b57cec5SDimitry Andric     // There shouldn't be any VPValue for Inst at this point. Otherwise, we
2900b57cec5SDimitry Andric     // visited Inst when we shouldn't, breaking the RPO traversal order.
2910b57cec5SDimitry Andric     assert(!IRDef2VPValue.count(Inst) &&
2920b57cec5SDimitry Andric            "Instruction shouldn't have been visited.");
2930b57cec5SDimitry Andric 
2940b57cec5SDimitry Andric     if (auto *Br = dyn_cast<BranchInst>(Inst)) {
29581ad6265SDimitry Andric       // Conditional branch instruction are represented using BranchOnCond
29681ad6265SDimitry Andric       // recipes.
29781ad6265SDimitry Andric       if (Br->isConditional()) {
29881ad6265SDimitry Andric         VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
299*0fca6ea1SDimitry Andric         VPIRBuilder.createNaryOp(VPInstruction::BranchOnCond, {Cond}, Inst);
30081ad6265SDimitry Andric       }
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric       // Skip the rest of the Instruction processing for Branch instructions.
3030b57cec5SDimitry Andric       continue;
3040b57cec5SDimitry Andric     }
3050b57cec5SDimitry Andric 
306fe6060f1SDimitry Andric     VPValue *NewVPV;
3070b57cec5SDimitry Andric     if (auto *Phi = dyn_cast<PHINode>(Inst)) {
3080b57cec5SDimitry Andric       // Phi node's operands may have not been visited at this point. We create
3090b57cec5SDimitry Andric       // an empty VPInstruction that we will fix once the whole plain CFG has
3100b57cec5SDimitry Andric       // been built.
311fe6060f1SDimitry Andric       NewVPV = new VPWidenPHIRecipe(Phi);
312fe6060f1SDimitry Andric       VPBB->appendRecipe(cast<VPWidenPHIRecipe>(NewVPV));
3130b57cec5SDimitry Andric       PhisToFix.push_back(Phi);
3140b57cec5SDimitry Andric     } else {
3150b57cec5SDimitry Andric       // Translate LLVM-IR operands into VPValue operands and set them in the
3160b57cec5SDimitry Andric       // new VPInstruction.
3170b57cec5SDimitry Andric       SmallVector<VPValue *, 4> VPOperands;
3180b57cec5SDimitry Andric       for (Value *Op : Inst->operands())
3190b57cec5SDimitry Andric         VPOperands.push_back(getOrCreateVPOperand(Op));
3200b57cec5SDimitry Andric 
321bdd1243dSDimitry Andric       // Build VPInstruction for any arbitrary Instruction without specific
3220b57cec5SDimitry Andric       // representation in VPlan.
323fe6060f1SDimitry Andric       NewVPV = cast<VPInstruction>(
3240b57cec5SDimitry Andric           VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
3250b57cec5SDimitry Andric     }
3260b57cec5SDimitry Andric 
327fe6060f1SDimitry Andric     IRDef2VPValue[Inst] = NewVPV;
3280b57cec5SDimitry Andric   }
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric // Main interface to build the plain CFG.
33206c3fb27SDimitry Andric void PlainCFGBuilder::buildPlainCFG() {
3335f757f3fSDimitry Andric   // 0. Reuse the top-level region, vector-preheader and exit VPBBs from the
3345f757f3fSDimitry Andric   // skeleton. These were created directly rather than via getOrCreateVPBB(),
3355f757f3fSDimitry Andric   // revisit them now to update BB2VPBB. Note that header/entry and
3365f757f3fSDimitry Andric   // latch/exiting VPBB's of top-level region have yet to be created.
3375f757f3fSDimitry Andric   VPRegionBlock *TheRegion = Plan.getVectorLoopRegion();
3385f757f3fSDimitry Andric   BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
3395f757f3fSDimitry Andric   assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
3405f757f3fSDimitry Andric          "Unexpected loop preheader");
3415f757f3fSDimitry Andric   auto *VectorPreheaderVPBB =
3425f757f3fSDimitry Andric       cast<VPBasicBlock>(TheRegion->getSinglePredecessor());
3435f757f3fSDimitry Andric   // ThePreheaderBB conceptually corresponds to both Plan.getPreheader() (which
3445f757f3fSDimitry Andric   // wraps the original preheader BB) and Plan.getEntry() (which represents the
3455f757f3fSDimitry Andric   // new vector preheader); here we're interested in setting BB2VPBB to the
3465f757f3fSDimitry Andric   // latter.
3475f757f3fSDimitry Andric   BB2VPBB[ThePreheaderBB] = VectorPreheaderVPBB;
3485f757f3fSDimitry Andric   BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
349*0fca6ea1SDimitry Andric   Loop2Region[LI->getLoopFor(TheLoop->getHeader())] = TheRegion;
3505f757f3fSDimitry Andric   assert(LoopExitBB && "Loops with multiple exits are not supported.");
3515f757f3fSDimitry Andric   BB2VPBB[LoopExitBB] = cast<VPBasicBlock>(TheRegion->getSingleSuccessor());
3525f757f3fSDimitry Andric 
353*0fca6ea1SDimitry Andric   // The existing vector region's entry and exiting VPBBs correspond to the loop
354*0fca6ea1SDimitry Andric   // header and latch.
355*0fca6ea1SDimitry Andric   VPBasicBlock *VectorHeaderVPBB = TheRegion->getEntryBasicBlock();
356*0fca6ea1SDimitry Andric   VPBasicBlock *VectorLatchVPBB = TheRegion->getExitingBasicBlock();
357*0fca6ea1SDimitry Andric   BB2VPBB[TheLoop->getHeader()] = VectorHeaderVPBB;
358*0fca6ea1SDimitry Andric   VectorHeaderVPBB->clearSuccessors();
359*0fca6ea1SDimitry Andric   VectorLatchVPBB->clearPredecessors();
360*0fca6ea1SDimitry Andric   if (TheLoop->getHeader() != TheLoop->getLoopLatch()) {
361*0fca6ea1SDimitry Andric     BB2VPBB[TheLoop->getLoopLatch()] = VectorLatchVPBB;
362*0fca6ea1SDimitry Andric   } else {
363*0fca6ea1SDimitry Andric     TheRegion->setExiting(VectorHeaderVPBB);
364*0fca6ea1SDimitry Andric     delete VectorLatchVPBB;
365*0fca6ea1SDimitry Andric   }
366*0fca6ea1SDimitry Andric 
36781ad6265SDimitry Andric   // 1. Scan the body of the loop in a topological order to visit each basic
3680b57cec5SDimitry Andric   // block after having visited its predecessor basic blocks. Create a VPBB for
3690b57cec5SDimitry Andric   // each BB and link it to its successor and predecessor VPBBs. Note that
3700b57cec5SDimitry Andric   // predecessors must be set in the same order as they are in the incomming IR.
3710b57cec5SDimitry Andric   // Otherwise, there might be problems with existing phi nodes and algorithm
3720b57cec5SDimitry Andric   // based on predecessors traversal.
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   // Loop PH needs to be explicitly visited since it's not taken into account by
3750b57cec5SDimitry Andric   // LoopBlocksDFS.
37681ad6265SDimitry Andric   for (auto &I : *ThePreheaderBB) {
377fe6060f1SDimitry Andric     if (I.getType()->isVoidTy())
378fe6060f1SDimitry Andric       continue;
379*0fca6ea1SDimitry Andric     IRDef2VPValue[&I] = Plan.getOrAddLiveIn(&I);
380fe6060f1SDimitry Andric   }
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric   LoopBlocksRPO RPO(TheLoop);
3830b57cec5SDimitry Andric   RPO.perform(LI);
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric   for (BasicBlock *BB : RPO) {
3860b57cec5SDimitry Andric     // Create or retrieve the VPBasicBlock for this BB and create its
3870b57cec5SDimitry Andric     // VPInstructions.
3880b57cec5SDimitry Andric     VPBasicBlock *VPBB = getOrCreateVPBB(BB);
3895f757f3fSDimitry Andric     VPRegionBlock *Region = VPBB->getParent();
3900b57cec5SDimitry Andric     createVPInstructionsForVPBB(VPBB, BB);
3915f757f3fSDimitry Andric     Loop *LoopForBB = LI->getLoopFor(BB);
3925f757f3fSDimitry Andric     // Set VPBB predecessors in the same order as they are in the incoming BB.
3935f757f3fSDimitry Andric     if (!isHeaderBB(BB, LoopForBB)) {
3945f757f3fSDimitry Andric       setVPBBPredsFromBB(VPBB, BB);
3955f757f3fSDimitry Andric     } else {
3965f757f3fSDimitry Andric       // BB is a loop header, set the predecessor for the region, except for the
3975f757f3fSDimitry Andric       // top region, whose predecessor was set when creating VPlan's skeleton.
3985f757f3fSDimitry Andric       assert(isHeaderVPBB(VPBB) && "isHeaderBB and isHeaderVPBB disagree");
3995f757f3fSDimitry Andric       if (TheRegion != Region)
4005f757f3fSDimitry Andric         setRegionPredsFromBB(Region, BB);
4015f757f3fSDimitry Andric     }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric     // Set VPBB successors. We create empty VPBBs for successors if they don't
4040b57cec5SDimitry Andric     // exist already. Recipes will be created when the successor is visited
4050b57cec5SDimitry Andric     // during the RPO traversal.
4065f757f3fSDimitry Andric     auto *BI = cast<BranchInst>(BB->getTerminator());
4075f757f3fSDimitry Andric     unsigned NumSuccs = succ_size(BB);
4080b57cec5SDimitry Andric     if (NumSuccs == 1) {
4095f757f3fSDimitry Andric       auto *Successor = getOrCreateVPBB(BB->getSingleSuccessor());
4105f757f3fSDimitry Andric       VPBB->setOneSuccessor(isHeaderVPBB(Successor)
4115f757f3fSDimitry Andric                                 ? Successor->getParent()
4125f757f3fSDimitry Andric                                 : static_cast<VPBlockBase *>(Successor));
4135f757f3fSDimitry Andric       continue;
4145f757f3fSDimitry Andric     }
4155f757f3fSDimitry Andric     assert(BI->isConditional() && NumSuccs == 2 && BI->isConditional() &&
4165f757f3fSDimitry Andric            "block must have conditional branch with 2 successors");
4170b57cec5SDimitry Andric     // Look up the branch condition to get the corresponding VPValue
4180b57cec5SDimitry Andric     // representing the condition bit in VPlan (which may be in another VPBB).
4195f757f3fSDimitry Andric     assert(IRDef2VPValue.contains(BI->getCondition()) &&
4200b57cec5SDimitry Andric            "Missing condition bit in IRDef2VPValue!");
4215f757f3fSDimitry Andric     VPBasicBlock *Successor0 = getOrCreateVPBB(BI->getSuccessor(0));
4225f757f3fSDimitry Andric     VPBasicBlock *Successor1 = getOrCreateVPBB(BI->getSuccessor(1));
4235f757f3fSDimitry Andric     if (!LoopForBB || BB != LoopForBB->getLoopLatch()) {
4245f757f3fSDimitry Andric       VPBB->setTwoSuccessors(Successor0, Successor1);
4255f757f3fSDimitry Andric       continue;
4265f757f3fSDimitry Andric     }
4275f757f3fSDimitry Andric     // For a latch we need to set the successor of the region rather than that
4285f757f3fSDimitry Andric     // of VPBB and it should be set to the exit, i.e., non-header successor,
4295f757f3fSDimitry Andric     // except for the top region, whose successor was set when creating VPlan's
4305f757f3fSDimitry Andric     // skeleton.
431*0fca6ea1SDimitry Andric     if (TheRegion != Region) {
4325f757f3fSDimitry Andric       Region->setOneSuccessor(isHeaderVPBB(Successor0) ? Successor1
4335f757f3fSDimitry Andric                                                        : Successor0);
4345f757f3fSDimitry Andric       Region->setExiting(VPBB);
4350b57cec5SDimitry Andric     }
436*0fca6ea1SDimitry Andric   }
4370b57cec5SDimitry Andric 
4385f757f3fSDimitry Andric   // 2. The whole CFG has been built at this point so all the input Values must
4390b57cec5SDimitry Andric   // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
4400b57cec5SDimitry Andric   // VPlan operands.
4410b57cec5SDimitry Andric   fixPhiNodes();
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
44406c3fb27SDimitry Andric void VPlanHCFGBuilder::buildPlainCFG() {
4450b57cec5SDimitry Andric   PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
44606c3fb27SDimitry Andric   PCFGBuilder.buildPlainCFG();
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric // Public interface to build a H-CFG.
4500b57cec5SDimitry Andric void VPlanHCFGBuilder::buildHierarchicalCFG() {
45106c3fb27SDimitry Andric   // Build Top Region enclosing the plain CFG.
45206c3fb27SDimitry Andric   buildPlainCFG();
4530b57cec5SDimitry Andric   LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);
4540b57cec5SDimitry Andric 
4550b57cec5SDimitry Andric   // Compute plain CFG dom tree for VPLInfo.
456bdd1243dSDimitry Andric   VPDomTree.recalculate(Plan);
4570b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Dominator Tree after building the plain CFG.\n";
4580b57cec5SDimitry Andric              VPDomTree.print(dbgs()));
4590b57cec5SDimitry Andric }
460