1 //===- Verifier.cpp - MLIR Verifier Implementation ------------------------===//
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 // This file implements the verify() methods on the various IR types, performing
10 // (potentially expensive) checks on the holistic structure of the code.  This
11 // can be used for detecting bugs in compiler transformations and hand written
12 // .mlir files.
13 //
14 // The checks in this file are only for things that can occur as part of IR
15 // transformations: e.g. violation of dominance information, malformed operation
16 // attributes, etc.  MLIR supports transformations moving IR through locally
17 // invalid states (e.g. unlinking an operation from a block before re-inserting
18 // it in a new place), but each transformation must complete with the IR in a
19 // valid form.
20 //
21 // This should not check for things that are always wrong by construction (e.g.
22 // attributes or other immutable structures that are incorrect), because those
23 // are not mutable and can be checked at time of construction.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "mlir/IR/Verifier.h"
28 #include "mlir/IR/Attributes.h"
29 #include "mlir/IR/Dialect.h"
30 #include "mlir/IR/Dominance.h"
31 #include "mlir/IR/Operation.h"
32 #include "mlir/IR/RegionKindInterface.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/Support/FormatVariadic.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Regex.h"
37 
38 using namespace mlir;
39 
40 namespace {
41 /// This class encapsulates all the state used to verify an operation region.
42 class OperationVerifier {
43 public:
44   explicit OperationVerifier(MLIRContext *ctx) : ctx(ctx) {}
45 
46   /// Verify the given operation.
47   LogicalResult verify(Operation &op);
48 
49 private:
50   /// Verify the given potentially nested region or block.
51   LogicalResult verifyRegion(Region &region);
52   LogicalResult verifyBlock(Block &block);
53   LogicalResult verifyOperation(Operation &op);
54 
55   /// Verify the dominance property of operations within the given Region.
56   LogicalResult verifyDominance(Region &region);
57 
58   /// Verify the dominance property of regions contained within the given
59   /// Operation.
60   LogicalResult verifyDominanceOfContainedRegions(Operation &op);
61 
62   /// Emit an error for the given block.
63   InFlightDiagnostic emitError(Block &bb, const Twine &message) {
64     // Take the location information for the first operation in the block.
65     if (!bb.empty())
66       return bb.front().emitError(message);
67 
68     // Worst case, fall back to using the parent's location.
69     return mlir::emitError(bb.getParent()->getLoc(), message);
70   }
71 
72   /// The current context for the verifier.
73   MLIRContext *ctx;
74 
75   /// Dominance information for this operation, when checking dominance.
76   DominanceInfo *domInfo = nullptr;
77 };
78 } // end anonymous namespace
79 
80 /// Verify the given operation.
81 LogicalResult OperationVerifier::verify(Operation &op) {
82   // Verify the operation first.
83   if (failed(verifyOperation(op)))
84     return failure();
85 
86   // Since everything looks structurally ok to this point, we do a dominance
87   // check for any nested regions. We do this as a second pass since malformed
88   // CFG's can cause dominator analysis constructure to crash and we want the
89   // verifier to be resilient to malformed code.
90   DominanceInfo theDomInfo(&op);
91   domInfo = &theDomInfo;
92   if (failed(verifyDominanceOfContainedRegions(op)))
93     return failure();
94 
95   domInfo = nullptr;
96   return success();
97 }
98 
99 LogicalResult OperationVerifier::verifyRegion(Region &region) {
100   if (region.empty())
101     return success();
102 
103   // Verify the first block has no predecessors.
104   auto *firstBB = &region.front();
105   if (!firstBB->hasNoPredecessors())
106     return mlir::emitError(region.getLoc(),
107                            "entry block of region may not have predecessors");
108 
109   // Verify each of the blocks within the region.
110   for (Block &block : region)
111     if (failed(verifyBlock(block)))
112       return failure();
113   return success();
114 }
115 
116 /// Returns true if this block may be valid without terminator. That is if:
117 /// - it does not have a parent region.
118 /// - Or the parent region have a single block and:
119 ///    - This region does not have a parent op.
120 ///    - Or the parent op is unregistered.
121 ///    - Or the parent op has the NoTerminator trait.
122 static bool mayNotHaveTerminator(Block *block) {
123   if (!block->getParent())
124     return true;
125   if (!llvm::hasSingleElement(*block->getParent()))
126     return false;
127   Operation *op = block->getParentOp();
128   return !op || op->mightHaveTrait<OpTrait::NoTerminator>();
129 }
130 
131 LogicalResult OperationVerifier::verifyBlock(Block &block) {
132   for (auto arg : block.getArguments())
133     if (arg.getOwner() != &block)
134       return emitError(block, "block argument not owned by block");
135 
136   // Verify that this block has a terminator.
137 
138   if (block.empty()) {
139     if (mayNotHaveTerminator(&block))
140       return success();
141     return emitError(block, "empty block: expect at least a terminator");
142   }
143 
144   // Verify the non-terminator operations separately so that we can verify
145   // they have no successors.
146   for (auto &op : llvm::make_range(block.begin(), std::prev(block.end()))) {
147     if (op.getNumSuccessors() != 0)
148       return op.emitError(
149           "operation with block successors must terminate its parent block");
150 
151     if (failed(verifyOperation(op)))
152       return failure();
153   }
154 
155   // Verify the terminator.
156   Operation &terminator = block.back();
157   if (failed(verifyOperation(terminator)))
158     return failure();
159 
160   if (mayNotHaveTerminator(&block))
161     return success();
162 
163   if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
164     return block.back().emitError("block with no terminator, has ")
165            << terminator;
166 
167   // Verify that this block is not branching to a block of a different
168   // region.
169   for (Block *successor : block.getSuccessors())
170     if (successor->getParent() != block.getParent())
171       return block.back().emitOpError(
172           "branching to block of a different region");
173 
174   return success();
175 }
176 
177 LogicalResult OperationVerifier::verifyOperation(Operation &op) {
178   // Check that operands are non-nil and structurally ok.
179   for (auto operand : op.getOperands())
180     if (!operand)
181       return op.emitError("null operand found");
182 
183   /// Verify that all of the attributes are okay.
184   for (auto attr : op.getAttrs()) {
185     // Check for any optional dialect specific attributes.
186     if (auto *dialect = attr.first.getDialect())
187       if (failed(dialect->verifyOperationAttribute(&op, attr)))
188         return failure();
189   }
190 
191   // If we can get operation info for this, check the custom hook.
192   OperationName opName = op.getName();
193   auto *opInfo = opName.getAbstractOperation();
194   if (opInfo && failed(opInfo->verifyInvariants(&op)))
195     return failure();
196 
197   auto kindInterface = dyn_cast<mlir::RegionKindInterface>(op);
198 
199   // Verify that all child regions are ok.
200   unsigned numRegions = op.getNumRegions();
201   for (unsigned i = 0; i < numRegions; i++) {
202     Region &region = op.getRegion(i);
203     RegionKind kind =
204         kindInterface ? kindInterface.getRegionKind(i) : RegionKind::SSACFG;
205     // Check that Graph Regions only have a single basic block. This is
206     // similar to the code in SingleBlockImplicitTerminator, but doesn't
207     // require the trait to be specified. This arbitrary limitation is
208     // designed to limit the number of cases that have to be handled by
209     // transforms and conversions until the concept stabilizes.
210     if (op.isRegistered() && kind == RegionKind::Graph) {
211       // Empty regions are fine.
212       if (region.empty())
213         continue;
214 
215       // Non-empty regions must contain a single basic block.
216       if (std::next(region.begin()) != region.end())
217         return op.emitOpError("expects graph region #")
218                << i << " to have 0 or 1 blocks";
219     }
220     if (failed(verifyRegion(region)))
221       return failure();
222   }
223 
224   // If this is a registered operation, there is nothing left to do.
225   if (opInfo)
226     return success();
227 
228   // Otherwise, verify that the parent dialect allows un-registered operations.
229   Dialect *dialect = opName.getDialect();
230   if (!dialect) {
231     if (!ctx->allowsUnregisteredDialects()) {
232       return op.emitOpError()
233              << "created with unregistered dialect. If this is "
234                 "intended, please call allowUnregisteredDialects() on the "
235                 "MLIRContext, or use -allow-unregistered-dialect with "
236                 "mlir-opt";
237     }
238     return success();
239   }
240 
241   if (!dialect->allowsUnknownOperations()) {
242     return op.emitError("unregistered operation '")
243            << op.getName() << "' found in dialect ('" << dialect->getNamespace()
244            << "') that does not allow unknown operations";
245   }
246 
247   return success();
248 }
249 
250 /// Attach a note to an in-flight diagnostic that provide more information about
251 /// where an op operand is defined.
252 static void attachNoteForOperandDefinition(InFlightDiagnostic &diag,
253                                            Operation &op, Value operand) {
254   if (auto *useOp = operand.getDefiningOp()) {
255     Diagnostic &note = diag.attachNote(useOp->getLoc());
256     note << "operand defined here";
257     Block *block1 = op.getBlock();
258     Block *block2 = useOp->getBlock();
259     Region *region1 = block1->getParent();
260     Region *region2 = block2->getParent();
261     if (block1 == block2)
262       note << " (op in the same block)";
263     else if (region1 == region2)
264       note << " (op in the same region)";
265     else if (region2->isProperAncestor(region1))
266       note << " (op in a parent region)";
267     else if (region1->isProperAncestor(region2))
268       note << " (op in a child region)";
269     else
270       note << " (op is neither in a parent nor in a child region)";
271     return;
272   }
273   // Block argument case.
274   Block *block1 = op.getBlock();
275   Block *block2 = operand.cast<BlockArgument>().getOwner();
276   Region *region1 = block1->getParent();
277   Region *region2 = block2->getParent();
278   Location loc = UnknownLoc::get(op.getContext());
279   if (block2->getParentOp())
280     loc = block2->getParentOp()->getLoc();
281   Diagnostic &note = diag.attachNote(loc);
282   if (!region2) {
283     note << " (block without parent)";
284     return;
285   }
286   if (block1 == block2)
287     llvm::report_fatal_error("Internal error in dominance verification");
288   int index = std::distance(region2->begin(), block2->getIterator());
289   note << "operand defined as a block argument (block #" << index;
290   if (region1 == region2)
291     note << " in the same region)";
292   else if (region2->isProperAncestor(region1))
293     note << " in a parent region)";
294   else if (region1->isProperAncestor(region2))
295     note << " in a child region)";
296   else
297     note << " neither in a parent nor in a child region)";
298 }
299 
300 LogicalResult OperationVerifier::verifyDominance(Region &region) {
301   // Verify the dominance of each of the held operations.
302   for (Block &block : region) {
303     // Dominance is only meaningful inside reachable blocks.
304     if (domInfo->isReachableFromEntry(&block))
305       for (Operation &op : block)
306         // Check that operands properly dominate this use.
307         for (unsigned operandNo = 0, e = op.getNumOperands(); operandNo != e;
308              ++operandNo) {
309           Value operand = op.getOperand(operandNo);
310           if (domInfo->properlyDominates(operand, &op))
311             continue;
312 
313           InFlightDiagnostic diag = op.emitError("operand #")
314                                     << operandNo
315                                     << " does not dominate this use";
316           attachNoteForOperandDefinition(diag, op, operand);
317           return failure();
318         }
319     // Recursively verify dominance within each operation in the
320     // block, even if the block itself is not reachable, or we are in
321     // a region which doesn't respect dominance.
322     for (Operation &op : block)
323       if (failed(verifyDominanceOfContainedRegions(op)))
324         return failure();
325   }
326   return success();
327 }
328 
329 /// Verify the dominance of each of the nested blocks within the given operation
330 LogicalResult
331 OperationVerifier::verifyDominanceOfContainedRegions(Operation &op) {
332   for (Region &region : op.getRegions()) {
333     if (failed(verifyDominance(region)))
334       return failure();
335   }
336   return success();
337 }
338 
339 //===----------------------------------------------------------------------===//
340 // Entrypoint
341 //===----------------------------------------------------------------------===//
342 
343 /// Perform (potentially expensive) checks of invariants, used to detect
344 /// compiler bugs.  On error, this reports the error through the MLIRContext and
345 /// returns failure.
346 LogicalResult mlir::verify(Operation *op) {
347   return OperationVerifier(op->getContext()).verify(*op);
348 }
349