LLVM 22.0.0git
VPlanVerifier.cpp
Go to the documentation of this file.
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 "VPlanCFG.h"
18#include "VPlanDominatorTree.h"
19#include "VPlanHelpers.h"
20#include "VPlanPatternMatch.h"
22#include "llvm/ADT/TypeSwitch.h"
23
24#define DEBUG_TYPE "loop-vectorize"
25
26using namespace llvm;
27
28namespace {
29class VPlanVerifier {
30 const VPDominatorTree &VPDT;
31 VPTypeAnalysis &TypeInfo;
32 bool VerifyLate;
33
35
36 // Verify that phi-like recipes are at the beginning of \p VPBB, with no
37 // other recipes in between. Also check that only header blocks contain
38 // VPHeaderPHIRecipes.
39 bool verifyPhiRecipes(const VPBasicBlock *VPBB);
40
41 /// Verify that \p EVL is used correctly. The user must be either in
42 /// EVL-based recipes as a last operand or VPInstruction::Add which is
43 /// incoming value into EVL's recipe.
44 bool verifyEVLRecipe(const VPInstruction &EVL) const;
45
46 bool verifyVPBasicBlock(const VPBasicBlock *VPBB);
47
48 bool verifyBlock(const VPBlockBase *VPB);
49
50 /// Helper function that verifies the CFG invariants of the VPBlockBases
51 /// within
52 /// \p Region. Checks in this function are generic for VPBlockBases. They are
53 /// not specific for VPBasicBlocks or VPRegionBlocks.
54 bool verifyBlocksInRegion(const VPRegionBlock *Region);
55
56 /// Verify the CFG invariants of VPRegionBlock \p Region and its nested
57 /// VPBlockBases. Do not recurse inside nested VPRegionBlocks.
58 bool verifyRegion(const VPRegionBlock *Region);
59
60 /// Verify the CFG invariants of VPRegionBlock \p Region and its nested
61 /// VPBlockBases. Recurse inside nested VPRegionBlocks.
62 bool verifyRegionRec(const VPRegionBlock *Region);
63
64public:
65 VPlanVerifier(VPDominatorTree &VPDT, VPTypeAnalysis &TypeInfo,
66 bool VerifyLate)
67 : VPDT(VPDT), TypeInfo(TypeInfo), VerifyLate(VerifyLate) {}
68
69 bool verify(const VPlan &Plan);
70};
71} // namespace
72
73bool VPlanVerifier::verifyPhiRecipes(const VPBasicBlock *VPBB) {
74 auto RecipeI = VPBB->begin();
75 auto End = VPBB->end();
76 unsigned NumActiveLaneMaskPhiRecipes = 0;
77 bool IsHeaderVPBB = VPBlockUtils::isHeader(VPBB, VPDT);
78 while (RecipeI != End && RecipeI->isPhi()) {
80 NumActiveLaneMaskPhiRecipes++;
81
82 if (IsHeaderVPBB &&
84 errs() << "Found non-header PHI recipe in header VPBB";
85#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
86 errs() << ": ";
87 RecipeI->dump();
88#endif
89 return false;
90 }
91
92 if (!IsHeaderVPBB && isa<VPHeaderPHIRecipe>(*RecipeI)) {
93 errs() << "Found header PHI recipe in non-header VPBB";
94#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
95 errs() << ": ";
96 RecipeI->dump();
97#endif
98 return false;
99 }
100
101 // Check if the recipe operands match the number of predecessors.
102 // TODO Extend to other phi-like recipes.
103 if (auto *PhiIRI = dyn_cast<VPIRPhi>(&*RecipeI)) {
104 if (PhiIRI->getNumOperands() != VPBB->getNumPredecessors()) {
105 errs() << "Phi-like recipe with different number of operands and "
106 "predecessors.\n";
107 // TODO: Print broken recipe. At the moment printing an ill-formed
108 // phi-like recipe may crash.
109 return false;
110 }
111 }
112
113 RecipeI++;
114 }
115
116 if (!VerifyLate && NumActiveLaneMaskPhiRecipes > 1) {
117 errs() << "There should be no more than one VPActiveLaneMaskPHIRecipe";
118 return false;
119 }
120
121 while (RecipeI != End) {
122 if (RecipeI->isPhi() && !isa<VPBlendRecipe>(&*RecipeI)) {
123 errs() << "Found phi-like recipe after non-phi recipe";
124
125#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
126 errs() << ": ";
127 RecipeI->dump();
128 errs() << "after\n";
129 std::prev(RecipeI)->dump();
130#endif
131 return false;
132 }
133 RecipeI++;
134 }
135 return true;
136}
137
138bool VPlanVerifier::verifyEVLRecipe(const VPInstruction &EVL) const {
140 errs() << "verifyEVLRecipe should only be called on "
141 "VPInstruction::ExplicitVectorLength\n";
142 return false;
143 }
144 auto VerifyEVLUse = [&](const VPRecipeBase &R,
145 const unsigned ExpectedIdx) -> bool {
147 unsigned UseCount = count(Ops, &EVL);
148 if (UseCount != 1 || Ops[ExpectedIdx] != &EVL) {
149 errs() << "EVL is used as non-last operand in EVL-based recipe\n";
150 return false;
151 }
152 return true;
153 };
154 return all_of(EVL.users(), [this, &VerifyEVLUse](VPUser *U) {
155 return TypeSwitch<const VPUser *, bool>(U)
156 .Case<VPWidenIntrinsicRecipe>([&](const VPWidenIntrinsicRecipe *S) {
157 return VerifyEVLUse(*S, S->getNumOperands() - 1);
158 })
159 .Case<VPWidenStoreEVLRecipe, VPReductionEVLRecipe,
160 VPWidenIntOrFpInductionRecipe, VPWidenPointerInductionRecipe>(
161 [&](const VPRecipeBase *S) { return VerifyEVLUse(*S, 2); })
162 .Case<VPScalarIVStepsRecipe>([&](auto *R) {
163 if (R->getNumOperands() != 3) {
164 errs() << "Unrolling with EVL tail folding not yet supported\n";
165 return false;
166 }
167 return VerifyEVLUse(*R, 2);
168 })
169 .Case<VPWidenLoadEVLRecipe, VPVectorEndPointerRecipe,
170 VPInterleaveEVLRecipe>(
171 [&](const VPRecipeBase *R) { return VerifyEVLUse(*R, 1); })
172 .Case<VPInstructionWithType>(
173 [&](const VPInstructionWithType *S) { return VerifyEVLUse(*S, 0); })
174 .Case<VPInstruction>([&](const VPInstruction *I) {
175 if (I->getOpcode() == Instruction::PHI ||
176 I->getOpcode() == Instruction::ICmp ||
177 I->getOpcode() == Instruction::Sub)
178 return VerifyEVLUse(*I, 1);
179 switch (I->getOpcode()) {
180 case Instruction::Add:
181 break;
182 case Instruction::UIToFP:
183 case Instruction::Trunc:
184 case Instruction::ZExt:
185 case Instruction::Mul:
186 case Instruction::FMul:
188 // Opcodes above can only use EVL after wide inductions have been
189 // expanded.
190 if (!VerifyLate) {
191 errs() << "EVL used by unexpected VPInstruction\n";
192 return false;
193 }
194 break;
195 default:
196 errs() << "EVL used by unexpected VPInstruction\n";
197 return false;
198 }
199 // EVLIVIncrement is only used by EVLIV & BranchOnCount.
200 // Having more than two users is unexpected.
201 if ((I->getNumUsers() != 1) &&
202 (I->getNumUsers() != 2 || none_of(I->users(), [&I](VPUser *U) {
203 using namespace llvm::VPlanPatternMatch;
204 return match(U, m_BranchOnCount(m_Specific(I), m_VPValue()));
205 }))) {
206 errs() << "EVL is used in VPInstruction with multiple users\n";
207 return false;
208 }
209 if (!VerifyLate && !isa<VPEVLBasedIVPHIRecipe>(*I->users().begin())) {
210 errs() << "Result of VPInstruction::Add with EVL operand is "
211 "not used by VPEVLBasedIVPHIRecipe\n";
212 return false;
213 }
214 return true;
215 })
216 .Default([&](const VPUser *U) {
217 errs() << "EVL has unexpected user\n";
218 return false;
219 });
220 });
221}
222
223bool VPlanVerifier::verifyVPBasicBlock(const VPBasicBlock *VPBB) {
224 if (!verifyPhiRecipes(VPBB))
225 return false;
226
227 // Verify that defs in VPBB dominate all their uses.
228 DenseMap<const VPRecipeBase *, unsigned> RecipeNumbering;
229 unsigned Cnt = 0;
230 for (const VPRecipeBase &R : *VPBB)
231 RecipeNumbering[&R] = Cnt++;
232
233 for (const VPRecipeBase &R : *VPBB) {
234 if (isa<VPIRInstruction>(&R) && !isa<VPIRBasicBlock>(VPBB)) {
235 errs() << "VPIRInstructions ";
236#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
237 R.dump();
238 errs() << " ";
239#endif
240 errs() << "not in a VPIRBasicBlock!\n";
241 return false;
242 }
243 for (const VPValue *V : R.definedValues()) {
244 // Verify that we can infer a scalar type for each defined value. With
245 // assertions enabled, inferScalarType will perform some consistency
246 // checks during type inference.
247 if (!TypeInfo.inferScalarType(V)) {
248 errs() << "Failed to infer scalar type!\n";
249 return false;
250 }
251
252 for (const VPUser *U : V->users()) {
253 auto *UI = cast<VPRecipeBase>(U);
254 if (auto *Phi = dyn_cast<VPPhiAccessors>(UI)) {
255 for (const auto &[IncomingVPV, IncomingVPBB] :
256 Phi->incoming_values_and_blocks()) {
257 if (IncomingVPV != V)
258 continue;
259
260 if (VPDT.dominates(VPBB, IncomingVPBB))
261 continue;
262
263 errs() << "Incoming def does not dominate incoming block!\n";
264#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
265 VPSlotTracker Tracker(VPBB->getPlan());
266 IncomingVPV->getDefiningRecipe()->print(errs(), " ", Tracker);
267 errs() << "\n does not dominate " << IncomingVPBB->getName()
268 << " for\n";
269 UI->print(errs(), " ", Tracker);
270#endif
271 return false;
272 }
273 continue;
274 }
275 // TODO: Also verify VPPredInstPHIRecipe.
277 continue;
278
279 // If the user is in the same block, check it comes after R in the
280 // block.
281 if (UI->getParent() == VPBB) {
282 if (RecipeNumbering[UI] >= RecipeNumbering[&R])
283 continue;
284 } else {
285 if (VPDT.dominates(VPBB, UI->getParent()))
286 continue;
287 }
288
289 errs() << "Use before def!\n";
290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
291 VPSlotTracker Tracker(VPBB->getPlan());
292 UI->print(errs(), " ", Tracker);
293 errs() << "\n before\n";
294 R.print(errs(), " ", Tracker);
295 errs() << "\n";
296#endif
297 return false;
298 }
299 }
300 if (const auto *EVL = dyn_cast<VPInstruction>(&R)) {
302 !verifyEVLRecipe(*EVL)) {
303 errs() << "EVL VPValue is not used correctly\n";
304 return false;
305 }
306 }
307 }
308
309 auto *IRBB = dyn_cast<VPIRBasicBlock>(VPBB);
310 if (!IRBB)
311 return true;
312
313 if (!WrappedIRBBs.insert(IRBB->getIRBasicBlock()).second) {
314 errs() << "Same IR basic block used by multiple wrapper blocks!\n";
315 return false;
316 }
317
318 return true;
319}
320
321/// Utility function that checks whether \p VPBlockVec has duplicate
322/// VPBlockBases.
323static bool hasDuplicates(const SmallVectorImpl<VPBlockBase *> &VPBlockVec) {
325 for (const auto *Block : VPBlockVec) {
326 if (!VPBlockSet.insert(Block).second)
327 return true;
328 }
329 return false;
330}
331
332bool VPlanVerifier::verifyBlock(const VPBlockBase *VPB) {
333 auto *VPBB = dyn_cast<VPBasicBlock>(VPB);
334 // Check block's condition bit.
335 if (!isa<VPIRBasicBlock>(VPB)) {
336 if (VPB->getNumSuccessors() > 1 ||
337 (VPBB && VPBB->getParent() && VPBB->isExiting() &&
338 !VPBB->getParent()->isReplicator())) {
339 if (!VPBB || !VPBB->getTerminator()) {
340 errs() << "Block has multiple successors but doesn't "
341 "have a proper branch recipe!\n";
342 return false;
343 }
344 } else {
345 if (VPBB && VPBB->getTerminator()) {
346 errs() << "Unexpected branch recipe!\n";
347 return false;
348 }
349 }
350 }
351
352 // Check block's successors.
353 const auto &Successors = VPB->getSuccessors();
354 // There must be only one instance of a successor in block's successor list.
355 // TODO: This won't work for switch statements.
356 if (hasDuplicates(Successors)) {
357 errs() << "Multiple instances of the same successor.\n";
358 return false;
359 }
360
361 for (const VPBlockBase *Succ : Successors) {
362 // There must be a bi-directional link between block and successor.
363 const auto &SuccPreds = Succ->getPredecessors();
364 if (!is_contained(SuccPreds, VPB)) {
365 errs() << "Missing predecessor link.\n";
366 return false;
367 }
368 }
369
370 // Check block's predecessors.
371 const auto &Predecessors = VPB->getPredecessors();
372 // There must be only one instance of a predecessor in block's predecessor
373 // list.
374 // TODO: This won't work for switch statements.
375 if (hasDuplicates(Predecessors)) {
376 errs() << "Multiple instances of the same predecessor.\n";
377 return false;
378 }
379
380 for (const VPBlockBase *Pred : Predecessors) {
381 // Block and predecessor must be inside the same region.
382 if (Pred->getParent() != VPB->getParent()) {
383 errs() << "Predecessor is not in the same region.\n";
384 return false;
385 }
386
387 // There must be a bi-directional link between block and predecessor.
388 const auto &PredSuccs = Pred->getSuccessors();
389 if (!is_contained(PredSuccs, VPB)) {
390 errs() << "Missing successor link.\n";
391 return false;
392 }
393 }
394 return !VPBB || verifyVPBasicBlock(VPBB);
395}
396
397bool VPlanVerifier::verifyBlocksInRegion(const VPRegionBlock *Region) {
398 for (const VPBlockBase *VPB : vp_depth_first_shallow(Region->getEntry())) {
399 // Check block's parent.
400 if (VPB->getParent() != Region) {
401 errs() << "VPBlockBase has wrong parent\n";
402 return false;
403 }
404
405 if (!verifyBlock(VPB))
406 return false;
407 }
408 return true;
409}
410
411bool VPlanVerifier::verifyRegion(const VPRegionBlock *Region) {
412 const VPBlockBase *Entry = Region->getEntry();
413 const VPBlockBase *Exiting = Region->getExiting();
414
415 // Entry and Exiting shouldn't have any predecessor/successor, respectively.
416 if (Entry->hasPredecessors()) {
417 errs() << "region entry block has predecessors\n";
418 return false;
419 }
420 if (Exiting->getNumSuccessors() != 0) {
421 errs() << "region exiting block has successors\n";
422 return false;
423 }
424
425 return verifyBlocksInRegion(Region);
426}
427
428bool VPlanVerifier::verifyRegionRec(const VPRegionBlock *Region) {
429 // Recurse inside nested regions and check all blocks inside the region.
430 return verifyRegion(Region) &&
432 [this](const VPBlockBase *VPB) {
433 const auto *SubRegion = dyn_cast<VPRegionBlock>(VPB);
434 return !SubRegion || verifyRegionRec(SubRegion);
435 });
436}
437
438bool VPlanVerifier::verify(const VPlan &Plan) {
440 [this](const VPBlockBase *VPB) { return !verifyBlock(VPB); }))
441 return false;
442
443 const VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
444 // TODO: Verify all blocks using vp_depth_first_deep iterators.
445 if (!TopRegion)
446 return true;
447
448 if (!verifyRegionRec(TopRegion))
449 return false;
450
451 if (TopRegion->getParent()) {
452 errs() << "VPlan Top Region should have no parent.\n";
453 return false;
454 }
455
456 const VPBasicBlock *Entry = dyn_cast<VPBasicBlock>(TopRegion->getEntry());
457 if (!Entry) {
458 errs() << "VPlan entry block is not a VPBasicBlock\n";
459 return false;
460 }
461
462 if (!isa<VPCanonicalIVPHIRecipe>(&*Entry->begin())) {
463 errs() << "VPlan vector loop header does not start with a "
464 "VPCanonicalIVPHIRecipe\n";
465 return false;
466 }
467
468 const VPBasicBlock *Exiting = dyn_cast<VPBasicBlock>(TopRegion->getExiting());
469 if (!Exiting) {
470 errs() << "VPlan exiting block is not a VPBasicBlock\n";
471 return false;
472 }
473
474 if (Exiting->empty()) {
475 errs() << "VPlan vector loop exiting block must end with BranchOnCount or "
476 "BranchOnCond VPInstruction but is empty\n";
477 return false;
478 }
479
480 auto *LastInst = dyn_cast<VPInstruction>(std::prev(Exiting->end()));
481 if (!LastInst || (LastInst->getOpcode() != VPInstruction::BranchOnCount &&
482 LastInst->getOpcode() != VPInstruction::BranchOnCond)) {
483 errs() << "VPlan vector loop exit must end with BranchOnCount or "
484 "BranchOnCond VPInstruction\n";
485 return false;
486 }
487
488 return true;
489}
490
491bool llvm::verifyVPlanIsValid(const VPlan &Plan, bool VerifyLate) {
492 VPDominatorTree VPDT;
493 VPDT.recalculate(const_cast<VPlan &>(Plan));
494 VPTypeAnalysis TypeInfo(Plan);
495 VPlanVerifier Verifier(VPDT, TypeInfo, VerifyLate);
496 return Verifier.verify(Plan);
497}
@ Default
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define I(x, y, z)
Definition MD5.cpp:58
ppc ctr loops verify
verify safepoint Safepoint IR Verifier
This file defines the SmallPtrSet class.
This file implements the TypeSwitch template, which mimics a switch() statement whose cases are type ...
This file implements dominator tree analysis for a single level of a VPlan's H-CFG.
This file contains the declarations of different VPlan-related auxiliary helpers.
static bool hasDuplicates(const SmallVectorImpl< VPBlockBase * > &VPBlockVec)
Utility function that checks whether VPBlockVec has duplicate VPBlockBases.
This file declares the class VPlanVerifier, which contains utility functions to check the consistency...
This file contains the declarations of the Vectorization Plan base classes:
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void recalculate(ParentType &Func)
recalculate - compute a dominator tree for the given function
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:281
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
VPBasicBlock serves as the leaf of the Hierarchical Control-Flow Graph.
Definition VPlan.h:3754
iterator end()
Definition VPlan.h:3791
iterator begin()
Recipe iterator methods.
Definition VPlan.h:3789
bool empty() const
Definition VPlan.h:3800
VPBlockBase is the building block of the Hierarchical Control-Flow Graph.
Definition VPlan.h:81
VPRegionBlock * getParent()
Definition VPlan.h:173
size_t getNumSuccessors() const
Definition VPlan.h:219
size_t getNumPredecessors() const
Definition VPlan.h:220
const VPBlocksTy & getPredecessors() const
Definition VPlan.h:204
const VPBlocksTy & getSuccessors() const
Definition VPlan.h:198
static bool isHeader(const VPBlockBase *VPB, const VPDominatorTree &VPDT)
Returns true if VPB is a loop header, based on regions or VPDT in their absence.
Definition VPlan.cpp:220
Template specialization of the standard LLVM dominator tree utility for VPBlockBases.
This is a concrete Recipe that models a single VPlan-level instruction.
Definition VPlan.h:979
unsigned getOpcode() const
Definition VPlan.h:1120
VPRegionBlock represents a collection of VPBasicBlocks and VPRegionBlocks which form a Single-Entry-S...
Definition VPlan.h:3942
const VPBlockBase * getEntry() const
Definition VPlan.h:3978
const VPBlockBase * getExiting() const
Definition VPlan.h:3990
An analysis for type-inference for VPValues.
Type * inferScalarType(const VPValue *V)
Infer the type of V. Returns the scalar type of V.
user_range users()
Definition VPlanValue.h:134
VPlan models a candidate for vectorization, encoding various decisions take to produce efficient outp...
Definition VPlan.h:4045
VPBasicBlock * getEntry()
Definition VPlan.h:4144
LLVM_ABI_FOR_TEST VPRegionBlock * getVectorLoopRegion()
Returns the VPRegionBlock of the vector loop.
Definition VPlan.cpp:1050
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:194
@ Entry
Definition COFF.h:862
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1727
LLVM_ABI_FOR_TEST bool verifyVPlanIsValid(const VPlan &Plan, bool VerifyLate=false)
Verify invariants for general VPlans.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:649
iterator_range< df_iterator< VPBlockShallowTraversalWrapper< VPBlockBase * > > > vp_depth_first_shallow(VPBlockBase *G)
Returns an iterator range to traverse the graph starting at G in depth-first order.
Definition VPlanCFG.h:216
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1734
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1741
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:1956
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:565
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1899