xref: /llvm-project/mlir/examples/minimal-opt/mlir-cat.cpp (revision e59f76e9f57696c2f3c816947314be097d1c2942)
1 //===- mlir-cat.cpp ---------------------------------------------*- C++ -*-===//
2 //
3 // This file is licensed under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "mlir/IR/MLIRContext.h"
10 #include "mlir/IR/Operation.h"
11 #include "mlir/IR/OwningOpRef.h"
12 #include "mlir/Parser/Parser.h"
13 #include "mlir/Support/FileUtilities.h"
14 #include "mlir/Support/LLVM.h"
15 #include "llvm/Support/SourceMgr.h"
16 #include "llvm/Support/ToolOutputFile.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <cstdlib>
19 #include <string>
20 #include <utility>
21 
22 using namespace mlir;
23 
24 /// This example parse its input, either from a file or its standard input (in
25 /// bytecode or textual assembly) and print it back.
26 
main(int argc,char ** argv)27 int main(int argc, char **argv) {
28   // Set up the input file.
29   StringRef inputFile;
30   if (argc <= 1) {
31     llvm::errs() << "Reading from stdin...\n";
32     inputFile = "-";
33   } else {
34     inputFile = argv[1];
35   }
36   std::string errorMessage;
37   auto file = openInputFile(inputFile, &errorMessage);
38   if (!file) {
39     llvm::errs() << errorMessage << "\n";
40     exit(1);
41   }
42   llvm::SourceMgr sourceMgr;
43   sourceMgr.AddNewSourceBuffer(std::move(file), SMLoc());
44 
45   auto output = openOutputFile("-", &errorMessage);
46   if (!output) {
47     llvm::errs() << errorMessage << "\n";
48     exit(1);
49   }
50 
51   DialectRegistry registry;
52   MLIRContext context(registry, MLIRContext::Threading::DISABLED);
53   context.allowUnregisteredDialects(true);
54   OwningOpRef<Operation *> op = parseSourceFile(sourceMgr, &context);
55   if (!op) {
56     llvm::errs() << "Failed to parse input file";
57     exit(1);
58   }
59   output->os() << *(op.get()) << "\n";
60 }
61