blob: 272395cf87fbaa1da20ca4e17886c2241a7a0d52 [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"
Chris Lattnerf7bdf952018-08-05 21:12:29 -070040#include "mlir/IR/Statements.h"
41#include "llvm/ADT/ScopedHashTable.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070042#include "llvm/ADT/Twine.h"
Chris Lattnerf7bdf952018-08-05 21:12:29 -070043#include "llvm/Support/PrettyStackTrace.h"
Chris Lattner21e67f62018-07-06 10:46:19 -070044#include "llvm/Support/raw_ostream.h"
45using namespace mlir;
46
Chris Lattner40746442018-07-21 14:32:09 -070047namespace {
48/// Base class for the verifiers in this file. It is a pervasive truth that
49/// this file treats "true" as an error that needs to be recovered from, and
50/// "false" as success.
51///
52class Verifier {
53public:
54 template <typename T>
55 static void failure(const Twine &message, const T &value, raw_ostream &os) {
56 // Print the error message and flush the stream in case printing the value
57 // causes a crash.
58 os << "MLIR verification failure: " + message + "\n";
59 os.flush();
60 value.print(os);
61 }
62
63 template <typename T>
64 bool failure(const Twine &message, const T &value) {
65 // If the caller isn't trying to collect failure information, just print
66 // the result and abort.
67 if (!errorResult) {
68 failure(message, value, llvm::errs());
69 abort();
70 }
71
72 // Otherwise, emit the error into the string and return true.
73 llvm::raw_string_ostream os(*errorResult);
74 failure(message, value, os);
75 os.flush();
76 return true;
77 }
78
Chris Lattner95865062018-08-01 10:18:59 -070079 bool opFailure(const Twine &message, const Operation &value) {
80 value.emitError(message);
81 return true;
82 }
83
Chris Lattner40746442018-07-21 14:32:09 -070084protected:
85 explicit Verifier(std::string *errorResult) : errorResult(errorResult) {}
86
87private:
88 std::string *errorResult;
89};
90} // end anonymous namespace
Chris Lattner21e67f62018-07-06 10:46:19 -070091
92//===----------------------------------------------------------------------===//
93// CFG Functions
94//===----------------------------------------------------------------------===//
95
96namespace {
Chris Lattner40746442018-07-21 14:32:09 -070097class CFGFuncVerifier : public Verifier {
Chris Lattner21e67f62018-07-06 10:46:19 -070098public:
99 const CFGFunction &fn;
100 OperationSet &operationSet;
101
Chris Lattner40746442018-07-21 14:32:09 -0700102 CFGFuncVerifier(const CFGFunction &fn, std::string *errorResult)
103 : Verifier(errorResult), fn(fn),
104 operationSet(OperationSet::get(fn.getContext())) {}
Chris Lattner21e67f62018-07-06 10:46:19 -0700105
Chris Lattner40746442018-07-21 14:32:09 -0700106 bool verify();
107 bool verifyBlock(const BasicBlock &block);
108 bool verifyOperation(const OperationInst &inst);
109 bool verifyTerminator(const TerminatorInst &term);
110 bool verifyReturn(const ReturnInst &inst);
Chris Lattner1604e472018-07-23 08:42:19 -0700111 bool verifyBranch(const BranchInst &inst);
James Molloy4f788372018-07-24 15:01:27 -0700112 bool verifyCondBranch(const CondBranchInst &inst);
113
114 // Given a list of "operands" and "arguments" that are the same length, verify
115 // that the types of operands pointwise match argument types. The iterator
116 // types must expose the "getType()" function when dereferenced twice; that
117 // is, the iterator's value_type must be equivalent to SSAValue*.
118 template <typename OperandIteratorTy, typename ArgumentIteratorTy>
119 bool verifyOperandsMatchArguments(OperandIteratorTy opBegin,
120 OperandIteratorTy opEnd,
121 ArgumentIteratorTy argBegin,
122 const Instruction &instContext);
Chris Lattner21e67f62018-07-06 10:46:19 -0700123};
124} // end anonymous namespace
125
Chris Lattner40746442018-07-21 14:32:09 -0700126bool CFGFuncVerifier::verify() {
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700127 llvm::PrettyStackTraceFormat fmt("MLIR Verifier: cfgfunc @%s",
128 fn.getName().c_str());
129
Chris Lattner21e67f62018-07-06 10:46:19 -0700130 // TODO: Lots to be done here, including verifying dominance information when
131 // we have uses and defs.
James Molloy61a656c2018-07-22 15:45:24 -0700132 // TODO: Verify the first block has no predecessors.
133
134 if (fn.empty())
135 return failure("cfgfunc must have at least one basic block", fn);
136
137 // Verify that the argument list of the function and the arg list of the first
138 // block line up.
139 auto *firstBB = &fn.front();
140 auto fnInputTypes = fn.getType()->getInputs();
141 if (fnInputTypes.size() != firstBB->getNumArguments())
142 return failure("first block of cfgfunc must have " +
143 Twine(fnInputTypes.size()) +
144 " arguments to match function signature",
145 fn);
146 for (unsigned i = 0, e = firstBB->getNumArguments(); i != e; ++i)
147 if (fnInputTypes[i] != firstBB->getArgument(i)->getType())
148 return failure(
149 "type of argument #" + Twine(i) +
150 " must match corresponding argument in function signature",
151 fn);
Chris Lattner21e67f62018-07-06 10:46:19 -0700152
153 for (auto &block : fn) {
Chris Lattner40746442018-07-21 14:32:09 -0700154 if (verifyBlock(block))
155 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700156 }
Chris Lattner40746442018-07-21 14:32:09 -0700157 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700158}
159
Chris Lattner40746442018-07-21 14:32:09 -0700160bool CFGFuncVerifier::verifyBlock(const BasicBlock &block) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700161 if (!block.getTerminator())
Chris Lattner40746442018-07-21 14:32:09 -0700162 return failure("basic block with no terminator", block);
163
164 if (verifyTerminator(*block.getTerminator()))
165 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700166
James Molloy61a656c2018-07-22 15:45:24 -0700167 for (auto *arg : block.getArguments()) {
168 if (arg->getOwner() != &block)
169 return failure("basic block argument not owned by block", block);
170 }
171
Chris Lattner21e67f62018-07-06 10:46:19 -0700172 for (auto &inst : block) {
Chris Lattner40746442018-07-21 14:32:09 -0700173 if (verifyOperation(inst))
174 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700175 }
Chris Lattner40746442018-07-21 14:32:09 -0700176 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700177}
178
Chris Lattner40746442018-07-21 14:32:09 -0700179bool CFGFuncVerifier::verifyTerminator(const TerminatorInst &term) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700180 if (term.getFunction() != &fn)
Chris Lattner40746442018-07-21 14:32:09 -0700181 return failure("terminator in the wrong function", term);
Chris Lattner21e67f62018-07-06 10:46:19 -0700182
183 // TODO: Check that operands are structurally ok.
184 // TODO: Check that successors are in the right function.
Chris Lattner40746442018-07-21 14:32:09 -0700185
186 if (auto *ret = dyn_cast<ReturnInst>(&term))
187 return verifyReturn(*ret);
188
Chris Lattner1604e472018-07-23 08:42:19 -0700189 if (auto *br = dyn_cast<BranchInst>(&term))
190 return verifyBranch(*br);
191
James Molloy4f788372018-07-24 15:01:27 -0700192 if (auto *br = dyn_cast<CondBranchInst>(&term))
193 return verifyCondBranch(*br);
194
Chris Lattner40746442018-07-21 14:32:09 -0700195 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700196}
197
Chris Lattner40746442018-07-21 14:32:09 -0700198bool CFGFuncVerifier::verifyReturn(const ReturnInst &inst) {
199 // Verify that the return operands match the results of the function.
200 auto results = fn.getType()->getResults();
201 if (inst.getNumOperands() != results.size())
202 return failure("return has " + Twine(inst.getNumOperands()) +
203 " operands, but enclosing function returns " +
204 Twine(results.size()),
205 inst);
206
Chris Lattner1604e472018-07-23 08:42:19 -0700207 for (unsigned i = 0, e = results.size(); i != e; ++i)
208 if (inst.getOperand(i)->getType() != results[i])
209 return failure("type of return operand " + Twine(i) +
Tatiana Shpeismand9b1d862018-08-09 12:28:58 -0700210 " doesn't match function result type",
Chris Lattner1604e472018-07-23 08:42:19 -0700211 inst);
212
213 return false;
214}
215
216bool CFGFuncVerifier::verifyBranch(const BranchInst &inst) {
217 // Verify that the number of operands lines up with the number of BB arguments
218 // in the successor.
219 auto dest = inst.getDest();
220 if (inst.getNumOperands() != dest->getNumArguments())
221 return failure("branch has " + Twine(inst.getNumOperands()) +
222 " operands, but target block has " +
223 Twine(dest->getNumArguments()),
224 inst);
225
226 for (unsigned i = 0, e = inst.getNumOperands(); i != e; ++i)
227 if (inst.getOperand(i)->getType() != dest->getArgument(i)->getType())
228 return failure("type of branch operand " + Twine(i) +
229 " doesn't match target bb argument type",
230 inst);
231
Chris Lattner40746442018-07-21 14:32:09 -0700232 return false;
233}
234
James Molloy4f788372018-07-24 15:01:27 -0700235template <typename OperandIteratorTy, typename ArgumentIteratorTy>
236bool CFGFuncVerifier::verifyOperandsMatchArguments(
237 OperandIteratorTy opBegin, OperandIteratorTy opEnd,
238 ArgumentIteratorTy argBegin, const Instruction &instContext) {
239 OperandIteratorTy opIt = opBegin;
240 ArgumentIteratorTy argIt = argBegin;
241 for (; opIt != opEnd; ++opIt, ++argIt) {
242 if ((*opIt)->getType() != (*argIt)->getType())
243 return failure("type of operand " + Twine(std::distance(opBegin, opIt)) +
244 " doesn't match argument type",
245 instContext);
246 }
247 return false;
248}
249
250bool CFGFuncVerifier::verifyCondBranch(const CondBranchInst &inst) {
251 // Verify that the number of operands lines up with the number of BB arguments
252 // in the true successor.
253 auto trueDest = inst.getTrueDest();
254 if (inst.getNumTrueOperands() != trueDest->getNumArguments())
255 return failure("branch has " + Twine(inst.getNumTrueOperands()) +
256 " true operands, but true target block has " +
257 Twine(trueDest->getNumArguments()),
258 inst);
259
260 if (verifyOperandsMatchArguments(inst.true_operand_begin(),
261 inst.true_operand_end(),
262 trueDest->args_begin(), inst))
263 return true;
264
265 // And the false successor.
266 auto falseDest = inst.getFalseDest();
267 if (inst.getNumFalseOperands() != falseDest->getNumArguments())
268 return failure("branch has " + Twine(inst.getNumFalseOperands()) +
269 " false operands, but false target block has " +
270 Twine(falseDest->getNumArguments()),
271 inst);
272
273 if (verifyOperandsMatchArguments(inst.false_operand_begin(),
274 inst.false_operand_end(),
275 falseDest->args_begin(), inst))
276 return true;
277
278 if (inst.getCondition()->getType() != Type::getInteger(1, fn.getContext()))
279 return failure("type of condition is not boolean (i1)", inst);
280
281 return false;
282}
283
Chris Lattner40746442018-07-21 14:32:09 -0700284bool CFGFuncVerifier::verifyOperation(const OperationInst &inst) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700285 if (inst.getFunction() != &fn)
Chris Lattner95865062018-08-01 10:18:59 -0700286 return opFailure("operation in the wrong function", inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700287
288 // TODO: Check that operands are structurally ok.
289
290 // See if we can get operation info for this.
Chris Lattner95865062018-08-01 10:18:59 -0700291 if (auto *opInfo = inst.getAbstractOperation()) {
Chris Lattner21e67f62018-07-06 10:46:19 -0700292 if (auto errorMessage = opInfo->verifyInvariants(&inst))
Chris Lattner95865062018-08-01 10:18:59 -0700293 return opFailure(
294 Twine("'") + inst.getName().str() + "' op " + errorMessage, inst);
Chris Lattner21e67f62018-07-06 10:46:19 -0700295 }
Chris Lattner40746442018-07-21 14:32:09 -0700296
297 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700298}
299
300//===----------------------------------------------------------------------===//
301// ML Functions
302//===----------------------------------------------------------------------===//
303
304namespace {
Chris Lattner40746442018-07-21 14:32:09 -0700305class MLFuncVerifier : public Verifier {
Chris Lattner21e67f62018-07-06 10:46:19 -0700306public:
307 const MLFunction &fn;
308
Chris Lattner40746442018-07-21 14:32:09 -0700309 MLFuncVerifier(const MLFunction &fn, std::string *errorResult)
310 : Verifier(errorResult), fn(fn) {}
Chris Lattner21e67f62018-07-06 10:46:19 -0700311
Chris Lattner40746442018-07-21 14:32:09 -0700312 bool verify() {
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700313 llvm::PrettyStackTraceFormat fmt("MLIR Verifier: mlfunc @%s",
314 fn.getName().c_str());
315
Tatiana Shpeismand9b1d862018-08-09 12:28:58 -0700316 // TODO: check basic structural properties
317 // TODO: check that operation is not a return statement unless it's
318 // the last one in the function.
319 if (verifyReturn())
320 return true;
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700321
322 return verifyDominance();
Chris Lattner21e67f62018-07-06 10:46:19 -0700323 }
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700324
325 /// Walk all of the code in this MLFunc and verify that the operands of any
326 /// operations are properly dominated by their definitions.
327 bool verifyDominance();
Tatiana Shpeismand9b1d862018-08-09 12:28:58 -0700328
329 /// Verify that function has a return statement that matches its signature.
330 bool verifyReturn();
Chris Lattner21e67f62018-07-06 10:46:19 -0700331};
332} // end anonymous namespace
333
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700334/// Walk all of the code in this MLFunc and verify that the operands of any
335/// operations are properly dominated by their definitions.
336bool MLFuncVerifier::verifyDominance() {
337 using HashTable = llvm::ScopedHashTable<const SSAValue *, bool>;
338 HashTable liveValues;
339 HashTable::ScopeTy topScope(liveValues);
340
341 // All of the arguments to the function are live for the whole function.
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -0700342 for (auto *arg : fn.getArguments())
343 liveValues.insert(arg, true);
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700344
345 // This recursive function walks the statement list pushing scopes onto the
346 // stack as it goes, and popping them to remove them from the table.
347 std::function<bool(const StmtBlock &block)> walkBlock;
348 walkBlock = [&](const StmtBlock &block) -> bool {
349 HashTable::ScopeTy blockScope(liveValues);
350
351 // The induction variable of a for statement is live within its body.
352 if (auto *forStmt = dyn_cast<ForStmt>(&block))
353 liveValues.insert(forStmt, true);
354
355 for (auto &stmt : block) {
356 // TODO: For and If will eventually have operands, we need to check them.
357 // When this happens, Statement should have a general getOperands() method
358 // we can use here first.
359 if (auto *opStmt = dyn_cast<OperationStmt>(&stmt)) {
360 // Verify that each of the operands are live.
361 unsigned operandNo = 0;
362 for (auto *opValue : opStmt->getOperands()) {
363 if (!liveValues.count(opValue)) {
364 opStmt->emitError("operand #" + Twine(operandNo) +
365 " does not dominate this use");
366 if (auto *useStmt = opValue->getDefiningStmt())
367 useStmt->emitNote("operand defined here");
368 return true;
369 }
370 ++operandNo;
371 }
372
373 // Operations define values, add them to the hash table.
374 for (auto *result : opStmt->getResults())
375 liveValues.insert(result, true);
376 continue;
377 }
378
379 // If this is an if or for, recursively walk the block they contain.
380 if (auto *ifStmt = dyn_cast<IfStmt>(&stmt)) {
Chris Lattnere787b322018-08-08 11:14:57 -0700381 if (walkBlock(*ifStmt->getThen()))
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700382 return true;
383
Chris Lattnere787b322018-08-08 11:14:57 -0700384 if (auto *elseClause = ifStmt->getElse())
Chris Lattnerf7bdf952018-08-05 21:12:29 -0700385 if (walkBlock(*elseClause))
386 return true;
387 }
388 if (auto *forStmt = dyn_cast<ForStmt>(&stmt))
389 if (walkBlock(*forStmt))
390 return true;
391 }
392
393 return false;
394 };
395
396 // Check the whole function out.
397 return walkBlock(fn);
398}
399
Tatiana Shpeismand9b1d862018-08-09 12:28:58 -0700400bool MLFuncVerifier::verifyReturn() {
401 // TODO: fold return verification in the pass that verifies all statements.
402 const char missingReturnMsg[] = "ML function must end with return statement";
403 if (fn.getStatements().empty())
404 return failure(missingReturnMsg, fn);
405
406 const auto &stmt = fn.getStatements().back();
407 if (const auto *op = dyn_cast<OperationStmt>(&stmt)) {
408 if (!op->isReturn())
409 return failure(missingReturnMsg, fn);
410
411 // The operand number and types must match the function signature.
412 // TODO: move this verification in ReturnOp::verify() if printing
413 // of the error messages below can be made to work there.
414 const auto &results = fn.getType()->getResults();
415 if (op->getNumOperands() != results.size())
416 return failure("return has " + Twine(op->getNumOperands()) +
417 " operands, but enclosing function returns " +
418 Twine(results.size()),
419 *op);
420
421 for (unsigned i = 0, e = results.size(); i != e; ++i)
422 if (op->getOperand(i)->getType() != results[i])
423 return failure("type of return operand " + Twine(i) +
424 " doesn't match function result type",
425 *op);
426 return false;
427 }
428 return failure(missingReturnMsg, fn);
429}
430
Chris Lattner21e67f62018-07-06 10:46:19 -0700431//===----------------------------------------------------------------------===//
432// Entrypoints
433//===----------------------------------------------------------------------===//
434
435/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700436/// compiler bugs. On error, this fills in the string and return true,
437/// or aborts if the string was not provided.
438bool Function::verify(std::string *errorResult) const {
Chris Lattner21e67f62018-07-06 10:46:19 -0700439 switch (getKind()) {
440 case Kind::ExtFunc:
441 // No body, nothing can be wrong here.
Chris Lattner40746442018-07-21 14:32:09 -0700442 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700443 case Kind::CFGFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700444 return CFGFuncVerifier(*cast<CFGFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700445 case Kind::MLFunc:
Chris Lattner40746442018-07-21 14:32:09 -0700446 return MLFuncVerifier(*cast<MLFunction>(this), errorResult).verify();
Chris Lattner21e67f62018-07-06 10:46:19 -0700447 }
448}
449
450/// Perform (potentially expensive) checks of invariants, used to detect
Chris Lattner40746442018-07-21 14:32:09 -0700451/// compiler bugs. On error, this fills in the string and return true,
452/// or aborts if the string was not provided.
453bool Module::verify(std::string *errorResult) const {
454
Chris Lattner21e67f62018-07-06 10:46:19 -0700455 /// Check that each function is correct.
Chris Lattnera8e47672018-07-25 14:08:16 -0700456 for (auto &fn : *this) {
457 if (fn.verify(errorResult))
Chris Lattner40746442018-07-21 14:32:09 -0700458 return true;
Chris Lattner21e67f62018-07-06 10:46:19 -0700459 }
Chris Lattner40746442018-07-21 14:32:09 -0700460
461 // Make sure the error string is empty on success.
462 if (errorResult)
463 errorResult->clear();
464 return false;
Chris Lattner21e67f62018-07-06 10:46:19 -0700465}