40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/FileUtilities.h"
43 #include "llvm/Support/InitLLVM.h"
44 #include "llvm/Support/LogicalResult.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/Process.h"
47 #include "llvm/Support/Regex.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/StringSaver.h"
50 #include "llvm/Support/ThreadPool.h"
51 #include "llvm/Support/ToolOutputFile.h"
57 class BytecodeVersionParser :
public cl::parser<std::optional<int64_t>> {
59 BytecodeVersionParser(cl::Option &o)
60 : cl::parser<std::optional<int64_t>>(o) {}
62 bool parse(cl::Option &o, StringRef , StringRef arg,
63 std::optional<int64_t> &v) {
65 if (getAsSignedInteger(arg, 10, w))
66 return o.error(
"Invalid argument '" + arg +
67 "', only integer is supported.");
76 MlirOptMainConfigCLOptions() {
82 static cl::opt<bool,
true> allowUnregisteredDialects(
83 "allow-unregistered-dialect",
84 cl::desc(
"Allow operation with no registered dialects"),
85 cl::location(allowUnregisteredDialectsFlag), cl::init(
false));
87 static cl::opt<bool,
true> dumpPassPipeline(
88 "dump-pass-pipeline", cl::desc(
"Print the pipeline that will be run"),
89 cl::location(dumpPassPipelineFlag), cl::init(
false));
91 static cl::opt<bool,
true> emitBytecode(
92 "emit-bytecode", cl::desc(
"Emit bytecode when generating output"),
93 cl::location(emitBytecodeFlag), cl::init(
false));
95 static cl::opt<bool,
true> elideResourcesFromBytecode(
96 "elide-resource-data-from-bytecode",
97 cl::desc(
"Elide resources when generating bytecode"),
98 cl::location(elideResourceDataFromBytecodeFlag), cl::init(
false));
100 static cl::opt<std::optional<int64_t>,
true,
101 BytecodeVersionParser>
103 "emit-bytecode-version",
104 cl::desc(
"Use specified bytecode when generating output"),
105 cl::location(emitBytecodeVersion), cl::init(std::nullopt));
107 static cl::opt<std::string,
true> irdlFile(
109 cl::desc(
"IRDL file to register before processing the input"),
110 cl::location(irdlFileFlag), cl::init(
""), cl::value_desc(
"filename"));
113 diagnosticVerbosityLevel(
114 "mlir-diagnostic-verbosity-level",
115 cl::desc(
"Choose level of diagnostic information"),
116 cl::location(diagnosticVerbosityLevelFlag),
121 "Errors and warnings"),
123 "Errors, warnings and remarks")));
125 static cl::opt<bool,
true> disableDiagnosticNotes(
126 "mlir-disable-diagnostic-notes", cl::desc(
"Disable diagnostic notes."),
127 cl::location(disableDiagnosticNotesFlag), cl::init(
false));
129 static cl::opt<bool,
true> explicitModule(
130 "no-implicit-module",
131 cl::desc(
"Disable implicit addition of a top-level module op during "
133 cl::location(useExplicitModuleFlag), cl::init(
false));
135 static cl::opt<bool,
true> listPasses(
136 "list-passes", cl::desc(
"Print the list of registered passes and exit"),
137 cl::location(listPassesFlag), cl::init(
false));
139 static cl::opt<bool,
true> runReproducer(
140 "run-reproducer", cl::desc(
"Run the pipeline stored in the reproducer"),
141 cl::location(runReproducerFlag), cl::init(
false));
143 static cl::opt<bool,
true> showDialects(
145 cl::desc(
"Print the list of registered dialects and exit"),
146 cl::location(showDialectsFlag), cl::init(
false));
148 static cl::opt<std::string,
true> splitInputFile{
150 llvm::cl::ValueOptional,
151 cl::callback([&](
const std::string &str) {
156 cl::desc(
"Split the input file into chunks using the given or "
157 "default marker and process each chunk independently"),
158 cl::location(splitInputFileFlag),
161 static cl::opt<std::string,
true> outputSplitMarker(
162 "output-split-marker",
163 cl::desc(
"Split marker to use for merging the ouput"),
169 "verify-diagnostics", llvm::cl::ValueOptional,
170 cl::desc(
"Check that emitted diagnostics match expected-* lines on "
171 "the corresponding line"),
172 cl::location(verifyDiagnosticsFlag),
176 "Check all diagnostics (expected, unexpected, "
181 "Check all diagnostics (expected, unexpected, "
185 "only-expected",
"Check only expected diagnostics"))};
187 static cl::opt<bool,
true> verifyPasses(
189 cl::desc(
"Run the verifier after each transformation pass"),
190 cl::location(verifyPassesFlag), cl::init(
true));
192 static cl::opt<bool,
true> disableVerifyOnParsing(
193 "mlir-very-unsafe-disable-verifier-on-parsing",
194 cl::desc(
"Disable the verifier on parsing (very unsafe)"),
195 cl::location(disableVerifierOnParsingFlag), cl::init(
false));
197 static cl::opt<bool,
true> verifyRoundtrip(
199 cl::desc(
"Round-trip the IR after parsing and ensure it succeeds"),
200 cl::location(verifyRoundtripFlag), cl::init(
false));
202 static cl::list<std::string> passPlugins(
203 "load-pass-plugin", cl::desc(
"Load passes from plugin library"));
205 static cl::opt<std::string,
true>
206 generateReproducerFile(
207 "mlir-generate-reproducer",
209 "Generate an mlir reproducer at the provided filename"
210 " (no crash required)"),
211 cl::location(generateReproducerFileFlag), cl::init(
""),
212 cl::value_desc(
"filename"));
215 passPlugins.setCallback([&](
const std::string &pluginPath) {
218 errs() <<
"Failed to load passes from '" << pluginPath
219 <<
"'. Request ignored.\n";
222 plugin.get().registerPassRegistryCallbacks();
225 static cl::list<std::string> dialectPlugins(
226 "load-dialect-plugin", cl::desc(
"Load dialects from plugin library"));
227 this->dialectPlugins = std::addressof(dialectPlugins);
230 setPassPipelineParser(passPipeline);
238 cl::list<std::string> *dialectPlugins =
nullptr;
246 bool showNotes =
true)
249 auto severity =
diag.getSeverity();
273 llvm_unreachable(
"Unknown diagnostic severity");
294 auto errorHandler = [&](
const Twine &msg) {
300 if (this->shouldDumpPassPipeline()) {
303 llvm::errs() <<
"\n";
310 void MlirOptMainConfigCLOptions::setDialectPluginsCallback(
312 dialectPlugins->setCallback([&](
const std::string &pluginPath) {
315 errs() <<
"Failed to load dialect plugin from '" << pluginPath
316 <<
"'. Request ignored.\n";
319 plugin.get().registerDialectRegistryCallbacks(registry);
325 registry.
insert<irdl::IRDLDialect>();
329 std::string errorMessage;
330 std::unique_ptr<MemoryBuffer> file =
openInputFile(irdlFile, &errorMessage);
339 sourceMgr.AddNewSourceBuffer(std::move(file), SMLoc());
364 StringRef irdlFile =
config.getIrdlFile();
365 if (!irdlFile.empty() && failed(
loadIRDLDialects(irdlFile, roundtripContext)))
368 std::string testType = (useBytecode) ?
"bytecode" :
"textual";
373 llvm::raw_string_ostream ostream(buffer);
377 <<
"failed to write bytecode, cannot verify round-trip.\n";
386 &fallbackResourceMap);
387 roundtripModule = parseSourceString<Operation *>(buffer, parseConfig);
388 if (!roundtripModule) {
389 op->
emitOpError() <<
"failed to parse " << testType
390 <<
" content back, cannot verify round-trip.\n";
397 std::string reference, roundtrip;
399 llvm::raw_string_ostream ostreamref(reference);
400 op->
print(ostreamref,
402 llvm::raw_string_ostream ostreamrndtrip(roundtrip);
403 roundtripModule.
get()->print(
407 if (reference != roundtrip) {
411 <<
" roundTrip testing roundtripped module differs "
412 "from reference:\n<<<<<<Reference\n"
413 << reference <<
"\n=====\n"
414 << roundtrip <<
"\n>>>>>roundtripped\n";
424 return success(succeeded(txtStatus) && succeeded(bcStatus));
435 const std::shared_ptr<llvm::SourceMgr> &sourceMgr,
453 &fallbackResourceMap);
454 if (
config.shouldRunReproducer())
460 sourceMgr, parseConfig, !
config.shouldUseExplicitModule());
466 if (
config.shouldVerifyRoundtrip() &&
478 if (
config.shouldRunReproducer() && failed(reproOptions.
apply(pm)))
480 if (failed(
config.setupPassPipeline(pm)))
484 if (failed(pm.
run(*op)))
488 if (!
config.getReproducerFilename().empty()) {
492 config.getReproducerFilename());
497 if (
config.shouldEmitBytecode()) {
499 if (
auto v =
config.bytecodeVersionToEmit())
501 if (
config.shouldElideResourceDataFromBytecode())
506 if (
config.bytecodeVersionToEmit().has_value())
508 <<
"bytecode version while not emitting bytecode";
510 &fallbackResourceMap);
511 op.
get()->print(os, asmState);
519 std::unique_ptr<MemoryBuffer> ownedBuffer,
522 llvm::ThreadPoolInterface *threadPool) {
524 auto sourceMgr = std::make_shared<SourceMgr>();
525 sourceMgr->AddNewSourceBuffer(std::move(ownedBuffer), SMLoc());
533 StringRef irdlFile =
config.getIrdlFile();
539 if (
config.shouldVerifyDiagnostics())
547 if (!
config.shouldVerifyDiagnostics()) {
549 DiagnosticFilter diagnosticFilter(&context,
550 config.getDiagnosticVerbosityLevel(),
551 config.shouldShowNotes());
556 *sourceMgr, &context,
config.verifyDiagnosticsLevel());
565 return sourceMgrHandler.
verify();
568 std::pair<std::string, std::string>
570 llvm::StringRef toolName,
572 static cl::opt<std::string> inputFilename(
573 cl::Positional, cl::desc(
"<input file>"), cl::init(
"-"));
575 static cl::opt<std::string> outputFilename(
"o", cl::desc(
"Output filename"),
576 cl::value_desc(
"filename"),
587 std::string helpHeader = (toolName +
"\nAvailable Dialects: ").str();
589 llvm::raw_string_ostream os(helpHeader);
591 [&](
auto name) { os << name; });
594 cl::ParseCommandLineOptions(argc, argv, helpHeader);
595 return std::make_pair(inputFilename.getValue(), outputFilename.getValue());
599 llvm::outs() <<
"Available Dialects: ";
601 llvm::outs() <<
"\n";
611 std::unique_ptr<llvm::MemoryBuffer> buffer,
614 if (
config.shouldShowDialects())
617 if (
config.shouldListPasses())
624 ThreadPoolInterface *threadPool =
nullptr;
634 auto chunkFn = [&](std::unique_ptr<MemoryBuffer> chunkBuffer,
640 config.inputSplitMarker(),
641 config.outputSplitMarker());
645 llvm::StringRef inputFilename,
646 llvm::StringRef outputFilename,
649 InitLLVM y(argc, argv);
653 if (
config.shouldShowDialects())
656 if (
config.shouldListPasses())
662 if (inputFilename ==
"-" &&
663 sys::Process::FileDescriptorIsDisplayed(fileno(stdin)))
664 llvm::errs() <<
"(processing input from stdin now, hit ctrl-c/ctrl-d to "
668 std::string errorMessage;
671 llvm::errs() << errorMessage <<
"\n";
677 llvm::errs() << errorMessage <<
"\n";
692 std::string inputFilename, outputFilename;
693 std::tie(inputFilename, outputFilename) =
696 return MlirOptMain(argc, argv, inputFilename, outputFilename, registry);
static LogicalResult printRegisteredDialects(DialectRegistry ®istry)
LogicalResult loadIRDLDialects(StringRef irdlFile, MLIRContext &ctx)
static LogicalResult doVerifyRoundTrip(Operation *op, const MlirOptMainConfig &config, bool useBytecode)
static LogicalResult printRegisteredPassesAndReturn()
ManagedStatic< MlirOptMainConfigCLOptions > clOptionsConfig
static LogicalResult processBuffer(raw_ostream &os, std::unique_ptr< MemoryBuffer > ownedBuffer, const MlirOptMainConfig &config, DialectRegistry ®istry, llvm::ThreadPoolInterface *threadPool)
Parses the memory buffer.
static LogicalResult performActions(raw_ostream &os, const std::shared_ptr< llvm::SourceMgr > &sourceMgr, MLIRContext *context, const MlirOptMainConfig &config)
Perform the actions on the input file indicated by the command line flags within the specified contex...
static std::string diag(const llvm::Value &value)
This class provides management for the lifetime of the state used when printing the IR.
This class contains the configuration used for the bytecode writer.
void setElideResourceDataFlag(bool shouldElideResourceData=true)
Set a boolean flag to skip emission of resources into the bytecode file.
void setDesiredBytecodeVersion(int64_t bytecodeVersion)
Set the desired bytecode version to emit.
Facilities for time measurement and report printing to an output stream.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
static llvm::Expected< DialectPlugin > load(const std::string &filename)
Attempts to load a dialect plugin from a given file.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
auto getDialectNames() const
Return the names of dialects known to this registry.
A fallback map containing external resources not explicitly handled by another parser/printer.
MLIRContext is the top-level object for a collection of MLIR operations.
void appendDialectRegistry(const DialectRegistry ®istry)
Append the contents of the given dialect registry to the registry associated with this context.
void disableMultithreading(bool disable=true)
Set the flag specifying if multi-threading is disabled by the context.
void setThreadPool(llvm::ThreadPoolInterface &pool)
Set a new thread pool to be used in this context.
void enableMultithreading(bool enable=true)
void printOpOnDiagnostic(bool enable)
Set the flag specifying if we should attach the operation to diagnostics emitted via Operation::emit.
const DialectRegistry & getDialectRegistry()
Return the dialect registry associated with this context.
llvm::ThreadPoolInterface & getThreadPool()
Return the thread pool used by this context.
bool isMultithreadingEnabled()
Return true if multi-threading is enabled by the context.
void allowUnregisteredDialects(bool allow=true)
Enables creating operations in unregistered dialects.
bool allowsUnregisteredDialects()
Return true if we allow to create operation for unregistered dialects.
Configuration options for the mlir-opt tool.
static MlirOptMainConfig createFromCLOptions()
Create a new config with the default set from the CL options.
static void registerCLOptions(DialectRegistry &dialectRegistry)
Register the options as global LLVM command line options.
MlirOptMainConfig & setPassPipelineParser(const PassPipelineCLParser &parser)
Set the parser to use to populate the pass manager.
@ Implicit
Implicit nesting behavior.
iterator_range< pass_iterator > getPasses()
static StringRef getAnyOpAnchorName()
Return the string name used to anchor op-agnostic pass managers that operate generically on any viabl...
Set of flags used to control the behavior of the various IR print methods (e.g.
Operation is the basic unit of execution within MLIR.
void print(raw_ostream &os, const OpPrintingFlags &flags=std::nullopt)
MLIRContext * getContext()
Return the context this operation is associated with.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
OpTy get() const
Allow accessing the internal op.
This class represents a configuration for the MLIR assembly parser.
The main pass manager and pipeline builder.
MLIRContext * getContext() const
Return an instance of the context.
LogicalResult run(Operation *op)
Run the passes within this manager on the provided operation.
void enableVerifier(bool enabled=true)
Runs the verifier after each individual pass.
void enableTiming(TimingScope &timingScope)
Add an instrumentation to time the execution of passes and the computation of analyses.
This class implements a command-line parser for MLIR passes.
LogicalResult addToPipeline(OpPassManager &pm, function_ref< LogicalResult(const Twine &)> errorHandler) const
Adds the passes defined by this parser entry to the given pass manager.
static llvm::Expected< PassPlugin > load(const std::string &filename)
Attempts to load a pass plugin from a given file.
This diagnostic handler is a simple RAII class that registers and erases a diagnostic handler on a gi...
This class is a utility diagnostic handler for use with llvm::SourceMgr.
This class is a utility diagnostic handler for use with llvm::SourceMgr that verifies that emitted di...
LogicalResult verify()
Returns the status of the handler and verifies that all expected diagnostics were emitted.
TimingScope getRootScope()
Get the root timer of this timing manager wrapped in a TimingScope for convenience.
An RAII-style wrapper around a timer that ensures the timer is properly started and stopped.
TimingScope nest(Args... args)
Create a nested timing scope.
void stop()
Manually stop the timer early.
static DebugConfig createFromCLOptions()
Create a new config with the default set from the CL options.
static void registerCLOptions()
Register the options as global LLVM command line options.
static void registerCLOptions()
Register the command line options for debug counters.
This is a RAII class that installs the debug handlers on the context based on the provided configurat...
The OpAsmOpInterface, see OpAsmInterface.td for more details.
llvm::LogicalResult loadDialects(ModuleOp op)
Load all the dialects defined in the module.
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Include the generated interface declarations.
std::unique_ptr< llvm::MemoryBuffer > openInputFile(llvm::StringRef inputFilename, std::string *errorMessage=nullptr)
Open the file specified by its name for reading.
LogicalResult applyPassManagerCLOptions(PassManager &pm)
Apply any values provided to the pass manager options that were registered with 'registerPassManagerO...
const char *const kDefaultSplitMarker
void registerDefaultTimingManagerCLOptions()
Register a set of useful command-line options that can be used to configure a DefaultTimingManager.
const FrozenRewritePatternSet GreedyRewriteConfig config
void printRegisteredPasses()
Prints the passes that were previously registered and stored in passRegistry.
LogicalResult MlirOptMain(llvm::raw_ostream &outputStream, std::unique_ptr< llvm::MemoryBuffer > buffer, DialectRegistry ®istry, const MlirOptMainConfig &config)
Perform the core processing behind mlir-opt.
std::unique_ptr< llvm::ToolOutputFile > openOutputFile(llvm::StringRef outputFilename, std::string *errorMessage=nullptr)
Open the file specified by its name for writing.
std::string makeReproducer(StringRef anchorName, const llvm::iterator_range< OpPassManager::pass_iterator > &passes, Operation *op, StringRef outputFile, bool disableThreads=false, bool verifyPasses=false)
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
void registerMLIRContextCLOptions()
Register a set of useful command-line options that can be used to configure various flags within the ...
LogicalResult splitAndProcessBuffer(std::unique_ptr< llvm::MemoryBuffer > originalBuffer, ChunkBufferHandler processChunkBuffer, raw_ostream &os, llvm::StringRef inputSplitMarker=kDefaultSplitMarker, llvm::StringRef outputSplitMarker="")
Splits the specified buffer on a marker (// ----- by default), processes each chunk independently acc...
OwningOpRef< Operation * > parseSourceFileForTool(const std::shared_ptr< llvm::SourceMgr > &sourceMgr, const ParserConfig &config, bool insertImplicitModule)
This parses the file specified by the indicated SourceMgr.
void registerAsmPrinterCLOptions()
Register a set of useful command-line options that can be used to configure various flags within the ...
void registerPassManagerCLOptions()
Register a set of useful command-line options that can be used to configure a pass manager.
void applyDefaultTimingManagerCLOptions(DefaultTimingManager &tm)
Apply any values that were registered with 'registerDefaultTimingManagerOptions' to a DefaultTimingMa...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
std::pair< std::string, std::string > registerAndParseCLIOptions(int argc, char **argv, llvm::StringRef toolName, DialectRegistry ®istry)
Register and parse command line options.
VerbosityLevel
enum class to indicate the verbosity level of the diagnostic filter.
@ ErrorsWarningsAndRemarks
LogicalResult writeBytecodeToFile(Operation *op, raw_ostream &os, const BytecodeWriterConfig &config={})
Write the bytecode for the given operation to the provided output stream.
void attachResourceParser(ParserConfig &config)
Attach an assembly resource parser to 'config' that collects the MLIR reproducer configuration into t...
LogicalResult apply(PassManager &pm) const
Apply the reproducer options to 'pm' and its context.