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