blob: 9e525561d791258e811db3318b6d95a234e5fb4e [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);
James Molloy4f788372018-07-24 15:01:27 -0700104 bool verifyCondBranch(const CondBranchInst &inst);
105
106 // Given a list of "operands" and "arguments" that are the same length, verify
107 // that the types of operands pointwise match argument types. The iterator
108 // types must expose the "getType()" function when dereferenced twice; that
109 // is, the iterator's value_type must be equivalent to SSAValue*.
110 template <typename OperandIteratorTy, typename ArgumentIteratorTy>
111 bool verifyOperandsMatchArguments(OperandIteratorTy opBegin,
112 OperandIteratorTy opEnd,
113 ArgumentIteratorTy argBegin,
114 const Instruction &instContext);
Chris Lattner21e67f62018-07-06 10:46:19 -0700115};
116} // end anonymous namespace
117
Chris Lattner40746442018-07-21 14:32:09 -0700118bool CFGFuncVerifier::verify() {
Chris Lattner21e67f62018-07-06 10:46:19 -0700119 // TODO: Lots to be done here, including verifying dominance information when
120 // we have uses and defs.
James Molloy61a656c2018-07-22 15:45:24 -0700121 // TODO: Verify the first block has no predecessors.
122
123 if (fn.empty())
124 return failure("cfgfunc must have at least one basic block", fn);
125
126 // Verify that the argument list of the function and the arg list of the first
127 // block line up.
128 auto *firstBB = &fn.front();
129 auto fnInputTypes = fn.getType()->getInputs();
130 if (fnInputTypes.size() != firstBB->getNumArguments())
131 return failure("first block of cfgfunc must have " +
132 Twine(fnInputTypes.size()) +
133 " arguments to match function signature",
134 fn);
135 for (unsigned i = 0, e = firstBB->getNumArguments(); i != e; ++i)
136 if (fnInputTypes[i] != firstBB->getArgument(i)->getType())
137 return failure(
138 "type of argument #" + Twine(i) +
139 " must match corresponding argument in function signature",
140 fn);
Chris Lattner21e67f62018-07-06 10:46:19 -0700141
142 for (auto &block : fn) {
Chris Lattner40746442018-07-21 14:32:09 -0700143 if (verifyBlock(block))
144 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700145 }
Chris Lattner40746442018-07-21 14:32:09 -0700146 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700147}
148
Chris Lattner40746442018-07-21 14:32:09 -0700149bool CFGFuncVerifier::verifyBlock(const BasicBlock &block) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700150 if (!block.getTerminator())
Chris Lattner40746442018-07-21 14:32:09 -0700151 return failure("basic block with no terminator", block);
152
153 if (verifyTerminator(*block.getTerminator()))
154 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700155
James Molloy61a656c2018-07-22 15:45:24 -0700156 for (auto *arg : block.getArguments()) {
157 if (arg->getOwner() != &block)
158 return failure("basic block argument not owned by block", block);
159 }
160
Chris Lattner21e67f62018-07-06 10:46:19 -0700161 for (auto &inst : block) {
Chris Lattner40746442018-07-21 14:32:09 -0700162 if (verifyOperation(inst))
163 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700164 }
Chris Lattner40746442018-07-21 14:32:09 -0700165 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700166}
167
Chris Lattner40746442018-07-21 14:32:09 -0700168bool CFGFuncVerifier::verifyTerminator(const TerminatorInst &term) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700169 if (term.getFunction() != &fn)
Chris Lattner40746442018-07-21 14:32:09 -0700170 return failure("terminator in the wrong function", term);
Chris Lattner21e67f62018-07-06 10:46:19 -0700171
172 // TODO: Check that operands are structurally ok.
173 // TODO: Check that successors are in the right function.
Chris Lattner40746442018-07-21 14:32:09 -0700174
175 if (auto *ret = dyn_cast<ReturnInst>(&term))
176 return verifyReturn(*ret);
177
Chris Lattner1604e472018-07-23 08:42:19 -0700178 if (auto *br = dyn_cast<BranchInst>(&term))
179 return verifyBranch(*br);
180
James Molloy4f788372018-07-24 15:01:27 -0700181 if (auto *br = dyn_cast<CondBranchInst>(&term))
182 return verifyCondBranch(*br);
183
Chris Lattner40746442018-07-21 14:32:09 -0700184 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700185}
186
Chris Lattner40746442018-07-21 14:32:09 -0700187bool CFGFuncVerifier::verifyReturn(const ReturnInst &inst) {
188 // Verify that the return operands match the results of the function.
189 auto results = fn.getType()->getResults();
190 if (inst.getNumOperands() != results.size())
191 return failure("return has " + Twine(inst.getNumOperands()) +
192 " operands, but enclosing function returns " +
193 Twine(results.size()),
194 inst);
195
Chris Lattner1604e472018-07-23 08:42:19 -0700196 for (unsigned i = 0, e = results.size(); i != e; ++i)
197 if (inst.getOperand(i)->getType() != results[i])
198 return failure("type of return operand " + Twine(i) +
199 " doesn't match result function result type",
200 inst);
201
202 return false;
203}
204
205bool CFGFuncVerifier::verifyBranch(const BranchInst &inst) {
206 // Verify that the number of operands lines up with the number of BB arguments
207 // in the successor.
208 auto dest = inst.getDest();
209 if (inst.getNumOperands() != dest->getNumArguments())
210 return failure("branch has " + Twine(inst.getNumOperands()) +
211 " operands, but target block has " +
212 Twine(dest->getNumArguments()),
213 inst);
214
215 for (unsigned i = 0, e = inst.getNumOperands(); i != e; ++i)
216 if (inst.getOperand(i)->getType() != dest->getArgument(i)->getType())
217 return failure("type of branch operand " + Twine(i) +
218 " doesn't match target bb argument type",
219 inst);
220
Chris Lattner40746442018-07-21 14:32:09 -0700221 return false;
222}
223
James Molloy4f788372018-07-24 15:01:27 -0700224template <typename OperandIteratorTy, typename ArgumentIteratorTy>
225bool CFGFuncVerifier::verifyOperandsMatchArguments(
226 OperandIteratorTy opBegin, OperandIteratorTy opEnd,
227 ArgumentIteratorTy argBegin, const Instruction &instContext) {
228 OperandIteratorTy opIt = opBegin;
229 ArgumentIteratorTy argIt = argBegin;
230 for (; opIt != opEnd; ++opIt, ++argIt) {
231 if ((*opIt)->getType() != (*argIt)->getType())
232 return failure("type of operand " + Twine(std::distance(opBegin, opIt)) +
233 " doesn't match argument type",
234 instContext);
235 }
236 return false;
237}
238
239bool CFGFuncVerifier::verifyCondBranch(const CondBranchInst &inst) {
240 // Verify that the number of operands lines up with the number of BB arguments
241 // in the true successor.
242 auto trueDest = inst.getTrueDest();
243 if (inst.getNumTrueOperands() != trueDest->getNumArguments())
244 return failure("branch has " + Twine(inst.getNumTrueOperands()) +
245 " true operands, but true target block has " +
246 Twine(trueDest->getNumArguments()),
247 inst);
248
249 if (verifyOperandsMatchArguments(inst.true_operand_begin(),
250 inst.true_operand_end(),
251 trueDest->args_begin(), inst))
252 return true;
253
254 // And the false successor.
255 auto falseDest = inst.getFalseDest();
256 if (inst.getNumFalseOperands() != falseDest->getNumArguments())
257 return failure("branch has " + Twine(inst.getNumFalseOperands()) +
258 " false operands, but false target block has " +
259 Twine(falseDest->getNumArguments()),
260 inst);
261
262 if (verifyOperandsMatchArguments(inst.false_operand_begin(),
263 inst.false_operand_end(),
264 falseDest->args_begin(), inst))
265 return true;
266
267 if (inst.getCondition()->getType() != Type::getInteger(1, fn.getContext()))
268 return failure("type of condition is not boolean (i1)", inst);
269
270 return false;
271}
272
Chris Lattner40746442018-07-21 14:32:09 -0700273bool CFGFuncVerifier::verifyOperation(const OperationInst &inst) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700274 if (inst.getFunction() != &fn)
Chris Lattner40746442018-07-21 14:32:09 -0700275 return failure("operation in the wrong function", inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700276
277 // TODO: Check that operands are structurally ok.
278
279 // See if we can get operation info for this.
280 if (auto *opInfo = inst.getAbstractOperation(fn.getContext())) {
281 if (auto errorMessage = opInfo->verifyInvariants(&inst))
Chris Lattner9361fb32018-07-24 08:34:58 -0700282 return failure(Twine("'") + inst.getName().str() + "' op " + errorMessage,
283 inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700284 }
Chris Lattner40746442018-07-21 14:32:09 -0700285
286 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700287}
288
289//===----------------------------------------------------------------------===//
290// ML Functions
291//===----------------------------------------------------------------------===//
292
293namespace {
Chris Lattner40746442018-07-21 14:32:09 -0700294class MLFuncVerifier : public Verifier {
Chris Lattner21e67f62018-07-06 10:46:19 -0700295public:
296 const MLFunction &fn;
297
Chris Lattner40746442018-07-21 14:32:09 -0700298 MLFuncVerifier(const MLFunction &fn, std::string *errorResult)
299 : Verifier(errorResult), fn(fn) {}
Chris Lattner21e67f62018-07-06 10:46:19 -0700300
Chris Lattner40746442018-07-21 14:32:09 -0700301 bool verify() {
Chris Lattner21e67f62018-07-06 10:46:19 -0700302 // TODO.
Chris Lattner40746442018-07-21 14:32:09 -0700303 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700304 }
305};
306} // end anonymous namespace
307
308//===----------------------------------------------------------------------===//
309// Entrypoints
310//===----------------------------------------------------------------------===//
311
312/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700313/// compiler bugs. On error, this fills in the string and return true,
314/// or aborts if the string was not provided.
315bool Function::verify(std::string *errorResult) const {
Chris Lattner21e67f62018-07-06 10:46:19 -0700316 switch (getKind()) {
317 case Kind::ExtFunc:
318 // No body, nothing can be wrong here.
Chris Lattner40746442018-07-21 14:32:09 -0700319 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700320 case Kind::CFGFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700321 return CFGFuncVerifier(*cast<CFGFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700322 case Kind::MLFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700323 return MLFuncVerifier(*cast<MLFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700324 }
325}
326
327/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700328/// compiler bugs. On error, this fills in the string and return true,
329/// or aborts if the string was not provided.
330bool Module::verify(std::string *errorResult) const {
331
Chris Lattner21e67f62018-07-06 10:46:19 -0700332 /// Check that each function is correct.
Chris Lattnera8e47672018-07-25 14:08:16 -0700333 for (auto &fn : *this) {
334 if (fn.verify(errorResult))
Chris Lattner40746442018-07-21 14:32:09 -0700335 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700336 }
Chris Lattner40746442018-07-21 14:32:09 -0700337
338 // Make sure the error string is empty on success.
339 if (errorResult)
340 errorResult->clear();
341 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700342}