1 //===-- VPlanVerifier.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 defines the class VPlanVerifier, which contains utility functions
11 /// to check the consistency and invariants of a VPlan.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "VPlanVerifier.h"
16 #include "VPlan.h"
17 #include "llvm/ADT/DepthFirstIterator.h"
18 #include "llvm/Support/CommandLine.h"
19 
20 #define DEBUG_TYPE "loop-vectorize"
21 
22 using namespace llvm;
23 
24 static cl::opt<bool> EnableHCFGVerifier("vplan-verify-hcfg", cl::init(false),
25                                         cl::Hidden,
26                                         cl::desc("Verify VPlan H-CFG."));
27 
28 #ifndef NDEBUG
29 /// Utility function that checks whether \p VPBlockVec has duplicate
30 /// VPBlockBases.
31 static bool hasDuplicates(const SmallVectorImpl<VPBlockBase *> &VPBlockVec) {
32   SmallDenseSet<const VPBlockBase *, 8> VPBlockSet;
33   for (const auto *Block : VPBlockVec) {
34     if (VPBlockSet.count(Block))
35       return true;
36     VPBlockSet.insert(Block);
37   }
38   return false;
39 }
40 #endif
41 
42 /// Helper function that verifies the CFG invariants of the VPBlockBases within
43 /// \p Region. Checks in this function are generic for VPBlockBases. They are
44 /// not specific for VPBasicBlocks or VPRegionBlocks.
45 static void verifyBlocksInRegion(const VPRegionBlock *Region) {
46   for (const VPBlockBase *VPB : make_range(
47            df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
48            df_iterator<const VPBlockBase *>::end(Region->getExiting()))) {
49     // Check block's parent.
50     assert(VPB->getParent() == Region && "VPBlockBase has wrong parent");
51 
52     auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
53     // Check block's condition bit.
54     if (VPB->getNumSuccessors() > 1 || (VPBB && VPBB->isExiting()))
55       assert(VPBB && VPBB->getTerminator() &&
56              "Block has multiple successors but doesn't "
57              "have a proper branch recipe!");
58     else
59       assert((!VPBB || !VPBB->getTerminator()) && "Unexpected branch recipe!");
60 
61     // Check block's successors.
62     const auto &Successors = VPB->getSuccessors();
63     // There must be only one instance of a successor in block's successor list.
64     // TODO: This won't work for switch statements.
65     assert(!hasDuplicates(Successors) &&
66            "Multiple instances of the same successor.");
67 
68     for (const VPBlockBase *Succ : Successors) {
69       // There must be a bi-directional link between block and successor.
70       const auto &SuccPreds = Succ->getPredecessors();
71       assert(llvm::is_contained(SuccPreds, VPB) && "Missing predecessor link.");
72       (void)SuccPreds;
73     }
74 
75     // Check block's predecessors.
76     const auto &Predecessors = VPB->getPredecessors();
77     // There must be only one instance of a predecessor in block's predecessor
78     // list.
79     // TODO: This won't work for switch statements.
80     assert(!hasDuplicates(Predecessors) &&
81            "Multiple instances of the same predecessor.");
82 
83     for (const VPBlockBase *Pred : Predecessors) {
84       // Block and predecessor must be inside the same region.
85       assert(Pred->getParent() == VPB->getParent() &&
86              "Predecessor is not in the same region.");
87 
88       // There must be a bi-directional link between block and predecessor.
89       const auto &PredSuccs = Pred->getSuccessors();
90       assert(llvm::is_contained(PredSuccs, VPB) && "Missing successor link.");
91       (void)PredSuccs;
92     }
93   }
94 }
95 
96 /// Verify the CFG invariants of VPRegionBlock \p Region and its nested
97 /// VPBlockBases. Do not recurse inside nested VPRegionBlocks.
98 static void verifyRegion(const VPRegionBlock *Region) {
99   const VPBlockBase *Entry = Region->getEntry();
100   const VPBlockBase *Exiting = Region->getExiting();
101 
102   // Entry and Exiting shouldn't have any predecessor/successor, respectively.
103   assert(!Entry->getNumPredecessors() && "Region entry has predecessors.");
104   assert(!Exiting->getNumSuccessors() &&
105          "Region exiting block has successors.");
106   (void)Entry;
107   (void)Exiting;
108 
109   verifyBlocksInRegion(Region);
110 }
111 
112 /// Verify the CFG invariants of VPRegionBlock \p Region and its nested
113 /// VPBlockBases. Recurse inside nested VPRegionBlocks.
114 static void verifyRegionRec(const VPRegionBlock *Region) {
115   verifyRegion(Region);
116 
117   // Recurse inside nested regions.
118   for (const VPBlockBase *VPB : make_range(
119            df_iterator<const VPBlockBase *>::begin(Region->getEntry()),
120            df_iterator<const VPBlockBase *>::end(Region->getExiting()))) {
121     if (const auto *SubRegion = dyn_cast<VPRegionBlock>(VPB))
122       verifyRegionRec(SubRegion);
123   }
124 }
125 
126 void VPlanVerifier::verifyHierarchicalCFG(
127     const VPRegionBlock *TopRegion) const {
128   if (!EnableHCFGVerifier)
129     return;
130 
131   LLVM_DEBUG(dbgs() << "Verifying VPlan H-CFG.\n");
132   assert(!TopRegion->getParent() && "VPlan Top Region should have no parent.");
133   verifyRegionRec(TopRegion);
134 }
135 
136 static bool
137 verifyVPBasicBlock(const VPBasicBlock *VPBB,
138                    DenseMap<const VPBlockBase *, unsigned> &BlockNumbering) {
139   // Verify that phi-like recipes are at the beginning of the block, with no
140   // other recipes in between.
141   auto RecipeI = VPBB->begin();
142   auto End = VPBB->end();
143   unsigned NumActiveLaneMaskPhiRecipes = 0;
144   while (RecipeI != End && RecipeI->isPhi()) {
145     if (isa<VPActiveLaneMaskPHIRecipe>(RecipeI))
146       NumActiveLaneMaskPhiRecipes++;
147     RecipeI++;
148   }
149 
150   if (NumActiveLaneMaskPhiRecipes > 1) {
151     errs() << "There should be no more than one VPActiveLaneMaskPHIRecipe";
152     return false;
153   }
154 
155   while (RecipeI != End) {
156     if (RecipeI->isPhi() && !isa<VPBlendRecipe>(&*RecipeI)) {
157       errs() << "Found phi-like recipe after non-phi recipe";
158 
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160       errs() << ": ";
161       RecipeI->dump();
162       errs() << "after\n";
163       std::prev(RecipeI)->dump();
164 #endif
165       return false;
166     }
167     RecipeI++;
168   }
169 
170   // Verify that defs in VPBB dominate all their uses. The current
171   // implementation is still incomplete.
172   DenseMap<const VPRecipeBase *, unsigned> RecipeNumbering;
173   unsigned Cnt = 0;
174   for (const VPRecipeBase &R : *VPBB)
175     RecipeNumbering[&R] = Cnt++;
176 
177   for (const VPRecipeBase &R : *VPBB) {
178     for (const VPValue *V : R.definedValues()) {
179       for (const VPUser *U : V->users()) {
180         auto *UI = dyn_cast<VPRecipeBase>(U);
181         if (!UI || isa<VPHeaderPHIRecipe>(UI))
182           continue;
183 
184         // If the user is in the same block, check it comes after R in the
185         // block.
186         if (UI->getParent() == VPBB) {
187           if (RecipeNumbering[UI] < RecipeNumbering[&R]) {
188             errs() << "Use before def!\n";
189             return false;
190           }
191           continue;
192         }
193 
194         // Skip blocks outside any region for now and blocks outside
195         // replicate-regions.
196         auto *ParentR = VPBB->getParent();
197         if (!ParentR || !ParentR->isReplicator())
198           continue;
199 
200         // For replicators, verify that VPPRedInstPHIRecipe defs are only used
201         // in subsequent blocks.
202         if (isa<VPPredInstPHIRecipe>(&R)) {
203           auto I = BlockNumbering.find(UI->getParent());
204           unsigned BlockNumber = I == BlockNumbering.end() ? std::numeric_limits<unsigned>::max() : I->second;
205           if (BlockNumber < BlockNumbering[ParentR]) {
206             errs() << "Use before def!\n";
207             return false;
208           }
209           continue;
210         }
211 
212         // All non-VPPredInstPHIRecipe recipes in the block must be used in
213         // the replicate region only.
214         if (UI->getParent()->getParent() != ParentR) {
215           errs() << "Use before def!\n";
216           return false;
217         }
218       }
219     }
220   }
221   return true;
222 }
223 
224 bool VPlanVerifier::verifyPlanIsValid(const VPlan &Plan) {
225   DenseMap<const VPBlockBase *, unsigned> BlockNumbering;
226   unsigned Cnt = 0;
227   auto Iter = depth_first(
228       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
229   for (const VPBlockBase *VPB : Iter) {
230     BlockNumbering[VPB] = Cnt++;
231     auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
232     if (!VPBB)
233       continue;
234     if (!verifyVPBasicBlock(VPBB, BlockNumbering))
235       return false;
236   }
237 
238   const VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
239   const VPBasicBlock *Entry = dyn_cast<VPBasicBlock>(TopRegion->getEntry());
240   if (!Entry) {
241     errs() << "VPlan entry block is not a VPBasicBlock\n";
242     return false;
243   }
244 
245   if (!isa<VPCanonicalIVPHIRecipe>(&*Entry->begin())) {
246     errs() << "VPlan vector loop header does not start with a "
247               "VPCanonicalIVPHIRecipe\n";
248     return false;
249   }
250 
251   const VPBasicBlock *Exiting = dyn_cast<VPBasicBlock>(TopRegion->getExiting());
252   if (!Exiting) {
253     errs() << "VPlan exiting block is not a VPBasicBlock\n";
254     return false;
255   }
256 
257   if (Exiting->empty()) {
258     errs() << "VPlan vector loop exiting block must end with BranchOnCount or "
259               "BranchOnCond VPInstruction but is empty\n";
260     return false;
261   }
262 
263   auto *LastInst = dyn_cast<VPInstruction>(std::prev(Exiting->end()));
264   if (!LastInst || (LastInst->getOpcode() != VPInstruction::BranchOnCount &&
265                     LastInst->getOpcode() != VPInstruction::BranchOnCond)) {
266     errs() << "VPlan vector loop exit must end with BranchOnCount or "
267               "BranchOnCond VPInstruction\n";
268     return false;
269   }
270 
271   for (const VPRegionBlock *Region :
272        VPBlockUtils::blocksOnly<const VPRegionBlock>(
273            depth_first(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
274                Plan.getEntry())))) {
275     if (Region->getEntry()->getNumPredecessors() != 0) {
276       errs() << "region entry block has predecessors\n";
277       return false;
278     }
279     if (Region->getExiting()->getNumSuccessors() != 0) {
280       errs() << "region exiting block has successors\n";
281       return false;
282     }
283   }
284 
285   for (auto &KV : Plan.getLiveOuts())
286     if (KV.second->getNumOperands() != 1) {
287       errs() << "live outs must have a single operand\n";
288       return false;
289     }
290 
291   return true;
292 }
293