[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / mlir / examples / toy / Ch3 / toyc.cpp
blob8c27a7af97a002a00ce415278f46272fabebb689
1 //===- toyc.cpp - The Toy Compiler ----------------------------------------===//
2 //
3 // Part of the LLVM Project, 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 // This file implements the entry point for the Toy compiler.
11 //===----------------------------------------------------------------------===//
13 #include "mlir/IR/Diagnostics.h"
14 #include "mlir/Support/LogicalResult.h"
15 #include "toy/AST.h"
16 #include "toy/Dialect.h"
17 #include "toy/Lexer.h"
18 #include "toy/MLIRGen.h"
19 #include "toy/Parser.h"
21 #include "mlir/IR/AsmState.h"
22 #include "mlir/IR/BuiltinOps.h"
23 #include "mlir/IR/MLIRContext.h"
24 #include "mlir/IR/Verifier.h"
25 #include "mlir/Parser/Parser.h"
26 #include "mlir/Pass/PassManager.h"
27 #include "mlir/Transforms/Passes.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorOr.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <memory>
36 #include <string>
37 #include <system_error>
38 #include <utility>
40 using namespace toy;
41 namespace cl = llvm::cl;
43 static cl::opt<std::string> inputFilename(cl::Positional,
44 cl::desc("<input toy file>"),
45 cl::init("-"),
46 cl::value_desc("filename"));
48 namespace {
49 enum InputType { Toy, MLIR };
50 } // namespace
51 static cl::opt<enum InputType> inputType(
52 "x", cl::init(Toy), cl::desc("Decided the kind of output desired"),
53 cl::values(clEnumValN(Toy, "toy", "load the input file as a Toy source.")),
54 cl::values(clEnumValN(MLIR, "mlir",
55 "load the input file as an MLIR file")));
57 namespace {
58 enum Action { None, DumpAST, DumpMLIR };
59 } // namespace
60 static cl::opt<enum Action> emitAction(
61 "emit", cl::desc("Select the kind of output desired"),
62 cl::values(clEnumValN(DumpAST, "ast", "output the AST dump")),
63 cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")));
65 static cl::opt<bool> enableOpt("opt", cl::desc("Enable optimizations"));
67 /// Returns a Toy AST resulting from parsing the file or a nullptr on error.
68 std::unique_ptr<toy::ModuleAST> parseInputFile(llvm::StringRef filename) {
69 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
70 llvm::MemoryBuffer::getFileOrSTDIN(filename);
71 if (std::error_code ec = fileOrErr.getError()) {
72 llvm::errs() << "Could not open input file: " << ec.message() << "\n";
73 return nullptr;
75 auto buffer = fileOrErr.get()->getBuffer();
76 LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename));
77 Parser parser(lexer);
78 return parser.parseModule();
81 int loadMLIR(llvm::SourceMgr &sourceMgr, mlir::MLIRContext &context,
82 mlir::OwningOpRef<mlir::ModuleOp> &module) {
83 // Handle '.toy' input to the compiler.
84 if (inputType != InputType::MLIR &&
85 !llvm::StringRef(inputFilename).endswith(".mlir")) {
86 auto moduleAST = parseInputFile(inputFilename);
87 if (!moduleAST)
88 return 6;
89 module = mlirGen(context, *moduleAST);
90 return !module ? 1 : 0;
93 // Otherwise, the input is '.mlir'.
94 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
95 llvm::MemoryBuffer::getFileOrSTDIN(inputFilename);
96 if (std::error_code ec = fileOrErr.getError()) {
97 llvm::errs() << "Could not open input file: " << ec.message() << "\n";
98 return -1;
101 // Parse the input mlir.
102 sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc());
103 module = mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, &context);
104 if (!module) {
105 llvm::errs() << "Error can't load file " << inputFilename << "\n";
106 return 3;
108 return 0;
111 int dumpMLIR() {
112 mlir::MLIRContext context;
113 // Load our Dialect in this MLIR Context.
114 context.getOrLoadDialect<mlir::toy::ToyDialect>();
116 mlir::OwningOpRef<mlir::ModuleOp> module;
117 llvm::SourceMgr sourceMgr;
118 mlir::SourceMgrDiagnosticHandler sourceMgrHandler(sourceMgr, &context);
119 if (int error = loadMLIR(sourceMgr, context, module))
120 return error;
122 if (enableOpt) {
123 mlir::PassManager pm(module.get()->getName());
124 // Apply any generic pass manager command line options and run the pipeline.
125 if (mlir::failed(mlir::applyPassManagerCLOptions(pm)))
126 return 4;
128 // Add a run of the canonicalizer to optimize the mlir module.
129 pm.addNestedPass<mlir::toy::FuncOp>(mlir::createCanonicalizerPass());
130 if (mlir::failed(pm.run(*module)))
131 return 4;
134 module->dump();
135 return 0;
138 int dumpAST() {
139 if (inputType == InputType::MLIR) {
140 llvm::errs() << "Can't dump a Toy AST when the input is MLIR\n";
141 return 5;
144 auto moduleAST = parseInputFile(inputFilename);
145 if (!moduleAST)
146 return 1;
148 dump(*moduleAST);
149 return 0;
152 int main(int argc, char **argv) {
153 // Register any command line options.
154 mlir::registerAsmPrinterCLOptions();
155 mlir::registerMLIRContextCLOptions();
156 mlir::registerPassManagerCLOptions();
158 cl::ParseCommandLineOptions(argc, argv, "toy compiler\n");
160 switch (emitAction) {
161 case Action::DumpAST:
162 return dumpAST();
163 case Action::DumpMLIR:
164 return dumpMLIR();
165 default:
166 llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";
169 return 0;