xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Vectorize/VPlanVerifier.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
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 verifyVPBasicBlock(const VPBasicBlock *VPBB) {
137   // Verify that phi-like recipes are at the beginning of the block, with no
138   // other recipes in between.
139   auto RecipeI = VPBB->begin();
140   auto End = VPBB->end();
141   unsigned NumActiveLaneMaskPhiRecipes = 0;
142   while (RecipeI != End && RecipeI->isPhi()) {
143     if (isa<VPActiveLaneMaskPHIRecipe>(RecipeI))
144       NumActiveLaneMaskPhiRecipes++;
145     RecipeI++;
146   }
147 
148   if (NumActiveLaneMaskPhiRecipes > 1) {
149     errs() << "There should be no more than one VPActiveLaneMaskPHIRecipe";
150     return false;
151   }
152 
153   while (RecipeI != End) {
154     if (RecipeI->isPhi() && !isa<VPBlendRecipe>(&*RecipeI)) {
155       errs() << "Found phi-like recipe after non-phi recipe";
156 
157 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
158       errs() << ": ";
159       RecipeI->dump();
160       errs() << "after\n";
161       std::prev(RecipeI)->dump();
162 #endif
163       return false;
164     }
165     RecipeI++;
166   }
167 
168   return true;
169 }
170 
171 bool VPlanVerifier::verifyPlanIsValid(const VPlan &Plan) {
172   auto Iter = depth_first(
173       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
174   for (const VPBasicBlock *VPBB :
175        VPBlockUtils::blocksOnly<const VPBasicBlock>(Iter)) {
176     if (!verifyVPBasicBlock(VPBB))
177       return false;
178   }
179 
180   const VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
181   const VPBasicBlock *Entry = dyn_cast<VPBasicBlock>(TopRegion->getEntry());
182   if (!Entry) {
183     errs() << "VPlan entry block is not a VPBasicBlock\n";
184     return false;
185   }
186 
187   if (!isa<VPCanonicalIVPHIRecipe>(&*Entry->begin())) {
188     errs() << "VPlan vector loop header does not start with a "
189               "VPCanonicalIVPHIRecipe\n";
190     return false;
191   }
192 
193   const VPBasicBlock *Exiting = dyn_cast<VPBasicBlock>(TopRegion->getExiting());
194   if (!Exiting) {
195     errs() << "VPlan exiting block is not a VPBasicBlock\n";
196     return false;
197   }
198 
199   if (Exiting->empty()) {
200     errs() << "VPlan vector loop exiting block must end with BranchOnCount or "
201               "BranchOnCond VPInstruction but is empty\n";
202     return false;
203   }
204 
205   auto *LastInst = dyn_cast<VPInstruction>(std::prev(Exiting->end()));
206   if (!LastInst || (LastInst->getOpcode() != VPInstruction::BranchOnCount &&
207                     LastInst->getOpcode() != VPInstruction::BranchOnCond)) {
208     errs() << "VPlan vector loop exit must end with BranchOnCount or "
209               "BranchOnCond VPInstruction\n";
210     return false;
211   }
212 
213   for (const VPRegionBlock *Region :
214        VPBlockUtils::blocksOnly<const VPRegionBlock>(
215            depth_first(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
216                Plan.getEntry())))) {
217     if (Region->getEntry()->getNumPredecessors() != 0) {
218       errs() << "region entry block has predecessors\n";
219       return false;
220     }
221     if (Region->getExiting()->getNumSuccessors() != 0) {
222       errs() << "region exiting block has successors\n";
223       return false;
224     }
225   }
226 
227   for (auto &KV : Plan.getLiveOuts())
228     if (KV.second->getNumOperands() != 1) {
229       errs() << "live outs must have a single operand\n";
230       return false;
231     }
232 
233   return true;
234 }
235