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/Parallel.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Regex.h"
38 #include <atomic>
39 
40 using namespace mlir;
41 
42 namespace {
43 /// This class encapsulates all the state used to verify an operation region.
44 class OperationVerifier {
45 public:
46   explicit OperationVerifier(MLIRContext *context)
47       : parallelismEnabled(context->isMultithreadingEnabled()) {}
48 
49   /// Verify the given operation.
50   LogicalResult verifyOpAndDominance(Operation &op);
51 
52 private:
53   LogicalResult
54   verifyBlock(Block &block,
55               SmallVectorImpl<Operation *> &opsWithIsolatedRegions);
56   /// Verify the properties and dominance relationships of this operation,
57   /// stopping region recursion at any "isolated from above operations".  Any
58   /// such ops are returned in the opsWithIsolatedRegions vector.
59   LogicalResult
60   verifyOperation(Operation &op,
61                   SmallVectorImpl<Operation *> &opsWithIsolatedRegions);
62 
63   /// Verify the dominance property of regions contained within the given
64   /// Operation.
65   LogicalResult verifyDominanceOfContainedRegions(Operation &op,
66                                                   DominanceInfo &domInfo);
67 
68   /// This is true if parallelism is enabled on the MLIRContext.
69   const bool parallelismEnabled;
70 };
71 } // end anonymous namespace
72 
73 LogicalResult OperationVerifier::verifyOpAndDominance(Operation &op) {
74   SmallVector<Operation *> opsWithIsolatedRegions;
75 
76   // Verify the operation first, collecting any IsolatedFromAbove operations.
77   if (failed(verifyOperation(op, opsWithIsolatedRegions)))
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 construction to crash and we want the
83   // verifier to be resilient to malformed code.
84   if (op.getNumRegions() != 0) {
85     DominanceInfo domInfo;
86     if (failed(verifyDominanceOfContainedRegions(op, domInfo)))
87       return failure();
88   }
89 
90   // Check the dominance properties and invariants of any operations in the
91   // regions contained by the 'opsWithIsolatedRegions' operations.
92   if (!parallelismEnabled || opsWithIsolatedRegions.size() <= 1) {
93     // If parallelism is disabled or if there is only 0/1 operation to do, use
94     // a simple non-parallel loop.
95     for (Operation *op : opsWithIsolatedRegions) {
96       if (failed(verifyOpAndDominance(*op)))
97         return failure();
98     }
99   } else {
100     // Otherwise, verify the operations and their bodies in parallel.
101     ParallelDiagnosticHandler handler(op.getContext());
102     std::atomic<bool> passFailed(false);
103     llvm::parallelForEachN(0, opsWithIsolatedRegions.size(), [&](size_t opIdx) {
104       handler.setOrderIDForThread(opIdx);
105       if (failed(verifyOpAndDominance(*opsWithIsolatedRegions[opIdx])))
106         passFailed = true;
107       handler.eraseOrderIDForThread();
108     });
109     if (passFailed)
110       return failure();
111   }
112 
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 mayBeValidWithoutTerminator(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(
132     Block &block, SmallVectorImpl<Operation *> &opsWithIsolatedRegions) {
133 
134   for (auto arg : block.getArguments())
135     if (arg.getOwner() != &block)
136       return emitError(arg.getLoc(), "block argument not owned by block");
137 
138   // Verify that this block has a terminator.
139   if (block.empty()) {
140     if (mayBeValidWithoutTerminator(&block))
141       return success();
142     return emitError(block.getParent()->getLoc(),
143                      "empty block: expect at least a terminator");
144   }
145 
146   // Check each operation, and make sure there are no branches out of the
147   // middle of this block.
148   for (auto &op : block) {
149     // Only the last instructions is allowed to have successors.
150     if (op.getNumSuccessors() != 0 && &op != &block.back())
151       return op.emitError(
152           "operation with block successors must terminate its parent block");
153 
154     // If this operation has regions and is IsolatedFromAbove, we defer
155     // checking.  This allows us to parallelize verification better.
156     if (op.getNumRegions() != 0 &&
157         op.hasTrait<OpTrait::IsIsolatedFromAbove>()) {
158       opsWithIsolatedRegions.push_back(&op);
159     } else {
160       // Otherwise, check the operation inline.
161       if (failed(verifyOperation(op, opsWithIsolatedRegions)))
162         return failure();
163     }
164   }
165 
166   // Verify that this block is not branching to a block of a different
167   // region.
168   for (Block *successor : block.getSuccessors())
169     if (successor->getParent() != block.getParent())
170       return block.back().emitOpError(
171           "branching to block of a different region");
172 
173   // If this block doesn't have to have a terminator, don't require it.
174   if (mayBeValidWithoutTerminator(&block))
175     return success();
176 
177   Operation &terminator = block.back();
178   if (!terminator.mightHaveTrait<OpTrait::IsTerminator>())
179     return block.back().emitError("block with no terminator, has ")
180            << terminator;
181 
182   return success();
183 }
184 
185 /// Verify the properties and dominance relationships of this operation,
186 /// stopping region recursion at any "isolated from above operations".  Any such
187 /// ops are returned in the opsWithIsolatedRegions vector.
188 LogicalResult OperationVerifier::verifyOperation(
189     Operation &op, SmallVectorImpl<Operation *> &opsWithIsolatedRegions) {
190   // Check that operands are non-nil and structurally ok.
191   for (auto operand : op.getOperands())
192     if (!operand)
193       return op.emitError("null operand found");
194 
195   /// Verify that all of the attributes are okay.
196   for (auto attr : op.getAttrs()) {
197     // Check for any optional dialect specific attributes.
198     if (auto *dialect = attr.first.getDialect())
199       if (failed(dialect->verifyOperationAttribute(&op, attr)))
200         return failure();
201   }
202 
203   // If we can get operation info for this, check the custom hook.
204   OperationName opName = op.getName();
205   auto *opInfo = opName.getAbstractOperation();
206   if (opInfo && failed(opInfo->verifyInvariants(&op)))
207     return failure();
208 
209   if (unsigned numRegions = op.getNumRegions()) {
210     auto kindInterface = dyn_cast<RegionKindInterface>(op);
211 
212     // Verify that all child regions are ok.
213     for (unsigned i = 0; i < numRegions; ++i) {
214       Region &region = op.getRegion(i);
215       RegionKind kind =
216           kindInterface ? kindInterface.getRegionKind(i) : RegionKind::SSACFG;
217       // Check that Graph Regions only have a single basic block. This is
218       // similar to the code in SingleBlockImplicitTerminator, but doesn't
219       // require the trait to be specified. This arbitrary limitation is
220       // designed to limit the number of cases that have to be handled by
221       // transforms and conversions.
222       if (op.isRegistered() && kind == RegionKind::Graph) {
223         // Non-empty regions must contain a single basic block.
224         if (!region.empty() && !region.hasOneBlock())
225           return op.emitOpError("expects graph region #")
226                  << i << " to have 0 or 1 blocks";
227       }
228 
229       if (region.empty())
230         continue;
231 
232       // Verify the first block has no predecessors.
233       Block *firstBB = &region.front();
234       if (!firstBB->hasNoPredecessors())
235         return emitError(op.getLoc(),
236                          "entry block of region may not have predecessors");
237 
238       // Verify each of the blocks within the region.
239       for (Block &block : region)
240         if (failed(verifyBlock(block, opsWithIsolatedRegions)))
241           return failure();
242     }
243   }
244 
245   // If this is a registered operation, there is nothing left to do.
246   if (opInfo)
247     return success();
248 
249   // Otherwise, verify that the parent dialect allows un-registered operations.
250   Dialect *dialect = opName.getDialect();
251   if (!dialect) {
252     if (!op.getContext()->allowsUnregisteredDialects()) {
253       return op.emitOpError()
254              << "created with unregistered dialect. If this is "
255                 "intended, please call allowUnregisteredDialects() on the "
256                 "MLIRContext, or use -allow-unregistered-dialect with "
257                 "mlir-opt";
258     }
259     return success();
260   }
261 
262   if (!dialect->allowsUnknownOperations()) {
263     return op.emitError("unregistered operation '")
264            << op.getName() << "' found in dialect ('" << dialect->getNamespace()
265            << "') that does not allow unknown operations";
266   }
267 
268   return success();
269 }
270 
271 //===----------------------------------------------------------------------===//
272 // Dominance Checking
273 //===----------------------------------------------------------------------===//
274 
275 /// Emit an error when the specified operand of the specified operation is an
276 /// invalid use because of dominance properties.
277 static void diagnoseInvalidOperandDominance(Operation &op, unsigned operandNo) {
278   InFlightDiagnostic diag = op.emitError("operand #")
279                             << operandNo << " does not dominate this use";
280 
281   Value operand = op.getOperand(operandNo);
282 
283   /// Attach a note to an in-flight diagnostic that provide more information
284   /// about where an op operand is defined.
285   if (auto *useOp = operand.getDefiningOp()) {
286     Diagnostic &note = diag.attachNote(useOp->getLoc());
287     note << "operand defined here";
288     Block *block1 = op.getBlock();
289     Block *block2 = useOp->getBlock();
290     Region *region1 = block1->getParent();
291     Region *region2 = block2->getParent();
292     if (block1 == block2)
293       note << " (op in the same block)";
294     else if (region1 == region2)
295       note << " (op in the same region)";
296     else if (region2->isProperAncestor(region1))
297       note << " (op in a parent region)";
298     else if (region1->isProperAncestor(region2))
299       note << " (op in a child region)";
300     else
301       note << " (op is neither in a parent nor in a child region)";
302     return;
303   }
304   // Block argument case.
305   Block *block1 = op.getBlock();
306   Block *block2 = operand.cast<BlockArgument>().getOwner();
307   Region *region1 = block1->getParent();
308   Region *region2 = block2->getParent();
309   Location loc = UnknownLoc::get(op.getContext());
310   if (block2->getParentOp())
311     loc = block2->getParentOp()->getLoc();
312   Diagnostic &note = diag.attachNote(loc);
313   if (!region2) {
314     note << " (block without parent)";
315     return;
316   }
317   if (block1 == block2)
318     llvm::report_fatal_error("Internal error in dominance verification");
319   int index = std::distance(region2->begin(), block2->getIterator());
320   note << "operand defined as a block argument (block #" << index;
321   if (region1 == region2)
322     note << " in the same region)";
323   else if (region2->isProperAncestor(region1))
324     note << " in a parent region)";
325   else if (region1->isProperAncestor(region2))
326     note << " in a child region)";
327   else
328     note << " neither in a parent nor in a child region)";
329 }
330 
331 /// Verify the dominance of each of the nested blocks within the given operation
332 LogicalResult
333 OperationVerifier::verifyDominanceOfContainedRegions(Operation &op,
334                                                      DominanceInfo &domInfo) {
335   for (Region &region : op.getRegions()) {
336     // Verify the dominance of each of the held operations.
337     for (Block &block : region) {
338       // Dominance is only meaningful inside reachable blocks.
339       bool isReachable = domInfo.isReachableFromEntry(&block);
340 
341       for (Operation &op : block) {
342         if (isReachable) {
343           // Check that operands properly dominate this use.
344           for (auto operand : llvm::enumerate(op.getOperands())) {
345             if (domInfo.properlyDominates(operand.value(), &op))
346               continue;
347 
348             diagnoseInvalidOperandDominance(op, operand.index());
349             return failure();
350           }
351         }
352 
353         // Recursively verify dominance within each operation in the
354         // block, even if the block itself is not reachable, or we are in
355         // a region which doesn't respect dominance.
356         if (op.getNumRegions() != 0) {
357           // If this operation is IsolatedFromAbove, then we'll handle it in the
358           // outer verification loop.
359           if (op.hasTrait<OpTrait::IsIsolatedFromAbove>())
360             continue;
361 
362           if (failed(verifyDominanceOfContainedRegions(op, domInfo)))
363             return failure();
364         }
365       }
366     }
367   }
368   return success();
369 }
370 
371 //===----------------------------------------------------------------------===//
372 // Entrypoint
373 //===----------------------------------------------------------------------===//
374 
375 /// Perform (potentially expensive) checks of invariants, used to detect
376 /// compiler bugs.  On error, this reports the error through the MLIRContext and
377 /// returns failure.
378 LogicalResult mlir::verify(Operation *op) {
379   return OperationVerifier(op->getContext()).verifyOpAndDominance(*op);
380 }
381