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