From a4c3a6455c404ef4e56a73be9457affb53536873 Mon Sep 17 00:00:00 2001 From: River Riddle Date: Tue, 25 Jun 2019 21:31:54 -0700 Subject: [PATCH] Move the emitError/Warning/Remark utility methods out of MLIRContext and into the mlir namespace. Now that Locations are attributes, they have direct access to the MLIR context. This allows for simplifying error emission by removing unnecessary context lookups. PiperOrigin-RevId: 255112791 --- .../Linalg/Linalg1/include/linalg1/Common.h | 3 +- mlir/examples/Linalg/Linalg1/lib/Dialect.cpp | 2 +- mlir/examples/toy/Ch2/mlir/MLIRGen.cpp | 23 +++-- mlir/examples/toy/Ch3/mlir/MLIRGen.cpp | 28 +++--- mlir/examples/toy/Ch3/mlir/ToyDialect.cpp | 8 +- mlir/examples/toy/Ch4/mlir/MLIRGen.cpp | 28 +++--- .../toy/Ch4/mlir/ShapeInferencePass.cpp | 14 ++- mlir/examples/toy/Ch4/mlir/ToyDialect.cpp | 8 +- mlir/examples/toy/Ch5/mlir/EarlyLowering.cpp | 3 +- mlir/examples/toy/Ch5/mlir/LateLowering.cpp | 4 +- mlir/examples/toy/Ch5/mlir/MLIRGen.cpp | 28 +++--- .../toy/Ch5/mlir/ShapeInferencePass.cpp | 43 ++++----- mlir/examples/toy/Ch5/mlir/ToyDialect.cpp | 8 +- mlir/g3doc/Diagnostics.md | 7 +- mlir/include/mlir/IR/Diagnostics.h | 12 +++ mlir/include/mlir/IR/MLIRContext.h | 12 --- mlir/lib/Analysis/Verifier.cpp | 6 +- .../Conversion/AffineToGPU/AffineToGPU.cpp | 11 +-- .../StandardToLLVM/ConvertStandardToLLVM.cpp | 10 +-- .../Transforms/LowerUniformRealMath.cpp | 3 +- mlir/lib/Dialect/QuantOps/IR/QuantTypes.cpp | 22 ++--- mlir/lib/Dialect/QuantOps/IR/TypeParser.cpp | 2 +- .../QuantOps/Utils/FakeQuantSupport.cpp | 4 +- mlir/lib/IR/Attributes.cpp | 9 +- mlir/lib/IR/Diagnostics.cpp | 35 ++++++++ mlir/lib/IR/Dialect.cpp | 8 +- mlir/lib/IR/Function.cpp | 6 +- mlir/lib/IR/MLIRContext.cpp | 38 -------- mlir/lib/IR/Operation.cpp | 6 +- mlir/lib/IR/StandardTypes.cpp | 21 +++-- mlir/lib/IR/Types.cpp | 3 +- mlir/lib/LLVMIR/IR/LLVMDialect.cpp | 2 +- mlir/lib/Linalg/IR/LinalgTypes.cpp | 5 +- mlir/lib/Parser/Lexer.cpp | 4 +- mlir/lib/Parser/Parser.cpp | 6 +- .../Quantizer/Support/UniformConstraints.cpp | 14 ++- .../Transforms/InferQuantizedTypesPass.cpp | 5 +- mlir/lib/SPIRV/SPIRVDialect.cpp | 88 +++++++------------ .../SPIRV/Serialization/ConvertFromBinary.cpp | 4 +- mlir/lib/SPIRV/Serialization/Deserializer.cpp | 23 +++-- mlir/lib/Target/LLVMIR/ModuleTranslation.cpp | 19 ++-- mlir/lib/Transforms/DialectConversion.cpp | 7 +- mlir/lib/Transforms/LowerAffine.cpp | 18 ++-- .../lib/Transforms/TestVectorizationUtils.cpp | 2 +- 44 files changed, 262 insertions(+), 350 deletions(-) diff --git a/mlir/examples/Linalg/Linalg1/include/linalg1/Common.h b/mlir/examples/Linalg/Linalg1/include/linalg1/Common.h index a721756e96de..ddd6df9fb895 100644 --- a/mlir/examples/Linalg/Linalg1/include/linalg1/Common.h +++ b/mlir/examples/Linalg/Linalg1/include/linalg1/Common.h @@ -87,8 +87,7 @@ inline void cleanupAndPrintFunction(mlir::Function *f) { bool printToOuts = true; auto check = [f, &printToOuts](mlir::LogicalResult result) { if (failed(result)) { - f->getContext()->emitError(f->getLoc(), - "Verification and cleanup passes failed"); + f->emitError("Verification and cleanup passes failed"); printToOuts = false; } }; diff --git a/mlir/examples/Linalg/Linalg1/lib/Dialect.cpp b/mlir/examples/Linalg/Linalg1/lib/Dialect.cpp index 5152df33da19..49e61c1e647b 100644 --- a/mlir/examples/Linalg/Linalg1/lib/Dialect.cpp +++ b/mlir/examples/Linalg/Linalg1/lib/Dialect.cpp @@ -54,7 +54,7 @@ Type LinalgDialect::parseType(StringRef spec, Location loc) const { if (str.consume_front("f64>")) return ViewType::get(context, FloatType::getF64(context), rank); } - return (context->emitError(loc, "unknown Linalg type: " + spec), nullptr); + return (emitError(loc, "unknown Linalg type: " + spec), nullptr); } /// RangeType prints as just "range". diff --git a/mlir/examples/toy/Ch2/mlir/MLIRGen.cpp b/mlir/examples/toy/Ch2/mlir/MLIRGen.cpp index f4ad20f7384f..842c7a1d0f82 100644 --- a/mlir/examples/toy/Ch2/mlir/MLIRGen.cpp +++ b/mlir/examples/toy/Ch2/mlir/MLIRGen.cpp @@ -82,8 +82,7 @@ public: // this won't do much, but it should at least check some structural // properties. if (failed(theModule->verify())) { - context.emitError(mlir::UnknownLoc::get(&context), - "Module verification error"); + emitError(mlir::UnknownLoc::get(&context), "Module verification error"); return nullptr; } @@ -223,9 +222,8 @@ private: op_name = "toy.mul"; break; default: - context.emitError(loc(binop.loc()), - Twine("Error: invalid binary operator '") + - Twine(binop.getOp()) + "'"); + emitError(loc(binop.loc()), "Error: invalid binary operator '") + << binop.getOp() << "'"; return nullptr; } @@ -244,8 +242,8 @@ private: mlir::Value *mlirGen(VariableExprAST &expr) { if (symbolTable.count(expr.getName())) return symbolTable.lookup(expr.getName()); - context.emitError(loc(expr.loc()), Twine("Error: unknown variable '") + - expr.getName() + "'"); + emitError(loc(expr.loc()), "Error: unknown variable '") + << expr.getName() << "'"; return nullptr; } @@ -404,10 +402,9 @@ private: case toy::ExprAST::Expr_Num: return mlirGen(cast(expr)); default: - context.emitError( - loc(expr.loc()), - Twine("MLIR codegen encountered an unhandled expr kind '") + - Twine(expr.getKind()) + "'"); + emitError(loc(expr.loc())) + << "MLIR codegen encountered an unhandled expr kind '" + << Twine(expr.getKind()) << "'"; return nullptr; } } @@ -433,8 +430,8 @@ private: value = builder->createOperation(result)->getResult(0); } } else { - context.emitError(loc(vardecl.loc()), - "Missing initializer in variable declaration"); + emitError(loc(vardecl.loc()), + "Missing initializer in variable declaration"); return nullptr; } // Register the value in the symbol table diff --git a/mlir/examples/toy/Ch3/mlir/MLIRGen.cpp b/mlir/examples/toy/Ch3/mlir/MLIRGen.cpp index 715f4011c928..e365f37f8c8c 100644 --- a/mlir/examples/toy/Ch3/mlir/MLIRGen.cpp +++ b/mlir/examples/toy/Ch3/mlir/MLIRGen.cpp @@ -83,8 +83,7 @@ public: // this won't do much, but it should at least check some structural // properties. if (failed(theModule->verify())) { - context.emitError(mlir::UnknownLoc::get(&context), - "Module verification error"); + emitError(mlir::UnknownLoc::get(&context), "Module verification error"); return nullptr; } @@ -222,9 +221,8 @@ private: case '*': return builder->create(location, L, R).getResult(); default: - context.emitError(loc(binop.loc()), - Twine("Error: invalid binary operator '") + - Twine(binop.getOp()) + "'"); + emitError(loc(binop.loc()), "Error: invalid binary operator '") + << binop.getOp() << "'"; return nullptr; } } @@ -235,8 +233,8 @@ private: mlir::Value *mlirGen(VariableExprAST &expr) { if (symbolTable.count(expr.getName())) return symbolTable.lookup(expr.getName()); - context.emitError(loc(expr.loc()), Twine("Error: unknown variable '") + - expr.getName() + "'"); + emitError(loc(expr.loc()), "Error: unknown variable '") + << expr.getName() << "'"; return nullptr; } @@ -326,9 +324,8 @@ private: std::string callee = call.getCallee(); if (callee == "transpose") { if (call.getArgs().size() != 1) { - context.emitError( - location, Twine("MLIR codegen encountered an error: toy.transpose " - "does not accept multiple arguments")); + emitError(location, "MLIR codegen encountered an error: toy.transpose " + "does not accept multiple arguments"); return nullptr; } mlir::Value *arg = mlirGen(*call.getArgs()[0]); @@ -384,10 +381,9 @@ private: case toy::ExprAST::Expr_Num: return mlirGen(cast(expr)); default: - context.emitError( - loc(expr.loc()), - Twine("MLIR codegen encountered an unhandled expr kind '") + - Twine(expr.getKind()) + "'"); + emitError(loc(expr.loc())) + << "MLIR codegen encountered an unhandled expr kind '" + << Twine(expr.getKind()) << "'"; return nullptr; } } @@ -414,8 +410,8 @@ private: .getResult(); } } else { - context.emitError(loc(vardecl.loc()), - "Missing initializer in variable declaration"); + emitError(loc(vardecl.loc()), + "Missing initializer in variable declaration"); return nullptr; } // Register the value in the symbol table diff --git a/mlir/examples/toy/Ch3/mlir/ToyDialect.cpp b/mlir/examples/toy/Ch3/mlir/ToyDialect.cpp index 7972d759b098..b682dbc608bc 100644 --- a/mlir/examples/toy/Ch3/mlir/ToyDialect.cpp +++ b/mlir/examples/toy/Ch3/mlir/ToyDialect.cpp @@ -104,8 +104,7 @@ ToyDialect::ToyDialect(mlir::MLIRContext *ctx) : mlir::Dialect("toy", ctx) { mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Sanity check: we only support array or array<...> if (!tyData.startswith("array")) { - getContext()->emitError(loc, "Invalid Toy type '" + tyData + - "', array expected"); + emitError(loc, "Invalid Toy type '" + tyData + "', array expected"); return nullptr; } // Drop the "array" prefix from the type name, we expect either an empty @@ -120,7 +119,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { SmallVector matches; auto shapeRegex = llvm::Regex("^<([0-9]+)(, ([0-9]+))*>$"); if (!shapeRegex.match(tyData, &matches)) { - getContext()->emitError(loc, "Invalid toy array shape '" + tyData + "'"); + emitError(loc, "Invalid toy array shape '" + tyData + "'"); return nullptr; } SmallVector shape; @@ -134,8 +133,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Convert the capture to an integer unsigned long long dim; if (getAsUnsignedInteger(dimStr, /* Radix = */ 10, dim)) { - getContext()->emitError( - loc, "Couldn't parse dimension as integer, matched: " + dimStr); + emitError(loc, "Couldn't parse dimension as integer, matched: " + dimStr); return mlir::Type(); } shape.push_back(dim); diff --git a/mlir/examples/toy/Ch4/mlir/MLIRGen.cpp b/mlir/examples/toy/Ch4/mlir/MLIRGen.cpp index 03049ed02430..032766a547f6 100644 --- a/mlir/examples/toy/Ch4/mlir/MLIRGen.cpp +++ b/mlir/examples/toy/Ch4/mlir/MLIRGen.cpp @@ -83,8 +83,7 @@ public: // this won't do much, but it should at least check some structural // properties. if (failed(theModule->verify())) { - context.emitError(mlir::UnknownLoc::get(&context), - "Module verification error"); + emitError(mlir::UnknownLoc::get(&context), "Module verification error"); return nullptr; } @@ -222,9 +221,8 @@ private: case '*': return builder->create(location, L, R).getResult(); default: - context.emitError(loc(binop.loc()), - Twine("Error: invalid binary operator '") + - Twine(binop.getOp()) + "'"); + emitError(location, "Error: invalid binary operator '") + << binop.getOp() << "'"; return nullptr; } } @@ -235,8 +233,8 @@ private: mlir::Value *mlirGen(VariableExprAST &expr) { if (symbolTable.count(expr.getName())) return symbolTable.lookup(expr.getName()); - context.emitError(loc(expr.loc()), Twine("Error: unknown variable '") + - expr.getName() + "'"); + emitError(loc(expr.loc()), "Error: unknown variable '") + << expr.getName() << "'"; return nullptr; } @@ -326,9 +324,8 @@ private: std::string callee = call.getCallee(); if (callee == "transpose") { if (call.getArgs().size() != 1) { - context.emitError( - location, Twine("MLIR codegen encountered an error: toy.transpose " - "does not accept multiple arguments")); + emitError(location, "MLIR codegen encountered an error: toy.transpose " + "does not accept multiple arguments"); return nullptr; } mlir::Value *arg = mlirGen(*call.getArgs()[0]); @@ -384,10 +381,9 @@ private: case toy::ExprAST::Expr_Num: return mlirGen(cast(expr)); default: - context.emitError( - loc(expr.loc()), - Twine("MLIR codegen encountered an unhandled expr kind '") + - Twine(expr.getKind()) + "'"); + emitError(loc(expr.loc())) + << "MLIR codegen encountered an unhandled expr kind '" + << Twine(expr.getKind()) << "'"; return nullptr; } } @@ -414,8 +410,8 @@ private: .getResult(); } } else { - context.emitError(loc(vardecl.loc()), - "Missing initializer in variable declaration"); + emitError(loc(vardecl.loc()), + "Missing initializer in variable declaration"); return nullptr; } // Register the value in the symbol table diff --git a/mlir/examples/toy/Ch4/mlir/ShapeInferencePass.cpp b/mlir/examples/toy/Ch4/mlir/ShapeInferencePass.cpp index 440e3d8be00f..688c73645a5b 100644 --- a/mlir/examples/toy/Ch4/mlir/ShapeInferencePass.cpp +++ b/mlir/examples/toy/Ch4/mlir/ShapeInferencePass.cpp @@ -122,9 +122,8 @@ public: auto &module = getModule(); auto *main = module.getNamedFunction("main"); if (!main) { - module.getContext()->emitError( - mlir::UnknownLoc::get(module.getContext()), - "Shape inference failed: can't find a main function\n"); + emitError(mlir::UnknownLoc::get(module.getContext()), + "Shape inference failed: can't find a main function\n"); signalPassFailure(); return; } @@ -203,8 +202,8 @@ public: auto *toyDialect = getContext().getRegisteredDialect("toy"); if (!toyDialect) { - getContext().emitError(mlir::UnknownLoc::get(&getContext()), - "Toy dialect is not registered"); + emitError(mlir::UnknownLoc::get(&getContext()), + "Toy dialect is not registered"); signalPassFailure(); return mlir::failure(); } @@ -295,9 +294,8 @@ public: auto calleeName = callOp.getCalleeName(); auto *callee = getModule().getNamedFunction(calleeName); if (!callee) { - f->emitError( - llvm::Twine("Shape inference failed, call to unknown '") + - calleeName + "'"); + f->emitError("Shape inference failed, call to unknown '") + << calleeName << "'"; signalPassFailure(); return mlir::failure(); } diff --git a/mlir/examples/toy/Ch4/mlir/ToyDialect.cpp b/mlir/examples/toy/Ch4/mlir/ToyDialect.cpp index eebc97147725..dfab06de47d6 100644 --- a/mlir/examples/toy/Ch4/mlir/ToyDialect.cpp +++ b/mlir/examples/toy/Ch4/mlir/ToyDialect.cpp @@ -104,8 +104,7 @@ ToyDialect::ToyDialect(mlir::MLIRContext *ctx) : mlir::Dialect("toy", ctx) { mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Sanity check: we only support array or array<...> if (!tyData.startswith("array")) { - getContext()->emitError(loc, "Invalid Toy type '" + tyData + - "', array expected"); + emitError(loc, "Invalid Toy type '" + tyData + "', array expected"); return nullptr; } // Drop the "array" prefix from the type name, we expect either an empty @@ -120,7 +119,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { SmallVector matches; auto shapeRegex = llvm::Regex("^<([0-9]+)(, ([0-9]+))*>$"); if (!shapeRegex.match(tyData, &matches)) { - getContext()->emitError(loc, "Invalid toy array shape '" + tyData + "'"); + emitError(loc, "Invalid toy array shape '" + tyData + "'"); return nullptr; } SmallVector shape; @@ -134,8 +133,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Convert the capture to an integer unsigned long long dim; if (getAsUnsignedInteger(dimStr, /* Radix = */ 10, dim)) { - getContext()->emitError( - loc, "Couldn't parse dimension as integer, matched: " + dimStr); + emitError(loc, "Couldn't parse dimension as integer, matched: " + dimStr); return mlir::Type(); } shape.push_back(dim); diff --git a/mlir/examples/toy/Ch5/mlir/EarlyLowering.cpp b/mlir/examples/toy/Ch5/mlir/EarlyLowering.cpp index e8ce2a4ed52a..5677f3553d5b 100644 --- a/mlir/examples/toy/Ch5/mlir/EarlyLowering.cpp +++ b/mlir/examples/toy/Ch5/mlir/EarlyLowering.cpp @@ -134,8 +134,7 @@ struct EarlyLoweringPass : public FunctionPass { RewriteListBuilder::build(patterns, &getContext()); if (failed(applyConversionPatterns(getFunction(), target, std::move(patterns)))) { - getContext().emitError(mlir::UnknownLoc::get(&getContext()), - "Error lowering Toy\n"); + emitError(mlir::UnknownLoc::get(&getContext()), "Error lowering Toy\n"); signalPassFailure(); } } diff --git a/mlir/examples/toy/Ch5/mlir/LateLowering.cpp b/mlir/examples/toy/Ch5/mlir/LateLowering.cpp index b2160898f520..34a2dc3cef5c 100644 --- a/mlir/examples/toy/Ch5/mlir/LateLowering.cpp +++ b/mlir/examples/toy/Ch5/mlir/LateLowering.cpp @@ -350,8 +350,8 @@ struct LateLoweringPass : public ModulePass { target.addLegalOp(); if (failed(applyConversionPatterns(getModule(), target, typeConverter, std::move(toyPatterns)))) { - getModule().getContext()->emitError( - UnknownLoc::get(getModule().getContext()), "Error lowering Toy\n"); + emitError(UnknownLoc::get(getModule().getContext()), + "Error lowering Toy\n"); signalPassFailure(); } diff --git a/mlir/examples/toy/Ch5/mlir/MLIRGen.cpp b/mlir/examples/toy/Ch5/mlir/MLIRGen.cpp index 03049ed02430..f7e6fad568ea 100644 --- a/mlir/examples/toy/Ch5/mlir/MLIRGen.cpp +++ b/mlir/examples/toy/Ch5/mlir/MLIRGen.cpp @@ -83,8 +83,7 @@ public: // this won't do much, but it should at least check some structural // properties. if (failed(theModule->verify())) { - context.emitError(mlir::UnknownLoc::get(&context), - "Module verification error"); + emitError(mlir::UnknownLoc::get(&context), "Module verification error"); return nullptr; } @@ -222,9 +221,8 @@ private: case '*': return builder->create(location, L, R).getResult(); default: - context.emitError(loc(binop.loc()), - Twine("Error: invalid binary operator '") + - Twine(binop.getOp()) + "'"); + emitError(loc(binop.loc()), "Error: invalid binary operator '") + << binop.getOp() << "'"; return nullptr; } } @@ -235,8 +233,8 @@ private: mlir::Value *mlirGen(VariableExprAST &expr) { if (symbolTable.count(expr.getName())) return symbolTable.lookup(expr.getName()); - context.emitError(loc(expr.loc()), Twine("Error: unknown variable '") + - expr.getName() + "'"); + emitError(loc(expr.loc()), "Error: unknown variable '") + << expr.getName() << "'"; return nullptr; } @@ -326,9 +324,8 @@ private: std::string callee = call.getCallee(); if (callee == "transpose") { if (call.getArgs().size() != 1) { - context.emitError( - location, Twine("MLIR codegen encountered an error: toy.transpose " - "does not accept multiple arguments")); + emitError(location, "MLIR codegen encountered an error: toy.transpose " + "does not accept multiple arguments"); return nullptr; } mlir::Value *arg = mlirGen(*call.getArgs()[0]); @@ -384,10 +381,9 @@ private: case toy::ExprAST::Expr_Num: return mlirGen(cast(expr)); default: - context.emitError( - loc(expr.loc()), - Twine("MLIR codegen encountered an unhandled expr kind '") + - Twine(expr.getKind()) + "'"); + emitError(loc(expr.loc()), + "MLIR codegen encountered an unhandled expr kind '") + << Twine(expr.getKind()) << "'"; return nullptr; } } @@ -414,8 +410,8 @@ private: .getResult(); } } else { - context.emitError(loc(vardecl.loc()), - "Missing initializer in variable declaration"); + emitError(loc(vardecl.loc()), + "Missing initializer in variable declaration"); return nullptr; } // Register the value in the symbol table diff --git a/mlir/examples/toy/Ch5/mlir/ShapeInferencePass.cpp b/mlir/examples/toy/Ch5/mlir/ShapeInferencePass.cpp index 4294f7bbbbff..2552cbedd4c2 100644 --- a/mlir/examples/toy/Ch5/mlir/ShapeInferencePass.cpp +++ b/mlir/examples/toy/Ch5/mlir/ShapeInferencePass.cpp @@ -122,9 +122,8 @@ public: auto &module = getModule(); auto *main = module.getNamedFunction("main"); if (!main) { - module.getContext()->emitError( - mlir::UnknownLoc::get(module.getContext()), - "Shape inference failed: can't find a main function\n"); + emitError(mlir::UnknownLoc::get(module.getContext()), + "Shape inference failed: can't find a main function\n"); signalPassFailure(); return; } @@ -203,10 +202,9 @@ public: auto *toyDialect = getContext().getRegisteredDialect("toy"); if (!toyDialect) { - getContext().emitError(mlir::UnknownLoc::get(&getContext()), - "Toy dialect is not registered"); signalPassFailure(); - return mlir::failure(); + return emitError(mlir::UnknownLoc::get(&getContext()), + "Toy dialect is not registered"); } // Populate the worklist with the operations that need shape inference: @@ -267,10 +265,9 @@ public: auto lhsRank = lhs.getShape().size(); auto rhsRank = rhs.getShape().size(); if (lhsRank != rhsRank) { - op->emitError("Shape mismatch: LHS and RHS must have the same " - "rank for multiplication, got " + - Twine(lhsRank) + " vs " + Twine(lhsRank)); - return mlir::failure(); + return op->emitError("Shape mismatch: LHS and RHS must have the same " + "rank for multiplication, got ") + << lhsRank << " vs " << lhsRank; } SmallVector dims; if (lhsRank == 1) { @@ -278,10 +275,9 @@ public: dims.push_back(1); } else { if (lhsRank != 2) { - op->emitError( - "Shape mismatch: expect rank 1 or 2 for mul operands, got " + - Twine(lhsRank)); - return mlir::failure(); + return op->emitError("Shape mismatch: expect rank 1 or 2 for mul " + "operands, got ") + << lhsRank; } dims.push_back(lhs.getShape()[0]); dims.push_back(rhs.getShape()[1]); @@ -299,11 +295,9 @@ public: auto calleeName = callOp.getCalleeName(); auto *callee = getModule().getNamedFunction(calleeName); if (!callee) { - f->emitError( - llvm::Twine("Shape inference failed, call to unknown '") + - calleeName + "'"); signalPassFailure(); - return mlir::failure(); + return f->emitError("Shape inference failed, call to unknown '") + << calleeName << "'"; } auto mangledName = mangle(calleeName, op->getOpOperands()); LLVM_DEBUG(llvm::dbgs() << "Found callee to infer: '" << calleeName @@ -338,15 +332,12 @@ public: // If the operation worklist isn't empty, this indicates a failure. if (!opWorklist.empty()) { - std::string str; - llvm::raw_string_ostream errorMsg(str); - errorMsg << "Shape inference failed, " << opWorklist.size() - << " operations couldn't be inferred\n"; - for (auto *ope : opWorklist) - errorMsg << " - " << *ope << "\n"; - f->emitError(errorMsg.str()); signalPassFailure(); - return mlir::failure(); + auto diag = f->emitError("Shape inference failed, ") + << opWorklist.size() << " operations couldn't be inferred\n"; + for (auto *ope : opWorklist) + diag << " - " << *ope << "\n"; + return diag; } // Finally, update the return type of the function based on the argument to diff --git a/mlir/examples/toy/Ch5/mlir/ToyDialect.cpp b/mlir/examples/toy/Ch5/mlir/ToyDialect.cpp index be117f56de34..5e06323262ca 100644 --- a/mlir/examples/toy/Ch5/mlir/ToyDialect.cpp +++ b/mlir/examples/toy/Ch5/mlir/ToyDialect.cpp @@ -109,8 +109,7 @@ ToyDialect::ToyDialect(mlir::MLIRContext *ctx) : mlir::Dialect("toy", ctx) { mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Sanity check: we only support array or array<...> if (!tyData.startswith("array")) { - getContext()->emitError(loc, "Invalid Toy type '" + tyData + - "', array expected"); + emitError(loc, "Invalid Toy type '" + tyData + "', array expected"); return nullptr; } // Drop the "array" prefix from the type name, we expect either an empty @@ -125,7 +124,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { SmallVector matches; auto shapeRegex = llvm::Regex("^<([0-9]+)(, ([0-9]+))*>$"); if (!shapeRegex.match(tyData, &matches)) { - getContext()->emitError(loc, "Invalid toy array shape '" + tyData + "'"); + emitError(loc, "Invalid toy array shape '" + tyData + "'"); return nullptr; } SmallVector shape; @@ -139,8 +138,7 @@ mlir::Type ToyDialect::parseType(StringRef tyData, mlir::Location loc) const { // Convert the capture to an integer unsigned long long dim; if (getAsUnsignedInteger(dimStr, /* Radix = */ 10, dim)) { - getContext()->emitError( - loc, "Couldn't parse dimension as integer, matched: " + dimStr); + emitError(loc, "Couldn't parse dimension as integer, matched: " + dimStr); return mlir::Type(); } shape.push_back(dim); diff --git a/mlir/g3doc/Diagnostics.md b/mlir/g3doc/Diagnostics.md index 973555b3ab3a..1d572b0c7c84 100644 --- a/mlir/g3doc/Diagnostics.md +++ b/mlir/g3doc/Diagnostics.md @@ -93,12 +93,13 @@ InFlightDiagnostic emit(Location loc, DiagnosticSeverity severity); ``` Using the `DiagnosticEngine`, though, is generally not the preferred way to emit -diagnostics in MLIR. `MLIRContext`, [`function`](LangRef.md#functions), and -[`operation`](LangRef.md#operations) all provide utility methods for emitting +diagnostics in MLIR. [`function`](LangRef.md#functions), and +[`operation`](LangRef.md#operations) both provide utility methods for emitting diagnostics: ```c++ -InFlightDiagnostic MLIRContext::emitError/Remark/Warning(Location); +// `emit` methods available in the mlir namespace. +InFlightDiagnostic emitError/Remark/Warning(Location); // These methods use the location attached to the function/operation. InFlightDiagnostic Function::emitError/Remark/Warning(); diff --git a/mlir/include/mlir/IR/Diagnostics.h b/mlir/include/mlir/IR/Diagnostics.h index 090e96f9239a..e759c7c3d6f5 100644 --- a/mlir/include/mlir/IR/Diagnostics.h +++ b/mlir/include/mlir/IR/Diagnostics.h @@ -476,6 +476,18 @@ private: MLIRContext *ctx; }; +/// Utility method to emit an error message using this location. +InFlightDiagnostic emitError(Location loc); +InFlightDiagnostic emitError(Location loc, const Twine &message); + +/// Utility method to emit a warning message using this location. +InFlightDiagnostic emitWarning(Location loc); +InFlightDiagnostic emitWarning(Location loc, const Twine &message); + +/// Utility method to emit a remark message using this location. +InFlightDiagnostic emitRemark(Location loc); +InFlightDiagnostic emitRemark(Location loc, const Twine &message); + //===----------------------------------------------------------------------===// // SourceMgrDiagnosticHandler //===----------------------------------------------------------------------===// diff --git a/mlir/include/mlir/IR/MLIRContext.h b/mlir/include/mlir/IR/MLIRContext.h index 48e9e0307005..a93cb8b33538 100644 --- a/mlir/include/mlir/IR/MLIRContext.h +++ b/mlir/include/mlir/IR/MLIRContext.h @@ -67,18 +67,6 @@ public: // MLIRContextImpl type. MLIRContextImpl &getImpl() { return *impl; } - /// Emit an error message using the diagnostic engine. - InFlightDiagnostic emitError(Location location); - InFlightDiagnostic emitError(Location location, const Twine &message); - - /// Emit a warning message using the diagnostic engine. - InFlightDiagnostic emitWarning(Location location); - InFlightDiagnostic emitWarning(Location location, const Twine &message); - - /// Emit a remark message using the diagnostic engine. - InFlightDiagnostic emitRemark(Location location); - InFlightDiagnostic emitRemark(Location location, const Twine &message); - /// Returns the diagnostic engine for this context. DiagnosticEngine &getDiagEngine(); diff --git a/mlir/lib/Analysis/Verifier.cpp b/mlir/lib/Analysis/Verifier.cpp index 9e722e415819..2092dbf486d5 100644 --- a/mlir/lib/Analysis/Verifier.cpp +++ b/mlir/lib/Analysis/Verifier.cpp @@ -85,7 +85,7 @@ private: return bb.front().emitError(message); // Worst case, fall back to using the parent's location. - return ctx->emitError(bb.getParent()->getLoc(), message); + return mlir::emitError(bb.getParent()->getLoc(), message); } /// The current context for the verifier. @@ -149,8 +149,8 @@ LogicalResult OperationVerifier::verifyRegion(Region ®ion) { // Verify the first block has no predecessors. auto *firstBB = ®ion.front(); if (!firstBB->hasNoPredecessors()) - return ctx->emitError(region.getLoc(), - "entry block of region may not have predecessors"); + return mlir::emitError(region.getLoc(), + "entry block of region may not have predecessors"); // Verify each of the blocks within the region. for (auto &block : region) diff --git a/mlir/lib/Conversion/AffineToGPU/AffineToGPU.cpp b/mlir/lib/Conversion/AffineToGPU/AffineToGPU.cpp index cbbd07ccbf85..aebce54e5215 100644 --- a/mlir/lib/Conversion/AffineToGPU/AffineToGPU.cpp +++ b/mlir/lib/Conversion/AffineToGPU/AffineToGPU.cpp @@ -60,16 +60,13 @@ LogicalResult mlir::convertAffineLoopNestToGPULaunch(AffineForOp forOp, } OpBuilder builder(forOp.getOperation()); - if (numBlockDims > 3) { - forOp.getContext()->emitError(builder.getUnknownLoc(), - "cannot map to more than 3 block dimensions"); - return failure(); + return emitError(builder.getUnknownLoc(), + "cannot map to more than 3 block dimensions"); } if (numThreadDims > 3) { - forOp.getContext()->emitError( - builder.getUnknownLoc(), "cannot map to more than 3 thread dimensions"); - return failure(); + return emitError(builder.getUnknownLoc(), + "cannot map to more than 3 thread dimensions"); } // Check the structure of the loop nest: diff --git a/mlir/lib/Conversion/StandardToLLVM/ConvertStandardToLLVM.cpp b/mlir/lib/Conversion/StandardToLLVM/ConvertStandardToLLVM.cpp index 2f9d1d16da8a..872707842d79 100644 --- a/mlir/lib/Conversion/StandardToLLVM/ConvertStandardToLLVM.cpp +++ b/mlir/lib/Conversion/StandardToLLVM/ConvertStandardToLLVM.cpp @@ -58,8 +58,8 @@ LLVM::LLVMType LLVMTypeConverter::unwrap(Type type) { auto *mlirContext = type.getContext(); auto wrappedLLVMType = type.dyn_cast(); if (!wrappedLLVMType) - mlirContext->emitError(UnknownLoc::get(mlirContext), - "conversion resulted in a non-LLVM type"); + emitError(UnknownLoc::get(mlirContext), + "conversion resulted in a non-LLVM type"); return wrappedLLVMType; } @@ -86,8 +86,7 @@ Type LLVMTypeConverter::convertFloatType(FloatType type) { return LLVM::LLVMType::getHalfTy(llvmDialect); case mlir::StandardTypes::BF16: { auto *mlirContext = llvmDialect->getContext(); - return mlirContext->emitError(UnknownLoc::get(mlirContext), - "unsupported type: BF16"), + return emitError(UnknownLoc::get(mlirContext), "unsupported type: BF16"), Type(); } default: @@ -149,8 +148,7 @@ Type LLVMTypeConverter::convertMemRefType(MemRefType type) { Type LLVMTypeConverter::convertVectorType(VectorType type) { if (type.getRank() != 1) { auto *mlirContext = llvmDialect->getContext(); - mlirContext->emitError(UnknownLoc::get(mlirContext), - "only 1D vectors are supported"); + emitError(UnknownLoc::get(mlirContext), "only 1D vectors are supported"); return {}; } diff --git a/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp b/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp index 2a752c2c8658..ff198217bb71 100644 --- a/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp +++ b/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp @@ -52,8 +52,7 @@ static Value *emitUniformPerLayerDequantize(Location loc, Value *input, // Pre-conditions. if (!elementType.isSigned()) { // TODO: Support unsigned storage type. - rewriter.getContext()->emitWarning( - loc, "unimplemented: dequantize signed uniform"); + emitWarning(loc, "unimplemented: dequantize signed uniform"); return nullptr; } diff --git a/mlir/lib/Dialect/QuantOps/IR/QuantTypes.cpp b/mlir/lib/Dialect/QuantOps/IR/QuantTypes.cpp index 1b63b8f4f558..6cc8ab0f52f9 100644 --- a/mlir/lib/Dialect/QuantOps/IR/QuantTypes.cpp +++ b/mlir/lib/Dialect/QuantOps/IR/QuantTypes.cpp @@ -42,7 +42,7 @@ LogicalResult QuantizedType::verifyConstructionInvariants( auto intStorageType = storageType.dyn_cast(); if (!intStorageType) { if (loc) { - context->emitError(*loc, "storage type must be integral"); + emitError(*loc, "storage type must be integral"); } return failure(); } @@ -51,7 +51,7 @@ LogicalResult QuantizedType::verifyConstructionInvariants( // Verify storage width. if (integralWidth == 0 || integralWidth > MaxStorageBits) { if (loc) { - context->emitError(*loc, "illegal storage type size: ") << integralWidth; + emitError(*loc, "illegal storage type size: ") << integralWidth; } return failure(); } @@ -67,7 +67,7 @@ LogicalResult QuantizedType::verifyConstructionInvariants( storageTypeMin < defaultIntegerMin || storageTypeMax > defaultIntegerMax) { if (loc) { - context->emitError(*loc, "illegal storage min and storage max: (") + emitError(*loc, "illegal storage min and storage max: (") << storageTypeMin << ":" << storageTypeMax << ")"; } return failure(); @@ -249,7 +249,7 @@ LogicalResult AnyQuantizedType::verifyConstructionInvariants( // extended. if (expressedType && !expressedType.isa()) { if (loc) { - context->emitError(*loc, "expressed type must be floating point"); + emitError(*loc, "expressed type must be floating point"); } return failure(); } @@ -293,7 +293,7 @@ LogicalResult UniformQuantizedType::verifyConstructionInvariants( // expressed type. if (!expressedType) { if (loc) { - context->emitError(*loc, "uniform quantization requires expressed type"); + emitError(*loc, "uniform quantization requires expressed type"); } return failure(); } @@ -303,7 +303,7 @@ LogicalResult UniformQuantizedType::verifyConstructionInvariants( // extended. if (!expressedType.isa()) { if (loc) { - context->emitError(*loc, "expressed type must be floating point"); + emitError(*loc, "expressed type must be floating point"); } return failure(); } @@ -311,7 +311,7 @@ LogicalResult UniformQuantizedType::verifyConstructionInvariants( // Verify scale. if (scale <= 0.0 || std::isinf(scale) || std::isnan(scale)) { if (loc) { - context->emitError(*loc) << "illegal scale: " << scale; + emitError(*loc) << "illegal scale: " << scale; } return failure(); } @@ -362,7 +362,7 @@ LogicalResult UniformQuantizedPerAxisType::verifyConstructionInvariants( // expressed type. if (!expressedType) { if (loc) { - context->emitError(*loc, "uniform quantization requires expressed type"); + emitError(*loc, "uniform quantization requires expressed type"); } return failure(); } @@ -372,7 +372,7 @@ LogicalResult UniformQuantizedPerAxisType::verifyConstructionInvariants( // extended. if (!expressedType.isa()) { if (loc) { - context->emitError(*loc, "expressed type must be floating point"); + emitError(*loc, "expressed type must be floating point"); } return failure(); } @@ -380,7 +380,7 @@ LogicalResult UniformQuantizedPerAxisType::verifyConstructionInvariants( // Ensure that the number of scales and zeroPoints match. if (scales.size() != zeroPoints.size()) { if (loc) { - context->emitError(*loc, "illegal number of scales and zeroPoints: ") + emitError(*loc, "illegal number of scales and zeroPoints: ") << scales.size() << ", " << zeroPoints.size(); } return failure(); @@ -390,7 +390,7 @@ LogicalResult UniformQuantizedPerAxisType::verifyConstructionInvariants( for (double scale : scales) { if (scale <= 0.0 || std::isinf(scale) || std::isnan(scale)) { if (loc) { - context->emitError(*loc) << "illegal scale: " << scale; + emitError(*loc) << "illegal scale: " << scale; } return failure(); } diff --git a/mlir/lib/Dialect/QuantOps/IR/TypeParser.cpp b/mlir/lib/Dialect/QuantOps/IR/TypeParser.cpp index 1172f82bffaa..b3fbad8bd62c 100644 --- a/mlir/lib/Dialect/QuantOps/IR/TypeParser.cpp +++ b/mlir/lib/Dialect/QuantOps/IR/TypeParser.cpp @@ -258,7 +258,7 @@ private: // TODO: All errors show up at the beginning of the extended type location. // Figure out how to make this location relative to where the error occurred // in this instance. - context->emitError(location, message); + mlir::emitError(location, message); } // Parsers. diff --git a/mlir/lib/Dialect/QuantOps/Utils/FakeQuantSupport.cpp b/mlir/lib/Dialect/QuantOps/Utils/FakeQuantSupport.cpp index 5562e45bb4aa..9ec9151991db 100644 --- a/mlir/lib/Dialect/QuantOps/Utils/FakeQuantSupport.cpp +++ b/mlir/lib/Dialect/QuantOps/Utils/FakeQuantSupport.cpp @@ -44,7 +44,7 @@ UniformQuantizedType mlir::quant::fakeQuantAttrsToType(Location loc, qmin = -32768; qmax = 32767; } else { - ctx->emitError(loc, "unsupported FakeQuant number of bits: ") << numBits; + emitError(loc, "unsupported FakeQuant number of bits: ") << numBits; return nullptr; } @@ -55,7 +55,7 @@ UniformQuantizedType mlir::quant::fakeQuantAttrsToType(Location loc, // Range must straddle zero. if (rmin > 0.0 || rmax < 0.0) { - return (ctx->emitError(loc, "FakeQuant range must straddle zero: [") + return (emitError(loc, "FakeQuant range must straddle zero: [") << rmin << "," << rmax << "]", nullptr); } diff --git a/mlir/lib/IR/Attributes.cpp b/mlir/lib/IR/Attributes.cpp index 8c9141bb871c..c8ebb27ebb04 100644 --- a/mlir/lib/IR/Attributes.cpp +++ b/mlir/lib/IR/Attributes.cpp @@ -216,7 +216,7 @@ static LogicalResult verifyFloatTypeInvariants(llvm::Optional loc, Type type) { if (!type.isa()) { if (loc) - type.getContext()->emitError(*loc, "expected floating point type"); + emitError(*loc, "expected floating point type"); return failure(); } return success(); @@ -238,8 +238,8 @@ FloatAttr::verifyConstructionInvariants(llvm::Optional loc, // Verify that the type semantics match that of the value. if (&type.cast().getFloatSemantics() != &value.getSemantics()) { if (loc) - ctx->emitError( - *loc, "FloatAttr type doesn't match the type implied by its value"); + emitError(*loc, + "FloatAttr type doesn't match the type implied by its value"); return failure(); } return success(); @@ -321,8 +321,7 @@ LogicalResult OpaqueAttr::verifyConstructionInvariants( StringRef attrData) { if (!Dialect::isValidNamespace(dialect.strref())) { if (loc) - context->emitError(*loc) - << "invalid dialect namespace '" << dialect << "'"; + emitError(*loc) << "invalid dialect namespace '" << dialect << "'"; return failure(); } return success(); diff --git a/mlir/lib/IR/Diagnostics.cpp b/mlir/lib/IR/Diagnostics.cpp index 7078aadf99b6..50de2b1f8e32 100644 --- a/mlir/lib/IR/Diagnostics.cpp +++ b/mlir/lib/IR/Diagnostics.cpp @@ -264,6 +264,41 @@ void DiagnosticEngine::emit(Diagnostic diag) { impl->emit(std::move(diag)); } +/// Helper function used to emit a diagnostic with an optionally empty twine +/// message. If the message is empty, then it is not inserted into the +/// diagnostic. +static InFlightDiagnostic emitDiag(Location location, + DiagnosticSeverity severity, + const llvm::Twine &message) { + auto &diagEngine = location->getContext()->getDiagEngine(); + auto diag = diagEngine.emit(location, severity); + if (!message.isTriviallyEmpty()) + diag << message; + return diag; +} + +/// Emit an error message using this location. +InFlightDiagnostic mlir::emitError(Location loc) { return emitError(loc, {}); } +InFlightDiagnostic mlir::emitError(Location loc, const Twine &message) { + return emitDiag(loc, DiagnosticSeverity::Error, message); +} + +/// Emit a warning message using this location. +InFlightDiagnostic mlir::emitWarning(Location loc) { + return emitWarning(loc, {}); +} +InFlightDiagnostic mlir::emitWarning(Location loc, const Twine &message) { + return emitDiag(loc, DiagnosticSeverity::Warning, message); +} + +/// Emit a remark message using this location. +InFlightDiagnostic mlir::emitRemark(Location loc) { + return emitRemark(loc, {}); +} +InFlightDiagnostic mlir::emitRemark(Location loc, const Twine &message) { + return emitDiag(loc, DiagnosticSeverity::Remark, message); +} + //===----------------------------------------------------------------------===// // ScopedDiagnosticHandler //===----------------------------------------------------------------------===// diff --git a/mlir/lib/IR/Dialect.cpp b/mlir/lib/IR/Dialect.cpp index 67ce984aa0ca..4547452eb55e 100644 --- a/mlir/lib/IR/Dialect.cpp +++ b/mlir/lib/IR/Dialect.cpp @@ -70,15 +70,15 @@ Dialect::~Dialect() {} /// Parse an attribute registered to this dialect. Attribute Dialect::parseAttribute(StringRef attrData, Location loc) const { - getContext()->emitError(loc) << "dialect '" << getNamespace() - << "' provides no attribute parsing hook"; + emitError(loc) << "dialect '" << getNamespace() + << "' provides no attribute parsing hook"; return Attribute(); } /// Parse a type registered to this dialect. Type Dialect::parseType(StringRef tyData, Location loc) const { - getContext()->emitError(loc) - << "dialect '" << getNamespace() << "' provides no type parsing hook"; + emitError(loc) << "dialect '" << getNamespace() + << "' provides no type parsing hook"; return Type(); } diff --git a/mlir/lib/IR/Function.cpp b/mlir/lib/IR/Function.cpp index 4e0579538ea1..424548ac3a05 100644 --- a/mlir/lib/IR/Function.cpp +++ b/mlir/lib/IR/Function.cpp @@ -99,21 +99,21 @@ void Function::erase() { /// use when the IR is in an inconsistent state. InFlightDiagnostic Function::emitError() { return emitError({}); } InFlightDiagnostic Function::emitError(const Twine &message) { - return getContext()->emitError(getLoc(), message); + return mlir::emitError(getLoc(), message); } /// Emit a warning about this function, reporting up to any diagnostic /// handlers that may be listening. InFlightDiagnostic Function::emitWarning() { return emitWarning({}); } InFlightDiagnostic Function::emitWarning(const Twine &message) { - return getContext()->emitWarning(getLoc(), message); + return mlir::emitWarning(getLoc(), message); } /// Emit a remark about this function, reporting up to any diagnostic /// handlers that may be listening. InFlightDiagnostic Function::emitRemark() { return emitRemark({}); } InFlightDiagnostic Function::emitRemark(const Twine &message) { - return getContext()->emitRemark(getLoc(), message); + return mlir::emitRemark(getLoc(), message); } /// Clone the internal blocks from this function into dest and all attributes diff --git a/mlir/lib/IR/MLIRContext.cpp b/mlir/lib/IR/MLIRContext.cpp index 63206c3044b5..5e7f5b87d82b 100644 --- a/mlir/lib/IR/MLIRContext.cpp +++ b/mlir/lib/IR/MLIRContext.cpp @@ -297,44 +297,6 @@ static ArrayRef copyArrayRefInto(llvm::BumpPtrAllocator &allocator, // Diagnostic Handlers //===----------------------------------------------------------------------===// -/// Helper function used to emit a diagnostic with an optionally empty twine -/// message. If the message is empty, then it is not inserted into the -/// diagnostic. -static InFlightDiagnostic emitDiag(MLIRContextImpl &ctx, Location location, - DiagnosticSeverity severity, - const llvm::Twine &message) { - auto diag = ctx.diagEngine.emit(location, severity); - if (!message.isTriviallyEmpty()) - diag << message; - return diag; -} - -InFlightDiagnostic MLIRContext::emitError(Location location) { - return emitError(location, /*message=*/{}); -} -InFlightDiagnostic MLIRContext::emitError(Location location, - const llvm::Twine &message) { - return emitDiag(getImpl(), location, DiagnosticSeverity::Error, message); -} - -/// Emit a warning message using the diagnostic engine. -InFlightDiagnostic MLIRContext::emitWarning(Location location) { - return emitWarning(location, /*message=*/{}); -} -InFlightDiagnostic MLIRContext::emitWarning(Location location, - const Twine &message) { - return emitDiag(getImpl(), location, DiagnosticSeverity::Warning, message); -} - -/// Emit a remark message using the diagnostic engine. -InFlightDiagnostic MLIRContext::emitRemark(Location location) { - return emitRemark(location, /*message=*/{}); -} -InFlightDiagnostic MLIRContext::emitRemark(Location location, - const Twine &message) { - return emitDiag(getImpl(), location, DiagnosticSeverity::Remark, message); -} - /// Returns the diagnostic engine for this context. DiagnosticEngine &MLIRContext::getDiagEngine() { return getImpl().diagEngine; } diff --git a/mlir/lib/IR/Operation.cpp b/mlir/lib/IR/Operation.cpp index 3d16e9867d59..d26ddeb7398f 100644 --- a/mlir/lib/IR/Operation.cpp +++ b/mlir/lib/IR/Operation.cpp @@ -314,19 +314,19 @@ void Operation::walk(const std::function &callback) { /// Emit an error about fatal conditions with this operation, reporting up to /// any diagnostic handlers that may be listening. InFlightDiagnostic Operation::emitError(const Twine &message) { - return getContext()->emitError(getLoc(), message); + return mlir::emitError(getLoc(), message); } /// Emit a warning about this operation, reporting up to any diagnostic /// handlers that may be listening. InFlightDiagnostic Operation::emitWarning(const Twine &message) { - return getContext()->emitWarning(getLoc(), message); + return mlir::emitWarning(getLoc(), message); } /// Emit a remark about this operation, reporting up to any diagnostic /// handlers that may be listening. InFlightDiagnostic Operation::emitRemark(const Twine &message) { - return getContext()->emitRemark(getLoc(), message); + return mlir::emitRemark(getLoc(), message); } /// Given an operation 'other' that is within the same parent block, return diff --git a/mlir/lib/IR/StandardTypes.cpp b/mlir/lib/IR/StandardTypes.cpp index 703c50b25fdd..6077e4d9dd72 100644 --- a/mlir/lib/IR/StandardTypes.cpp +++ b/mlir/lib/IR/StandardTypes.cpp @@ -39,8 +39,8 @@ LogicalResult IntegerType::verifyConstructionInvariants( llvm::Optional loc, MLIRContext *context, unsigned width) { if (width > IntegerType::kMaxWidth) { if (loc) - context->emitError(*loc) << "integer bitwidth is limited to " - << IntegerType::kMaxWidth << " bits"; + emitError(*loc) << "integer bitwidth is limited to " + << IntegerType::kMaxWidth << " bits"; return failure(); } return success(); @@ -184,20 +184,19 @@ LogicalResult VectorType::verifyConstructionInvariants( Type elementType) { if (shape.empty()) { if (loc) - context->emitError(*loc, "vector types must have at least one dimension"); + emitError(*loc, "vector types must have at least one dimension"); return failure(); } if (!isValidElementType(elementType)) { if (loc) - context->emitError(*loc, "vector elements must be int or float type"); + emitError(*loc, "vector elements must be int or float type"); return failure(); } if (any_of(shape, [](int64_t i) { return i <= 0; })) { if (loc) - context->emitError(*loc, - "vector types must have positive constant sizes"); + emitError(*loc, "vector types must have positive constant sizes"); return failure(); } return success(); @@ -216,7 +215,7 @@ static inline LogicalResult checkTensorElementType(Optional location, Type elementType) { if (!TensorType::isValidElementType(elementType)) { if (location) - context->emitError(*location, "invalid tensor element type"); + emitError(*location, "invalid tensor element type"); return failure(); } return success(); @@ -245,7 +244,7 @@ LogicalResult RankedTensorType::verifyConstructionInvariants( for (int64_t s : shape) { if (s < -1) { if (loc) - context->emitError(*loc, "invalid tensor dimension size"); + emitError(*loc, "invalid tensor dimension size"); return failure(); } } @@ -320,7 +319,7 @@ MemRefType MemRefType::getImpl(ArrayRef shape, Type elementType, // Negative sizes are not allowed except for `-1` that means dynamic size. if (s < -1) { if (location) - context->emitError(*location, "invalid memref size"); + emitError(*location, "invalid memref size"); return {}; } } @@ -333,7 +332,7 @@ MemRefType MemRefType::getImpl(ArrayRef shape, Type elementType, for (const auto &affineMap : affineMapComposition) { if (affineMap.getNumDims() != dim) { if (location) - context->emitError(*location) + emitError(*location) << "memref affine map dimension mismatch between " << (i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) << " and affine map" << i + 1 << ": " << dim @@ -386,7 +385,7 @@ LogicalResult ComplexType::verifyConstructionInvariants( llvm::Optional loc, MLIRContext *context, Type elementType) { if (!elementType.isa() && !elementType.isa()) { if (loc) - context->emitError(*loc, "invalid element type for complex"); + emitError(*loc, "invalid element type for complex"); return failure(); } return success(); diff --git a/mlir/lib/IR/Types.cpp b/mlir/lib/IR/Types.cpp index b60e81d4949b..78bfc477f554 100644 --- a/mlir/lib/IR/Types.cpp +++ b/mlir/lib/IR/Types.cpp @@ -77,8 +77,7 @@ LogicalResult OpaqueType::verifyConstructionInvariants( StringRef typeData) { if (!Dialect::isValidNamespace(dialect.strref())) { if (loc) - context->emitError(*loc) - << "invalid dialect namespace '" << dialect << "'"; + emitError(*loc) << "invalid dialect namespace '" << dialect << "'"; return failure(); } return success(); diff --git a/mlir/lib/LLVMIR/IR/LLVMDialect.cpp b/mlir/lib/LLVMIR/IR/LLVMDialect.cpp index 513af8f4222b..cee9fe4dbae4 100644 --- a/mlir/lib/LLVMIR/IR/LLVMDialect.cpp +++ b/mlir/lib/LLVMIR/IR/LLVMDialect.cpp @@ -815,7 +815,7 @@ Type LLVMDialect::parseType(StringRef tyData, Location loc) const { llvm::SMDiagnostic errorMessage; llvm::Type *type = llvm::parseType(tyData, errorMessage, impl->module); if (!type) - return (getContext()->emitError(loc, errorMessage.getMessage()), nullptr); + return (emitError(loc, errorMessage.getMessage()), nullptr); return LLVMType::get(getContext(), type); } diff --git a/mlir/lib/Linalg/IR/LinalgTypes.cpp b/mlir/lib/Linalg/IR/LinalgTypes.cpp index 8496cfda0140..6b2e541422fb 100644 --- a/mlir/lib/Linalg/IR/LinalgTypes.cpp +++ b/mlir/lib/Linalg/IR/LinalgTypes.cpp @@ -108,8 +108,7 @@ Type mlir::linalg::LinalgDialect::parseType(StringRef spec, if (spec.consume_front("?")) { ++rank; if (!spec.consume_front("x")) { - context->emitError(loc, - "expected a list of '?x' dimension specifiers: ") + emitError(loc, "expected a list of '?x' dimension specifiers: ") << spec; return Type(); } @@ -119,7 +118,7 @@ Type mlir::linalg::LinalgDialect::parseType(StringRef spec, return ViewType::get(context, t, rank); } } - return (context->emitError(loc, "unknown Linalg type: " + origSpec), Type()); + return (emitError(loc, "unknown Linalg type: " + origSpec), Type()); } struct mlir::linalg::ViewTypeStorage : public TypeStorage { diff --git a/mlir/lib/Parser/Lexer.cpp b/mlir/lib/Parser/Lexer.cpp index 150146638677..d1b8bb3e9816 100644 --- a/mlir/lib/Parser/Lexer.cpp +++ b/mlir/lib/Parser/Lexer.cpp @@ -57,8 +57,8 @@ Location Lexer::getEncodedSourceLocation(llvm::SMLoc loc) { /// emitError - Emit an error message and return an Token::error token. Token Lexer::emitError(const char *loc, const Twine &message) { - context->emitError(getEncodedSourceLocation(SMLoc::getFromPointer(loc)), - message); + mlir::emitError(getEncodedSourceLocation(SMLoc::getFromPointer(loc)), + message); return formToken(Token::error, loc); } diff --git a/mlir/lib/Parser/Parser.cpp b/mlir/lib/Parser/Parser.cpp index ed7b5cc618cd..1fd191f6d755 100644 --- a/mlir/lib/Parser/Parser.cpp +++ b/mlir/lib/Parser/Parser.cpp @@ -472,7 +472,7 @@ static Symbol parseExtendedSymbol(Parser &p, Token::Kind identifierTok, //===----------------------------------------------------------------------===// InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) { - auto diag = getContext()->emitError(getEncodedSourceLocation(loc), message); + auto diag = mlir::emitError(getEncodedSourceLocation(loc), message); // If we hit a parse error in response to a lexer error, then the lexer // already reported the error. @@ -4152,8 +4152,8 @@ Module *mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr, Module *mlir::parseSourceFile(StringRef filename, MLIRContext *context) { auto file_or_err = llvm::MemoryBuffer::getFile(filename); if (std::error_code error = file_or_err.getError()) { - context->emitError(mlir::UnknownLoc::get(context), - "Could not open input file " + filename); + emitError(mlir::UnknownLoc::get(context), + "Could not open input file " + filename); return nullptr; } diff --git a/mlir/lib/Quantizer/Support/UniformConstraints.cpp b/mlir/lib/Quantizer/Support/UniformConstraints.cpp index 2ea081a7e7a3..c43ecdfb5c26 100644 --- a/mlir/lib/Quantizer/Support/UniformConstraints.cpp +++ b/mlir/lib/Quantizer/Support/UniformConstraints.cpp @@ -48,8 +48,7 @@ static QuantizedType solveUniformType(SolverContext &solverContext, Type originalElementType, Location loc) { switch (ct.scheme) { default: - solverContext.getMlirContext().emitError( - loc, "unsupported scheme for uniform type conversion"); + emitError(loc, "unsupported scheme for uniform type conversion"); return nullptr; case CandidateQuantizedType::Scheme::UniformPerLayer: { @@ -66,9 +65,8 @@ static QuantizedType solveUniformType(SolverContext &solverContext, params, clusteredFacts.requiredRange.getValue().first, clusteredFacts.requiredRange.getValue().second); if (!solver.compute()) { - solverContext.getMlirContext().emitWarning(loc) - << "unable to solve uniform type with " - << "UniformParamsFromMinMaxSolver"; + emitWarning(loc) << "unable to solve uniform type with " + << "UniformParamsFromMinMaxSolver"; return nullptr; } @@ -80,7 +78,7 @@ static QuantizedType solveUniformType(SolverContext &solverContext, } case CandidateQuantizedType::Scheme::UniformExplicitFixedPointScale: { if (!clusteredFacts.explicitScaleZeroPoint.hasValue()) { - solverContext.getMlirContext().emitRemark(loc) + emitRemark(loc) << "unable to solve uniform type with UniformExplicitFixedPointScale " << "(no explicitScaleZeroPoint)"; return nullptr; @@ -90,7 +88,7 @@ static QuantizedType solveUniformType(SolverContext &solverContext, assert(scaleZp.value && "optional value not set on fact"); if (scaleZp.conflict) { - solverContext.getMlirContext().emitWarning(loc) + emitWarning(loc) << "conflicting explicit scale/zeroPoint on node cluster: " << "an arbitrary scale/zeroPoint will be used"; } @@ -216,7 +214,7 @@ private: } if (!bestCandidateType || !originalElementType) { - solverContext.getMlirContext().emitRemark(fusedLoc) + emitRemark(fusedLoc) << "not solving uniform type (no viable candidate type)"; return; } diff --git a/mlir/lib/Quantizer/Transforms/InferQuantizedTypesPass.cpp b/mlir/lib/Quantizer/Transforms/InferQuantizedTypesPass.cpp index c443354714f5..dec4ea90db8e 100644 --- a/mlir/lib/Quantizer/Transforms/InferQuantizedTypesPass.cpp +++ b/mlir/lib/Quantizer/Transforms/InferQuantizedTypesPass.cpp @@ -142,9 +142,8 @@ void InferQuantizedTypesPass::runWithConfig(SolverContext &solverContext, break; } if (propRound == 0) { - getContext().emitError( - UnknownLoc::get(&getContext()), - "exceeded maximum number of solver iterations (infinite loop?)"); + emitError(UnknownLoc::get(&getContext()), + "exceeded maximum number of solver iterations (infinite loop?)"); return; } diff --git a/mlir/lib/SPIRV/SPIRVDialect.cpp b/mlir/lib/SPIRV/SPIRVDialect.cpp index f2885d4ce7ac..46ea02149b46 100644 --- a/mlir/lib/SPIRV/SPIRVDialect.cpp +++ b/mlir/lib/SPIRV/SPIRVDialect.cpp @@ -82,7 +82,7 @@ static Type parseAndVerifyTypeImpl(SPIRVDialect const &dialect, Location loc, auto *context = dialect.getContext(); auto type = mlir::parseType(spec, context); if (!type) { - context->emitError(loc, "cannot parse type: ") << spec; + emitError(loc, "cannot parse type: ") << spec; return Type(); } @@ -93,25 +93,23 @@ static Type parseAndVerifyTypeImpl(SPIRVDialect const &dialect, Location loc, // Check other allowed types if (auto t = type.dyn_cast()) { if (type.isBF16()) { - context->emitError(loc, "cannot use 'bf16' to compose SPIR-V types"); + emitError(loc, "cannot use 'bf16' to compose SPIR-V types"); return Type(); } } else if (auto t = type.dyn_cast()) { if (!llvm::is_contained(llvm::ArrayRef({8, 16, 32, 64}), t.getWidth())) { - context->emitError(loc, - "only 8/16/32/64-bit integer type allowed but found ") + emitError(loc, "only 8/16/32/64-bit integer type allowed but found ") << type; return Type(); } } else if (auto t = type.dyn_cast()) { if (t.getRank() != 1) { - context->emitError(loc, "only 1-D vector allowed but found ") << t; + emitError(loc, "only 1-D vector allowed but found ") << t; return Type(); } } else { - context->emitError(loc, "cannot use ") - << type << " to compose SPIR-V types"; + emitError(loc, "cannot use ") << type << " to compose SPIR-V types"; return Type(); } @@ -129,23 +127,21 @@ Type SPIRVDialect::parseAndVerifyType(StringRef spec, Location loc) const { // // array-type ::= `!spv.array<` integer-literal `x` element-type `>` Type SPIRVDialect::parseArrayType(StringRef spec, Location loc) const { - auto *context = getContext(); if (!spec.consume_front("array<") || !spec.consume_back(">")) { - context->emitError(loc, "spv.array delimiter <...> mismatch"); + emitError(loc, "spv.array delimiter <...> mismatch"); return Type(); } int64_t count = 0; spec = spec.trim(); if (!parseNumberX(spec, count)) { - context->emitError( - loc, "expected array element count followed by 'x' but found '") + emitError(loc, "expected array element count followed by 'x' but found '") << spec << "'"; return Type(); } if (spec.trim().empty()) { - context->emitError(loc, "expected element type"); + emitError(loc, "expected element type"); return Type(); } @@ -163,9 +159,8 @@ Type SPIRVDialect::parseArrayType(StringRef spec, Location loc) const { // // pointer-type ::= `!spv.ptr<` element-type `,` storage-class `>` Type SPIRVDialect::parsePointerType(StringRef spec, Location loc) const { - auto *context = getContext(); if (!spec.consume_front("ptr<") || !spec.consume_back(">")) { - context->emitError(loc, "spv.ptr delimiter <...> mismatch"); + emitError(loc, "spv.ptr delimiter <...> mismatch"); return Type(); } @@ -173,8 +168,8 @@ Type SPIRVDialect::parsePointerType(StringRef spec, Location loc) const { StringRef scSpec, ptSpec; std::tie(ptSpec, scSpec) = spec.rsplit(','); if (scSpec.empty()) { - context->emitError( - loc, "expected comma to separate pointee type and storage class in '") + emitError(loc, + "expected comma to separate pointee type and storage class in '") << spec << "'"; return Type(); } @@ -182,12 +177,12 @@ Type SPIRVDialect::parsePointerType(StringRef spec, Location loc) const { scSpec = scSpec.trim(); auto storageClass = symbolizeStorageClass(scSpec); if (!storageClass) { - context->emitError(loc, "unknown storage class: ") << scSpec; + emitError(loc, "unknown storage class: ") << scSpec; return Type(); } if (ptSpec.trim().empty()) { - context->emitError(loc, "expected pointee type"); + emitError(loc, "expected pointee type"); return Type(); } @@ -200,14 +195,13 @@ Type SPIRVDialect::parsePointerType(StringRef spec, Location loc) const { // runtime-array-type ::= `!spv.rtarray<` element-type `>` Type SPIRVDialect::parseRuntimeArrayType(StringRef spec, Location loc) const { - auto *context = getContext(); if (!spec.consume_front("rtarray<") || !spec.consume_back(">")) { - context->emitError(loc, "spv.rtarray delimiter <...> mismatch"); + emitError(loc, "spv.rtarray delimiter <...> mismatch"); return Type(); } if (spec.trim().empty()) { - context->emitError(loc, "expected element type"); + emitError(loc, "expected element type"); return Type(); } @@ -223,9 +217,7 @@ Type SPIRVDialect::parseRuntimeArrayType(StringRef spec, Location loc) const { template Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { - auto *context = dialect.getContext(); - context->emitError(loc, "unexpected parameter while parsing '") - << spec << "'"; + emitError(loc, "unexpected parameter while parsing '") << spec << "'"; return llvm::None; } @@ -240,10 +232,8 @@ template <> Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto dim = symbolizeDim(spec); - if (!dim) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown Dim in Image type: '") << spec << "'"; - } + if (!dim) + emitError(loc, "unknown Dim in Image type: '") << spec << "'"; return dim; } @@ -252,11 +242,8 @@ Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto depth = symbolizeImageDepthInfo(spec); - if (!depth) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown ImageDepthInfo in Image type: '") - << spec << "'"; - } + if (!depth) + emitError(loc, "unknown ImageDepthInfo in Image type: '") << spec << "'"; return depth; } @@ -265,11 +252,8 @@ Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto arrayedInfo = symbolizeImageArrayedInfo(spec); - if (!arrayedInfo) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown ImageArrayedInfo in Image type: '") - << spec << "'"; - } + if (!arrayedInfo) + emitError(loc, "unknown ImageArrayedInfo in Image type: '") << spec << "'"; return arrayedInfo; } @@ -278,11 +262,8 @@ Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto samplingInfo = symbolizeImageSamplingInfo(spec); - if (!samplingInfo) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown ImageSamplingInfo in Image type: '") - << spec << "'"; - } + if (!samplingInfo) + emitError(loc, "unknown ImageSamplingInfo in Image type: '") << spec << "'"; return samplingInfo; } @@ -291,11 +272,9 @@ Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto samplerUseInfo = symbolizeImageSamplerUseInfo(spec); - if (!samplerUseInfo) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown ImageSamplerUseInfo in Image type: '") + if (!samplerUseInfo) + emitError(loc, "unknown ImageSamplerUseInfo in Image type: '") << spec << "'"; - } return samplerUseInfo; } @@ -304,11 +283,8 @@ Optional parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) { auto format = symbolizeImageFormat(spec); - if (!format) { - auto *context = dialect.getContext(); - context->emitError(loc, "unknown ImageFormat in Image type: '") - << spec << "'"; - } + if (!format) + emitError(loc, "unknown ImageFormat in Image type: '") << spec << "'"; return format; } @@ -321,12 +297,11 @@ template struct parseCommaSeparatedList { operator()(SPIRVDialect const &dialect, Location loc, StringRef spec) const { auto numArgs = std::tuple_size>::value; StringRef parseSpec, restSpec; - auto *context = dialect.getContext(); std::tie(parseSpec, restSpec) = spec.split(','); parseSpec = parseSpec.trim(); if (numArgs != 0 && restSpec.empty()) { - context->emitError(loc, "expected more parameters for image type '") + emitError(loc, "expected more parameters for image type '") << parseSpec << "'"; return llvm::None; } @@ -376,9 +351,8 @@ template struct parseCommaSeparatedList { // arrayed-info `,` sampling-info `,` // sampler-use-info `,` format `>` Type SPIRVDialect::parseImageType(StringRef spec, Location loc) const { - auto *context = getContext(); if (!spec.consume_front("image<") || !spec.consume_back(">")) { - context->emitError(loc, "spv.image delimiter <...> mismatch"); + emitError(loc, "spv.image delimiter <...> mismatch"); return Type(); } @@ -403,7 +377,7 @@ Type SPIRVDialect::parseType(StringRef spec, Location loc) const { if (spec.startswith("rtarray")) return parseRuntimeArrayType(spec, loc); - getContext()->emitError(loc, "unknown SPIR-V type: ") << spec; + emitError(loc, "unknown SPIR-V type: ") << spec; return Type(); } diff --git a/mlir/lib/SPIRV/Serialization/ConvertFromBinary.cpp b/mlir/lib/SPIRV/Serialization/ConvertFromBinary.cpp index 95908b0dfe84..3add211fdd56 100644 --- a/mlir/lib/SPIRV/Serialization/ConvertFromBinary.cpp +++ b/mlir/lib/SPIRV/Serialization/ConvertFromBinary.cpp @@ -58,7 +58,7 @@ std::unique_ptr deserializeModule(llvm::StringRef inputFilename, std::string errorMessage; auto file = openInputFile(inputFilename, &errorMessage); if (!file) { - context->emitError(builder.getUnknownLoc()) << errorMessage; + emitError(UnknownLoc::get(context), errorMessage); return {}; } @@ -66,7 +66,7 @@ std::unique_ptr deserializeModule(llvm::StringRef inputFilename, auto start = file->getBufferStart(); auto end = file->getBufferEnd(); if ((start - end) % sizeof(uint32_t) != 0) { - context->emitError(builder.getUnknownLoc()) + emitError(UnknownLoc::get(context)) << "SPIR-V binary module must contain integral number of 32-bit words"; return {}; } diff --git a/mlir/lib/SPIRV/Serialization/Deserializer.cpp b/mlir/lib/SPIRV/Serialization/Deserializer.cpp index f55805dfd23a..e8ad6fd9e671 100644 --- a/mlir/lib/SPIRV/Serialization/Deserializer.cpp +++ b/mlir/lib/SPIRV/Serialization/Deserializer.cpp @@ -106,12 +106,12 @@ LogicalResult Deserializer::deserialize() { uint32_t opcode = binary[curOffset] & 0xffff; if (wordCount == 0) - return context->emitError(unknownLoc, "word count cannot be zero"); + return emitError(unknownLoc, "word count cannot be zero"); uint32_t nextOffset = curOffset + wordCount; if (nextOffset > binarySize) - return context->emitError(unknownLoc, - "insufficient words for the last instruction"); + return emitError(unknownLoc, + "insufficient words for the last instruction"); auto operands = binary.slice(curOffset + 1, wordCount - 1); if (failed(processInstruction(opcode, operands))) @@ -127,11 +127,11 @@ Optional Deserializer::collect() { return module; } LogicalResult Deserializer::processHeader() { if (binary.size() < spirv::kHeaderWordCount) - return context->emitError(unknownLoc, - "SPIR-V binary module must have a 5-word header"); + return emitError(unknownLoc, + "SPIR-V binary module must have a 5-word header"); if (binary[0] != spirv::kMagicNumber) - return context->emitError(unknownLoc, "incorrect magic number"); + return emitError(unknownLoc, "incorrect magic number"); // TODO(antiagainst): generator number, bound, schema return success(); @@ -145,26 +145,23 @@ LogicalResult Deserializer::processInstruction(uint32_t opcode, default: break; } - return context->emitError(unknownLoc, "NYI: opcode ") << opcode; + return emitError(unknownLoc, "NYI: opcode ") << opcode; } LogicalResult Deserializer::processMemoryModel(ArrayRef operands) { if (operands.size() != 2) - return context->emitError(unknownLoc, - "OpMemoryModel must have two operands"); + return emitError(unknownLoc, "OpMemoryModel must have two operands"); // TODO(antiagainst): use IntegerAttr-backed enum attributes to avoid the // excessive string conversions here. auto am = spirv::symbolizeAddressingModel(operands.front()); if (!am) - return context->emitError(unknownLoc, - "unknown addressing model for OpMemoryModel"); + return emitError(unknownLoc, "unknown addressing model for OpMemoryModel"); auto mm = spirv::symbolizeMemoryModel(operands.back()); if (!mm) - return context->emitError(unknownLoc, - "unknown memory model for OpMemoryModel"); + return emitError(unknownLoc, "unknown memory model for OpMemoryModel"); module->setAttr( "addressing_model", diff --git a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp index 36d04a9ae6c4..1cb9e6c7dcb5 100644 --- a/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp +++ b/mlir/lib/Target/LLVMIR/ModuleTranslation.cpp @@ -47,11 +47,8 @@ static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext, FunctionType type, Location loc, bool isVarArgs) { assert(type && "expected non-null type"); - - auto context = type.getContext(); if (type.getNumResults() > 1) - return context->emitError(loc, - "LLVM functions can only have 0 or 1 result"), + return emitError(loc, "LLVM functions can only have 0 or 1 result"), nullptr; SmallVector argTypes; @@ -59,8 +56,7 @@ static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext, for (auto t : type.getInputs()) { auto wrappedLLVMType = t.dyn_cast(); if (!wrappedLLVMType) - return context->emitError(loc, "non-LLVM function argument type"), - nullptr; + return emitError(loc, "non-LLVM function argument type"), nullptr; argTypes.push_back(wrappedLLVMType.getUnderlyingType()); } @@ -70,7 +66,7 @@ static llvm::FunctionType *convertFunctionType(llvm::LLVMContext &llvmContext, auto wrappedResultType = type.getResult(0).dyn_cast(); if (!wrappedResultType) - return context->emitError(loc, "non-LLVM function result"), nullptr; + return emitError(loc, "non-LLVM function result"), nullptr; return llvm::FunctionType::get(wrappedResultType.getUnderlyingType(), argTypes, isVarArgs); @@ -115,7 +111,7 @@ llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType, llvmModule->getContext(), ArrayRef{stringAttr.getValue().data(), stringAttr.getValue().size()}); } - mlirModule.getContext()->emitError(loc, "unsupported constant value"); + emitError(loc, "unsupported constant value"); return nullptr; } @@ -238,8 +234,8 @@ bool ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { for (auto *arg : bb.getArguments()) { auto wrappedType = arg->getType().dyn_cast(); if (!wrappedType) { - arg->getType().getContext()->emitError( - bb.front().getLoc(), "block argument does not have an LLVM type"); + emitError(bb.front().getLoc(), + "block argument does not have an LLVM type"); return true; } llvm::Type *type = wrappedType.getUnderlyingType(); @@ -344,8 +340,7 @@ bool ModuleTranslation::convertOneFunction(Function &func) { // attach the attribute to this argument, based on its type. auto argTy = mlirArg->getType().dyn_cast(); if (!argTy.getUnderlyingType()->isPointerTy()) { - argTy.getContext()->emitError( - func.getLoc(), + func.emitError( "llvm.noalias attribute attached to LLVM non-pointer argument"); return true; } diff --git a/mlir/lib/Transforms/DialectConversion.cpp b/mlir/lib/Transforms/DialectConversion.cpp index 673544d03147..88db7b6213ca 100644 --- a/mlir/lib/Transforms/DialectConversion.cpp +++ b/mlir/lib/Transforms/DialectConversion.cpp @@ -177,7 +177,7 @@ LogicalResult ArgConverter::applyRewrites() { // Don't emit another error if we already have one. if (!failed(result)) { auto *parent = block->getParent(); - auto diag = parent->getContext()->emitError(parent->getLoc()) + auto diag = emitError(parent->getLoc()) << "block argument #" << i << " with type " << op->getResult(0)->getType() << " has unexpected remaining uses"; @@ -246,7 +246,7 @@ LogicalResult ArgConverter::convertArguments(Block *block, for (unsigned i = 0; i != origArgCount; ++i) { auto *arg = block->getArgument(i); if (failed(converter.convertType(arg->getType(), newArgTypes[i]))) - return arg->getContext()->emitError(block->getParent()->getLoc()) + return emitError(block->getParent()->getLoc()) << "could not convert block argument of type " << arg->getType(); } @@ -963,8 +963,7 @@ FunctionConverter::convertRegion(DialectConversionRewriter &rewriter, // If some blocks are not reachable through successor chains, they should have // been removed by the DCE before this. if (visitedBlocks.size() != numBlocks) - return rewriter.getContext()->emitError(region.getLoc()) - << "unreachable blocks were not converted"; + return emitError(region.getLoc(), "unreachable blocks were not converted"); return success(); } diff --git a/mlir/lib/Transforms/LowerAffine.cpp b/mlir/lib/Transforms/LowerAffine.cpp index 8a632c8add36..6b6ba9065373 100644 --- a/mlir/lib/Transforms/LowerAffine.cpp +++ b/mlir/lib/Transforms/LowerAffine.cpp @@ -78,14 +78,13 @@ public: Value *visitModExpr(AffineBinaryOpExpr expr) { auto rhsConst = expr.getRHS().dyn_cast(); if (!rhsConst) { - builder.getContext()->emitError( + emitError( loc, "semi-affine expressions (modulo by non-const) are not supported"); return nullptr; } if (rhsConst.getValue() <= 0) { - builder.getContext()->emitError( - loc, "modulo by non-positive value is not supported"); + emitError(loc, "modulo by non-positive value is not supported"); return nullptr; } @@ -116,14 +115,13 @@ public: Value *visitFloorDivExpr(AffineBinaryOpExpr expr) { auto rhsConst = expr.getRHS().dyn_cast(); if (!rhsConst) { - builder.getContext()->emitError( + emitError( loc, "semi-affine expressions (division by non-const) are not supported"); return nullptr; } if (rhsConst.getValue() <= 0) { - builder.getContext()->emitError( - loc, "division by non-positive value is not supported"); + emitError(loc, "division by non-positive value is not supported"); return nullptr; } @@ -158,14 +156,12 @@ public: Value *visitCeilDivExpr(AffineBinaryOpExpr expr) { auto rhsConst = expr.getRHS().dyn_cast(); if (!rhsConst) { - builder.getContext()->emitError( - loc, - "semi-affine expressions (division by non-const) are not supported"); + emitError(loc) << "semi-affine expressions (division by non-const) are " + "not supported"; return nullptr; } if (rhsConst.getValue() <= 0) { - builder.getContext()->emitError( - loc, "division by non-positive value is not supported"); + emitError(loc, "division by non-positive value is not supported"); return nullptr; } auto lhs = visit(expr.getLHS()); diff --git a/mlir/test/lib/Transforms/TestVectorizationUtils.cpp b/mlir/test/lib/Transforms/TestVectorizationUtils.cpp index 6636453c5e9d..4767e3367be1 100644 --- a/mlir/test/lib/Transforms/TestVectorizationUtils.cpp +++ b/mlir/test/lib/Transforms/TestVectorizationUtils.cpp @@ -282,7 +282,7 @@ void VectorizerTestPass::runOnFunction() { testNormalizeMaps(); if (!outs.str().empty()) { - getContext().emitRemark(UnknownLoc::get(&getContext()), outs.str()); + emitRemark(UnknownLoc::get(&getContext()), outs.str()); } } -- 2.34.1