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 #include "toy/Passes.h"
17
18 #include "mlir/IR/AsmState.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/MLIRContext.h"
21 #include "mlir/IR/Verifier.h"
22 #include "mlir/InitAllDialects.h"
23 #include "mlir/Parser.h"
24 #include "mlir/Pass/Pass.h"
25 #include "mlir/Pass/PassManager.h"
26 #include "mlir/Transforms/Passes.h"
27
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorOr.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 using namespace toy;
36 namespace cl = llvm::cl;
37
38 static cl::opt<std::string> inputFilename(cl::Positional,
39 cl::desc("<input toy file>"),
40 cl::init("-"),
41 cl::value_desc("filename"));
42
43 namespace {
44 enum InputType { Toy, MLIR };
45 }
46 static cl::opt<enum InputType> inputType(
47 "x", cl::init(Toy), cl::desc("Decided the kind of output desired"),
48 cl::values(clEnumValN(Toy, "toy", "load the input file as a Toy source.")),
49 cl::values(clEnumValN(MLIR, "mlir",
50 "load the input file as an MLIR file")));
51
52 namespace {
53 enum Action { None, DumpAST, DumpMLIR, DumpMLIRAffine };
54 }
55 static cl::opt<enum Action> emitAction(
56 "emit", cl::desc("Select the kind of output desired"),
57 cl::values(clEnumValN(DumpAST, "ast", "output the AST dump")),
58 cl::values(clEnumValN(DumpMLIR, "mlir", "output the MLIR dump")),
59 cl::values(clEnumValN(DumpMLIRAffine, "mlir-affine",
60 "output the MLIR dump after affine lowering")));
61
62 static cl::opt<bool> enableOpt("opt", cl::desc("Enable optimizations"));
63
64 /// Returns a Toy AST resulting from parsing the file or a nullptr on error.
parseInputFile(llvm::StringRef filename)65 std::unique_ptr<toy::ModuleAST> parseInputFile(llvm::StringRef filename) {
66 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
67 llvm::MemoryBuffer::getFileOrSTDIN(filename);
68 if (std::error_code ec = fileOrErr.getError()) {
69 llvm::errs() << "Could not open input file: " << ec.message() << "\n";
70 return nullptr;
71 }
72 auto buffer = fileOrErr.get()->getBuffer();
73 LexerBuffer lexer(buffer.begin(), buffer.end(), std::string(filename));
74 Parser parser(lexer);
75 return parser.parseModule();
76 }
77
loadMLIR(llvm::SourceMgr & sourceMgr,mlir::MLIRContext & context,mlir::OwningModuleRef & module)78 int loadMLIR(llvm::SourceMgr &sourceMgr, mlir::MLIRContext &context,
79 mlir::OwningModuleRef &module) {
80 // Handle '.toy' input to the compiler.
81 if (inputType != InputType::MLIR &&
82 !llvm::StringRef(inputFilename).endswith(".mlir")) {
83 auto moduleAST = parseInputFile(inputFilename);
84 if (!moduleAST)
85 return 6;
86 module = mlirGen(context, *moduleAST);
87 return !module ? 1 : 0;
88 }
89
90 // Otherwise, the input is '.mlir'.
91 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
92 llvm::MemoryBuffer::getFileOrSTDIN(inputFilename);
93 if (std::error_code EC = fileOrErr.getError()) {
94 llvm::errs() << "Could not open input file: " << EC.message() << "\n";
95 return -1;
96 }
97
98 // Parse the input mlir.
99 sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc());
100 module = mlir::parseSourceFile(sourceMgr, &context);
101 if (!module) {
102 llvm::errs() << "Error can't load file " << inputFilename << "\n";
103 return 3;
104 }
105 return 0;
106 }
107
dumpMLIR()108 int dumpMLIR() {
109 mlir::MLIRContext context;
110 // Load our Dialect in this MLIR Context.
111 context.getOrLoadDialect<mlir::toy::ToyDialect>();
112
113 mlir::OwningModuleRef module;
114 llvm::SourceMgr sourceMgr;
115 mlir::SourceMgrDiagnosticHandler sourceMgrHandler(sourceMgr, &context);
116 if (int error = loadMLIR(sourceMgr, context, module))
117 return error;
118
119 mlir::PassManager pm(&context);
120 // Apply any generic pass manager command line options and run the pipeline.
121 applyPassManagerCLOptions(pm);
122
123 // Check to see what granularity of MLIR we are compiling to.
124 bool isLoweringToAffine = emitAction >= Action::DumpMLIRAffine;
125
126 if (enableOpt || isLoweringToAffine) {
127 // Inline all functions into main and then delete them.
128 pm.addPass(mlir::createInlinerPass());
129
130 // Now that there is only one function, we can infer the shapes of each of
131 // the operations.
132 mlir::OpPassManager &optPM = pm.nest<mlir::FuncOp>();
133 optPM.addPass(mlir::toy::createShapeInferencePass());
134 optPM.addPass(mlir::createCanonicalizerPass());
135 optPM.addPass(mlir::createCSEPass());
136 }
137
138 if (isLoweringToAffine) {
139 mlir::OpPassManager &optPM = pm.nest<mlir::FuncOp>();
140
141 // Partially lower the toy dialect with a few cleanups afterwards.
142 optPM.addPass(mlir::toy::createLowerToAffinePass());
143 optPM.addPass(mlir::createCanonicalizerPass());
144 optPM.addPass(mlir::createCSEPass());
145
146 // Add optimizations if enabled.
147 if (enableOpt) {
148 optPM.addPass(mlir::createLoopFusionPass());
149 optPM.addPass(mlir::createMemRefDataFlowOptPass());
150 }
151 }
152
153 if (mlir::failed(pm.run(*module)))
154 return 4;
155
156 module->dump();
157 return 0;
158 }
159
dumpAST()160 int dumpAST() {
161 if (inputType == InputType::MLIR) {
162 llvm::errs() << "Can't dump a Toy AST when the input is MLIR\n";
163 return 5;
164 }
165
166 auto moduleAST = parseInputFile(inputFilename);
167 if (!moduleAST)
168 return 1;
169
170 dump(*moduleAST);
171 return 0;
172 }
173
main(int argc,char ** argv)174 int main(int argc, char **argv) {
175 // Register any command line options.
176 mlir::registerAsmPrinterCLOptions();
177 mlir::registerMLIRContextCLOptions();
178 mlir::registerPassManagerCLOptions();
179
180 cl::ParseCommandLineOptions(argc, argv, "toy compiler\n");
181
182 switch (emitAction) {
183 case Action::DumpAST:
184 return dumpAST();
185 case Action::DumpMLIR:
186 case Action::DumpMLIRAffine:
187 return dumpMLIR();
188 default:
189 llvm::errs() << "No action specified (parsing only?), use -emit=<action>\n";
190 }
191
192 return 0;
193 }
194