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