blob: cb622a23cff0f1634fab2ca70516760f5a29ec18 [file] [log] [blame]
Chris Lattner21e67f62018-07-06 10:46:19 -07001//===- Verifier.cpp - MLIR Verifier Implementation ------------------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the verify() methods on the various IR types, performing
19// (potentially expensive) checks on the holistic structure of the code. This
20// can be used for detecting bugs in compiler transformations and hand written
21// .mlir files.
22//
23// The checks in this file are only for things that can occur as part of IR
24// transformations: e.g. violation of dominance information, malformed operation
25// attributes, etc. MLIR supports transformations moving IR through locally
26// invalid states (e.g. unlinking an instruction from an instruction before
27// re-inserting it in a new place), but each transformation must complete with
28// the IR in a valid form.
29//
30// This should not check for things that are always wrong by construction (e.g.
31// affine maps or other immutable structures that are incorrect), because those
32// are not mutable and can be checked at time of construction.
33//
34//===----------------------------------------------------------------------===//
35
36#include "mlir/IR/CFGFunction.h"
37#include "mlir/IR/MLFunction.h"
38#include "mlir/IR/Module.h"
39#include "mlir/IR/OperationSet.h"
40#include "llvm/ADT/Twine.h"
41#include "llvm/Support/raw_ostream.h"
42using namespace mlir;
43
Chris Lattner40746442018-07-21 14:32:09 -070044namespace {
45/// Base class for the verifiers in this file. It is a pervasive truth that
46/// this file treats "true" as an error that needs to be recovered from, and
47/// "false" as success.
48///
49class Verifier {
50public:
51 template <typename T>
52 static void failure(const Twine &message, const T &value, raw_ostream &os) {
53 // Print the error message and flush the stream in case printing the value
54 // causes a crash.
55 os << "MLIR verification failure: " + message + "\n";
56 os.flush();
57 value.print(os);
58 }
59
60 template <typename T>
61 bool failure(const Twine &message, const T &value) {
62 // If the caller isn't trying to collect failure information, just print
63 // the result and abort.
64 if (!errorResult) {
65 failure(message, value, llvm::errs());
66 abort();
67 }
68
69 // Otherwise, emit the error into the string and return true.
70 llvm::raw_string_ostream os(*errorResult);
71 failure(message, value, os);
72 os.flush();
73 return true;
74 }
75
76protected:
77 explicit Verifier(std::string *errorResult) : errorResult(errorResult) {}
78
79private:
80 std::string *errorResult;
81};
82} // end anonymous namespace
Chris Lattner21e67f62018-07-06 10:46:19 -070083
84//===----------------------------------------------------------------------===//
85// CFG Functions
86//===----------------------------------------------------------------------===//
87
88namespace {
Chris Lattner40746442018-07-21 14:32:09 -070089class CFGFuncVerifier : public Verifier {
Chris Lattner21e67f62018-07-06 10:46:19 -070090public:
91 const CFGFunction &fn;
92 OperationSet &operationSet;
93
Chris Lattner40746442018-07-21 14:32:09 -070094 CFGFuncVerifier(const CFGFunction &fn, std::string *errorResult)
95 : Verifier(errorResult), fn(fn),
96 operationSet(OperationSet::get(fn.getContext())) {}
Chris Lattner21e67f62018-07-06 10:46:19 -070097
Chris Lattner40746442018-07-21 14:32:09 -070098 bool verify();
99 bool verifyBlock(const BasicBlock &block);
100 bool verifyOperation(const OperationInst &inst);
101 bool verifyTerminator(const TerminatorInst &term);
102 bool verifyReturn(const ReturnInst &inst);
Chris Lattner1604e472018-07-23 08:42:19 -0700103 bool verifyBranch(const BranchInst &inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700104};
105} // end anonymous namespace
106
Chris Lattner40746442018-07-21 14:32:09 -0700107bool CFGFuncVerifier::verify() {
Chris Lattner21e67f62018-07-06 10:46:19 -0700108 // TODO: Lots to be done here, including verifying dominance information when
109 // we have uses and defs.
James Molloy61a656c2018-07-22 15:45:24 -0700110 // TODO: Verify the first block has no predecessors.
111
112 if (fn.empty())
113 return failure("cfgfunc must have at least one basic block", fn);
114
115 // Verify that the argument list of the function and the arg list of the first
116 // block line up.
117 auto *firstBB = &fn.front();
118 auto fnInputTypes = fn.getType()->getInputs();
119 if (fnInputTypes.size() != firstBB->getNumArguments())
120 return failure("first block of cfgfunc must have " +
121 Twine(fnInputTypes.size()) +
122 " arguments to match function signature",
123 fn);
124 for (unsigned i = 0, e = firstBB->getNumArguments(); i != e; ++i)
125 if (fnInputTypes[i] != firstBB->getArgument(i)->getType())
126 return failure(
127 "type of argument #" + Twine(i) +
128 " must match corresponding argument in function signature",
129 fn);
Chris Lattner21e67f62018-07-06 10:46:19 -0700130
131 for (auto &block : fn) {
Chris Lattner40746442018-07-21 14:32:09 -0700132 if (verifyBlock(block))
133 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700134 }
Chris Lattner40746442018-07-21 14:32:09 -0700135 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700136}
137
Chris Lattner40746442018-07-21 14:32:09 -0700138bool CFGFuncVerifier::verifyBlock(const BasicBlock &block) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700139 if (!block.getTerminator())
Chris Lattner40746442018-07-21 14:32:09 -0700140 return failure("basic block with no terminator", block);
141
142 if (verifyTerminator(*block.getTerminator()))
143 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700144
James Molloy61a656c2018-07-22 15:45:24 -0700145 for (auto *arg : block.getArguments()) {
146 if (arg->getOwner() != &block)
147 return failure("basic block argument not owned by block", block);
148 }
149
Chris Lattner21e67f62018-07-06 10:46:19 -0700150 for (auto &inst : block) {
Chris Lattner40746442018-07-21 14:32:09 -0700151 if (verifyOperation(inst))
152 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700153 }
Chris Lattner40746442018-07-21 14:32:09 -0700154 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700155}
156
Chris Lattner40746442018-07-21 14:32:09 -0700157bool CFGFuncVerifier::verifyTerminator(const TerminatorInst &term) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700158 if (term.getFunction() != &fn)
Chris Lattner40746442018-07-21 14:32:09 -0700159 return failure("terminator in the wrong function", term);
Chris Lattner21e67f62018-07-06 10:46:19 -0700160
161 // TODO: Check that operands are structurally ok.
162 // TODO: Check that successors are in the right function.
Chris Lattner40746442018-07-21 14:32:09 -0700163
164 if (auto *ret = dyn_cast<ReturnInst>(&term))
165 return verifyReturn(*ret);
166
Chris Lattner1604e472018-07-23 08:42:19 -0700167 if (auto *br = dyn_cast<BranchInst>(&term))
168 return verifyBranch(*br);
169
Chris Lattner40746442018-07-21 14:32:09 -0700170 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700171}
172
Chris Lattner40746442018-07-21 14:32:09 -0700173bool CFGFuncVerifier::verifyReturn(const ReturnInst &inst) {
174 // Verify that the return operands match the results of the function.
175 auto results = fn.getType()->getResults();
176 if (inst.getNumOperands() != results.size())
177 return failure("return has " + Twine(inst.getNumOperands()) +
178 " operands, but enclosing function returns " +
179 Twine(results.size()),
180 inst);
181
Chris Lattner1604e472018-07-23 08:42:19 -0700182 for (unsigned i = 0, e = results.size(); i != e; ++i)
183 if (inst.getOperand(i)->getType() != results[i])
184 return failure("type of return operand " + Twine(i) +
185 " doesn't match result function result type",
186 inst);
187
188 return false;
189}
190
191bool CFGFuncVerifier::verifyBranch(const BranchInst &inst) {
192 // Verify that the number of operands lines up with the number of BB arguments
193 // in the successor.
194 auto dest = inst.getDest();
195 if (inst.getNumOperands() != dest->getNumArguments())
196 return failure("branch has " + Twine(inst.getNumOperands()) +
197 " operands, but target block has " +
198 Twine(dest->getNumArguments()),
199 inst);
200
201 for (unsigned i = 0, e = inst.getNumOperands(); i != e; ++i)
202 if (inst.getOperand(i)->getType() != dest->getArgument(i)->getType())
203 return failure("type of branch operand " + Twine(i) +
204 " doesn't match target bb argument type",
205 inst);
206
Chris Lattner40746442018-07-21 14:32:09 -0700207 return false;
208}
209
210bool CFGFuncVerifier::verifyOperation(const OperationInst &inst) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700211 if (inst.getFunction() != &fn)
Chris Lattner40746442018-07-21 14:32:09 -0700212 return failure("operation in the wrong function", inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700213
214 // TODO: Check that operands are structurally ok.
215
216 // See if we can get operation info for this.
217 if (auto *opInfo = inst.getAbstractOperation(fn.getContext())) {
218 if (auto errorMessage = opInfo->verifyInvariants(&inst))
Chris Lattner9361fb32018-07-24 08:34:58 -0700219 return failure(Twine("'") + inst.getName().str() + "' op " + errorMessage,
220 inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700221 }
Chris Lattner40746442018-07-21 14:32:09 -0700222
223 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700224}
225
226//===----------------------------------------------------------------------===//
227// ML Functions
228//===----------------------------------------------------------------------===//
229
230namespace {
Chris Lattner40746442018-07-21 14:32:09 -0700231class MLFuncVerifier : public Verifier {
Chris Lattner21e67f62018-07-06 10:46:19 -0700232public:
233 const MLFunction &fn;
234
Chris Lattner40746442018-07-21 14:32:09 -0700235 MLFuncVerifier(const MLFunction &fn, std::string *errorResult)
236 : Verifier(errorResult), fn(fn) {}
Chris Lattner21e67f62018-07-06 10:46:19 -0700237
Chris Lattner40746442018-07-21 14:32:09 -0700238 bool verify() {
Chris Lattner21e67f62018-07-06 10:46:19 -0700239 // TODO.
Chris Lattner40746442018-07-21 14:32:09 -0700240 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700241 }
242};
243} // end anonymous namespace
244
245//===----------------------------------------------------------------------===//
246// Entrypoints
247//===----------------------------------------------------------------------===//
248
249/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700250/// compiler bugs. On error, this fills in the string and return true,
251/// or aborts if the string was not provided.
252bool Function::verify(std::string *errorResult) const {
Chris Lattner21e67f62018-07-06 10:46:19 -0700253 switch (getKind()) {
254 case Kind::ExtFunc:
255 // No body, nothing can be wrong here.
Chris Lattner40746442018-07-21 14:32:09 -0700256 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700257 case Kind::CFGFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700258 return CFGFuncVerifier(*cast<CFGFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700259 case Kind::MLFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700260 return MLFuncVerifier(*cast<MLFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700261 }
262}
263
264/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700265/// compiler bugs. On error, this fills in the string and return true,
266/// or aborts if the string was not provided.
267bool Module::verify(std::string *errorResult) const {
268
Chris Lattner21e67f62018-07-06 10:46:19 -0700269 /// Check that each function is correct.
270 for (auto fn : functionList) {
Chris Lattner40746442018-07-21 14:32:09 -0700271 if (fn->verify(errorResult))
272 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700273 }
Chris Lattner40746442018-07-21 14:32:09 -0700274
275 // Make sure the error string is empty on success.
276 if (errorResult)
277 errorResult->clear();
278 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700279}