1 //===- MLIRGen.cpp - MLIR Generation from a Toy AST -----------------------===//
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 a simple IR generation targeting MLIR from a Module AST
10 // for the Toy language.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "toy/MLIRGen.h"
15 #include "toy/AST.h"
16 #include "toy/Dialect.h"
17
18 #include "mlir/IR/Attributes.h"
19 #include "mlir/IR/Builders.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/BuiltinTypes.h"
22 #include "mlir/IR/MLIRContext.h"
23 #include "mlir/IR/Verifier.h"
24
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/ScopedHashTable.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include <numeric>
29
30 using namespace mlir::toy;
31 using namespace toy;
32
33 using llvm::ArrayRef;
34 using llvm::cast;
35 using llvm::dyn_cast;
36 using llvm::isa;
37 using llvm::makeArrayRef;
38 using llvm::ScopedHashTableScope;
39 using llvm::SmallVector;
40 using llvm::StringRef;
41 using llvm::Twine;
42
43 namespace {
44
45 /// Implementation of a simple MLIR emission from the Toy AST.
46 ///
47 /// This will emit operations that are specific to the Toy language, preserving
48 /// the semantics of the language and (hopefully) allow to perform accurate
49 /// analysis and transformation based on these high level semantics.
50 class MLIRGenImpl {
51 public:
MLIRGenImpl(mlir::MLIRContext & context)52 MLIRGenImpl(mlir::MLIRContext &context) : builder(&context) {}
53
54 /// Public API: convert the AST for a Toy module (source file) to an MLIR
55 /// Module operation.
mlirGen(ModuleAST & moduleAST)56 mlir::ModuleOp mlirGen(ModuleAST &moduleAST) {
57 // We create an empty MLIR module and codegen functions one at a time and
58 // add them to the module.
59 theModule = mlir::ModuleOp::create(builder.getUnknownLoc());
60
61 for (auto &record : moduleAST) {
62 if (FunctionAST *funcAST = llvm::dyn_cast<FunctionAST>(record.get())) {
63 mlir::toy::FuncOp func = mlirGen(*funcAST);
64 if (!func)
65 return nullptr;
66 functionMap.insert({func.getName(), func});
67 } else if (StructAST *str = llvm::dyn_cast<StructAST>(record.get())) {
68 if (failed(mlirGen(*str)))
69 return nullptr;
70 } else {
71 llvm_unreachable("unknown record type");
72 }
73 }
74
75 // Verify the module after we have finished constructing it, this will check
76 // the structural properties of the IR and invoke any specific verifiers we
77 // have on the Toy operations.
78 if (failed(mlir::verify(theModule))) {
79 theModule.emitError("module verification error");
80 return nullptr;
81 }
82
83 return theModule;
84 }
85
86 private:
87 /// A "module" matches a Toy source file: containing a list of functions.
88 mlir::ModuleOp theModule;
89
90 /// The builder is a helper class to create IR inside a function. The builder
91 /// is stateful, in particular it keeps an "insertion point": this is where
92 /// the next operations will be introduced.
93 mlir::OpBuilder builder;
94
95 /// The symbol table maps a variable name to a value in the current scope.
96 /// Entering a function creates a new scope, and the function arguments are
97 /// added to the mapping. When the processing of a function is terminated, the
98 /// scope is destroyed and the mappings created in this scope are dropped.
99 llvm::ScopedHashTable<StringRef, std::pair<mlir::Value, VarDeclExprAST *>>
100 symbolTable;
101 using SymbolTableScopeT =
102 llvm::ScopedHashTableScope<StringRef,
103 std::pair<mlir::Value, VarDeclExprAST *>>;
104
105 /// A mapping for the functions that have been code generated to MLIR.
106 llvm::StringMap<mlir::toy::FuncOp> functionMap;
107
108 /// A mapping for named struct types to the underlying MLIR type and the
109 /// original AST node.
110 llvm::StringMap<std::pair<mlir::Type, StructAST *>> structMap;
111
112 /// Helper conversion for a Toy AST location to an MLIR location.
loc(const Location & loc)113 mlir::Location loc(const Location &loc) {
114 return mlir::FileLineColLoc::get(builder.getStringAttr(*loc.file), loc.line,
115 loc.col);
116 }
117
118 /// Declare a variable in the current scope, return success if the variable
119 /// wasn't declared yet.
declare(VarDeclExprAST & var,mlir::Value value)120 mlir::LogicalResult declare(VarDeclExprAST &var, mlir::Value value) {
121 if (symbolTable.count(var.getName()))
122 return mlir::failure();
123 symbolTable.insert(var.getName(), {value, &var});
124 return mlir::success();
125 }
126
127 /// Create an MLIR type for the given struct.
mlirGen(StructAST & str)128 mlir::LogicalResult mlirGen(StructAST &str) {
129 if (structMap.count(str.getName()))
130 return emitError(loc(str.loc())) << "error: struct type with name `"
131 << str.getName() << "' already exists";
132
133 auto variables = str.getVariables();
134 std::vector<mlir::Type> elementTypes;
135 elementTypes.reserve(variables.size());
136 for (auto &variable : variables) {
137 if (variable->getInitVal())
138 return emitError(loc(variable->loc()))
139 << "error: variables within a struct definition must not have "
140 "initializers";
141 if (!variable->getType().shape.empty())
142 return emitError(loc(variable->loc()))
143 << "error: variables within a struct definition must not have "
144 "initializers";
145
146 mlir::Type type = getType(variable->getType(), variable->loc());
147 if (!type)
148 return mlir::failure();
149 elementTypes.push_back(type);
150 }
151
152 structMap.try_emplace(str.getName(), StructType::get(elementTypes), &str);
153 return mlir::success();
154 }
155
156 /// Create the prototype for an MLIR function with as many arguments as the
157 /// provided Toy AST prototype.
mlirGen(PrototypeAST & proto)158 mlir::toy::FuncOp mlirGen(PrototypeAST &proto) {
159 auto location = loc(proto.loc());
160
161 // This is a generic function, the return type will be inferred later.
162 llvm::SmallVector<mlir::Type, 4> argTypes;
163 argTypes.reserve(proto.getArgs().size());
164 for (auto &arg : proto.getArgs()) {
165 mlir::Type type = getType(arg->getType(), arg->loc());
166 if (!type)
167 return nullptr;
168 argTypes.push_back(type);
169 }
170 auto funcType = builder.getFunctionType(argTypes, llvm::None);
171 return builder.create<mlir::toy::FuncOp>(location, proto.getName(),
172 funcType);
173 }
174
175 /// Emit a new function and add it to the MLIR module.
mlirGen(FunctionAST & funcAST)176 mlir::toy::FuncOp mlirGen(FunctionAST &funcAST) {
177 // Create a scope in the symbol table to hold variable declarations.
178 SymbolTableScopeT varScope(symbolTable);
179
180 // Create an MLIR function for the given prototype.
181 builder.setInsertionPointToEnd(theModule.getBody());
182 mlir::toy::FuncOp function = mlirGen(*funcAST.getProto());
183 if (!function)
184 return nullptr;
185
186 // Let's start the body of the function now!
187 mlir::Block &entryBlock = function.front();
188 auto protoArgs = funcAST.getProto()->getArgs();
189
190 // Declare all the function arguments in the symbol table.
191 for (const auto nameValue :
192 llvm::zip(protoArgs, entryBlock.getArguments())) {
193 if (failed(declare(*std::get<0>(nameValue), std::get<1>(nameValue))))
194 return nullptr;
195 }
196
197 // Set the insertion point in the builder to the beginning of the function
198 // body, it will be used throughout the codegen to create operations in this
199 // function.
200 builder.setInsertionPointToStart(&entryBlock);
201
202 // Emit the body of the function.
203 if (mlir::failed(mlirGen(*funcAST.getBody()))) {
204 function.erase();
205 return nullptr;
206 }
207
208 // Implicitly return void if no return statement was emitted.
209 // FIXME: we may fix the parser instead to always return the last expression
210 // (this would possibly help the REPL case later)
211 ReturnOp returnOp;
212 if (!entryBlock.empty())
213 returnOp = dyn_cast<ReturnOp>(entryBlock.back());
214 if (!returnOp) {
215 builder.create<ReturnOp>(loc(funcAST.getProto()->loc()));
216 } else if (returnOp.hasOperand()) {
217 // Otherwise, if this return operation has an operand then add a result to
218 // the function.
219 function.setType(
220 builder.getFunctionType(function.getFunctionType().getInputs(),
221 *returnOp.operand_type_begin()));
222 }
223
224 // If this function isn't main, then set the visibility to private.
225 if (funcAST.getProto()->getName() != "main")
226 function.setPrivate();
227
228 return function;
229 }
230
231 /// Return the struct type that is the result of the given expression, or null
232 /// if it cannot be inferred.
getStructFor(ExprAST * expr)233 StructAST *getStructFor(ExprAST *expr) {
234 llvm::StringRef structName;
235 if (auto *decl = llvm::dyn_cast<VariableExprAST>(expr)) {
236 auto varIt = symbolTable.lookup(decl->getName());
237 if (!varIt.first)
238 return nullptr;
239 structName = varIt.second->getType().name;
240 } else if (auto *access = llvm::dyn_cast<BinaryExprAST>(expr)) {
241 if (access->getOp() != '.')
242 return nullptr;
243 // The name being accessed should be in the RHS.
244 auto *name = llvm::dyn_cast<VariableExprAST>(access->getRHS());
245 if (!name)
246 return nullptr;
247 StructAST *parentStruct = getStructFor(access->getLHS());
248 if (!parentStruct)
249 return nullptr;
250
251 // Get the element within the struct corresponding to the name.
252 VarDeclExprAST *decl = nullptr;
253 for (auto &var : parentStruct->getVariables()) {
254 if (var->getName() == name->getName()) {
255 decl = var.get();
256 break;
257 }
258 }
259 if (!decl)
260 return nullptr;
261 structName = decl->getType().name;
262 }
263 if (structName.empty())
264 return nullptr;
265
266 // If the struct name was valid, check for an entry in the struct map.
267 auto structIt = structMap.find(structName);
268 if (structIt == structMap.end())
269 return nullptr;
270 return structIt->second.second;
271 }
272
273 /// Return the numeric member index of the given struct access expression.
getMemberIndex(BinaryExprAST & accessOp)274 llvm::Optional<size_t> getMemberIndex(BinaryExprAST &accessOp) {
275 assert(accessOp.getOp() == '.' && "expected access operation");
276
277 // Lookup the struct node for the LHS.
278 StructAST *structAST = getStructFor(accessOp.getLHS());
279 if (!structAST)
280 return llvm::None;
281
282 // Get the name from the RHS.
283 VariableExprAST *name = llvm::dyn_cast<VariableExprAST>(accessOp.getRHS());
284 if (!name)
285 return llvm::None;
286
287 auto structVars = structAST->getVariables();
288 const auto *it = llvm::find_if(structVars, [&](auto &var) {
289 return var->getName() == name->getName();
290 });
291 if (it == structVars.end())
292 return llvm::None;
293 return it - structVars.begin();
294 }
295
296 /// Emit a binary operation
mlirGen(BinaryExprAST & binop)297 mlir::Value mlirGen(BinaryExprAST &binop) {
298 // First emit the operations for each side of the operation before emitting
299 // the operation itself. For example if the expression is `a + foo(a)`
300 // 1) First it will visiting the LHS, which will return a reference to the
301 // value holding `a`. This value should have been emitted at declaration
302 // time and registered in the symbol table, so nothing would be
303 // codegen'd. If the value is not in the symbol table, an error has been
304 // emitted and nullptr is returned.
305 // 2) Then the RHS is visited (recursively) and a call to `foo` is emitted
306 // and the result value is returned. If an error occurs we get a nullptr
307 // and propagate.
308 //
309 mlir::Value lhs = mlirGen(*binop.getLHS());
310 if (!lhs)
311 return nullptr;
312 auto location = loc(binop.loc());
313
314 // If this is an access operation, handle it immediately.
315 if (binop.getOp() == '.') {
316 llvm::Optional<size_t> accessIndex = getMemberIndex(binop);
317 if (!accessIndex) {
318 emitError(location, "invalid access into struct expression");
319 return nullptr;
320 }
321 return builder.create<StructAccessOp>(location, lhs, *accessIndex);
322 }
323
324 // Otherwise, this is a normal binary op.
325 mlir::Value rhs = mlirGen(*binop.getRHS());
326 if (!rhs)
327 return nullptr;
328
329 // Derive the operation name from the binary operator. At the moment we only
330 // support '+' and '*'.
331 switch (binop.getOp()) {
332 case '+':
333 return builder.create<AddOp>(location, lhs, rhs);
334 case '*':
335 return builder.create<MulOp>(location, lhs, rhs);
336 }
337
338 emitError(location, "invalid binary operator '") << binop.getOp() << "'";
339 return nullptr;
340 }
341
342 /// This is a reference to a variable in an expression. The variable is
343 /// expected to have been declared and so should have a value in the symbol
344 /// table, otherwise emit an error and return nullptr.
mlirGen(VariableExprAST & expr)345 mlir::Value mlirGen(VariableExprAST &expr) {
346 if (auto variable = symbolTable.lookup(expr.getName()).first)
347 return variable;
348
349 emitError(loc(expr.loc()), "error: unknown variable '")
350 << expr.getName() << "'";
351 return nullptr;
352 }
353
354 /// Emit a return operation. This will return failure if any generation fails.
mlirGen(ReturnExprAST & ret)355 mlir::LogicalResult mlirGen(ReturnExprAST &ret) {
356 auto location = loc(ret.loc());
357
358 // 'return' takes an optional expression, handle that case here.
359 mlir::Value expr = nullptr;
360 if (ret.getExpr().hasValue()) {
361 if (!(expr = mlirGen(*ret.getExpr().getValue())))
362 return mlir::failure();
363 }
364
365 // Otherwise, this return operation has zero operands.
366 builder.create<ReturnOp>(location, expr ? makeArrayRef(expr)
367 : ArrayRef<mlir::Value>());
368 return mlir::success();
369 }
370
371 /// Emit a constant for a literal/constant array. It will be emitted as a
372 /// flattened array of data in an Attribute attached to a `toy.constant`
373 /// operation. See documentation on [Attributes](LangRef.md#attributes) for
374 /// more details. Here is an excerpt:
375 ///
376 /// Attributes are the mechanism for specifying constant data in MLIR in
377 /// places where a variable is never allowed [...]. They consist of a name
378 /// and a concrete attribute value. The set of expected attributes, their
379 /// structure, and their interpretation are all contextually dependent on
380 /// what they are attached to.
381 ///
382 /// Example, the source level statement:
383 /// var a<2, 3> = [[1, 2, 3], [4, 5, 6]];
384 /// will be converted to:
385 /// %0 = "toy.constant"() {value: dense<tensor<2x3xf64>,
386 /// [[1.000000e+00, 2.000000e+00, 3.000000e+00],
387 /// [4.000000e+00, 5.000000e+00, 6.000000e+00]]>} : () -> tensor<2x3xf64>
388 ///
getConstantAttr(LiteralExprAST & lit)389 mlir::DenseElementsAttr getConstantAttr(LiteralExprAST &lit) {
390 // The attribute is a vector with a floating point value per element
391 // (number) in the array, see `collectData()` below for more details.
392 std::vector<double> data;
393 data.reserve(std::accumulate(lit.getDims().begin(), lit.getDims().end(), 1,
394 std::multiplies<int>()));
395 collectData(lit, data);
396
397 // The type of this attribute is tensor of 64-bit floating-point with the
398 // shape of the literal.
399 mlir::Type elementType = builder.getF64Type();
400 auto dataType = mlir::RankedTensorType::get(lit.getDims(), elementType);
401
402 // This is the actual attribute that holds the list of values for this
403 // tensor literal.
404 return mlir::DenseElementsAttr::get(dataType, llvm::makeArrayRef(data));
405 }
getConstantAttr(NumberExprAST & lit)406 mlir::DenseElementsAttr getConstantAttr(NumberExprAST &lit) {
407 // The type of this attribute is tensor of 64-bit floating-point with no
408 // shape.
409 mlir::Type elementType = builder.getF64Type();
410 auto dataType = mlir::RankedTensorType::get({}, elementType);
411
412 // This is the actual attribute that holds the list of values for this
413 // tensor literal.
414 return mlir::DenseElementsAttr::get(dataType,
415 llvm::makeArrayRef(lit.getValue()));
416 }
417 /// Emit a constant for a struct literal. It will be emitted as an array of
418 /// other literals in an Attribute attached to a `toy.struct_constant`
419 /// operation. This function returns the generated constant, along with the
420 /// corresponding struct type.
421 std::pair<mlir::ArrayAttr, mlir::Type>
getConstantAttr(StructLiteralExprAST & lit)422 getConstantAttr(StructLiteralExprAST &lit) {
423 std::vector<mlir::Attribute> attrElements;
424 std::vector<mlir::Type> typeElements;
425
426 for (auto &var : lit.getValues()) {
427 if (auto *number = llvm::dyn_cast<NumberExprAST>(var.get())) {
428 attrElements.push_back(getConstantAttr(*number));
429 typeElements.push_back(getType(llvm::None));
430 } else if (auto *lit = llvm::dyn_cast<LiteralExprAST>(var.get())) {
431 attrElements.push_back(getConstantAttr(*lit));
432 typeElements.push_back(getType(llvm::None));
433 } else {
434 auto *structLit = llvm::cast<StructLiteralExprAST>(var.get());
435 auto attrTypePair = getConstantAttr(*structLit);
436 attrElements.push_back(attrTypePair.first);
437 typeElements.push_back(attrTypePair.second);
438 }
439 }
440 mlir::ArrayAttr dataAttr = builder.getArrayAttr(attrElements);
441 mlir::Type dataType = StructType::get(typeElements);
442 return std::make_pair(dataAttr, dataType);
443 }
444
445 /// Emit an array literal.
mlirGen(LiteralExprAST & lit)446 mlir::Value mlirGen(LiteralExprAST &lit) {
447 mlir::Type type = getType(lit.getDims());
448 mlir::DenseElementsAttr dataAttribute = getConstantAttr(lit);
449
450 // Build the MLIR op `toy.constant`. This invokes the `ConstantOp::build`
451 // method.
452 return builder.create<ConstantOp>(loc(lit.loc()), type, dataAttribute);
453 }
454
455 /// Emit a struct literal. It will be emitted as an array of
456 /// other literals in an Attribute attached to a `toy.struct_constant`
457 /// operation.
mlirGen(StructLiteralExprAST & lit)458 mlir::Value mlirGen(StructLiteralExprAST &lit) {
459 mlir::ArrayAttr dataAttr;
460 mlir::Type dataType;
461 std::tie(dataAttr, dataType) = getConstantAttr(lit);
462
463 // Build the MLIR op `toy.struct_constant`. This invokes the
464 // `StructConstantOp::build` method.
465 return builder.create<StructConstantOp>(loc(lit.loc()), dataType, dataAttr);
466 }
467
468 /// Recursive helper function to accumulate the data that compose an array
469 /// literal. It flattens the nested structure in the supplied vector. For
470 /// example with this array:
471 /// [[1, 2], [3, 4]]
472 /// we will generate:
473 /// [ 1, 2, 3, 4 ]
474 /// Individual numbers are represented as doubles.
475 /// Attributes are the way MLIR attaches constant to operations.
collectData(ExprAST & expr,std::vector<double> & data)476 void collectData(ExprAST &expr, std::vector<double> &data) {
477 if (auto *lit = dyn_cast<LiteralExprAST>(&expr)) {
478 for (auto &value : lit->getValues())
479 collectData(*value, data);
480 return;
481 }
482
483 assert(isa<NumberExprAST>(expr) && "expected literal or number expr");
484 data.push_back(cast<NumberExprAST>(expr).getValue());
485 }
486
487 /// Emit a call expression. It emits specific operations for the `transpose`
488 /// builtin. Other identifiers are assumed to be user-defined functions.
mlirGen(CallExprAST & call)489 mlir::Value mlirGen(CallExprAST &call) {
490 llvm::StringRef callee = call.getCallee();
491 auto location = loc(call.loc());
492
493 // Codegen the operands first.
494 SmallVector<mlir::Value, 4> operands;
495 for (auto &expr : call.getArgs()) {
496 auto arg = mlirGen(*expr);
497 if (!arg)
498 return nullptr;
499 operands.push_back(arg);
500 }
501
502 // Builtin calls have their custom operation, meaning this is a
503 // straightforward emission.
504 if (callee == "transpose") {
505 if (call.getArgs().size() != 1) {
506 emitError(location, "MLIR codegen encountered an error: toy.transpose "
507 "does not accept multiple arguments");
508 return nullptr;
509 }
510 return builder.create<TransposeOp>(location, operands[0]);
511 }
512
513 // Otherwise this is a call to a user-defined function. Calls to
514 // user-defined functions are mapped to a custom call that takes the callee
515 // name as an attribute.
516 auto calledFuncIt = functionMap.find(callee);
517 if (calledFuncIt == functionMap.end()) {
518 emitError(location) << "no defined function found for '" << callee << "'";
519 return nullptr;
520 }
521 mlir::toy::FuncOp calledFunc = calledFuncIt->second;
522 return builder.create<GenericCallOp>(
523 location, calledFunc.getFunctionType().getResult(0),
524 mlir::SymbolRefAttr::get(builder.getContext(), callee), operands);
525 }
526
527 /// Emit a print expression. It emits specific operations for two builtins:
528 /// transpose(x) and print(x).
mlirGen(PrintExprAST & call)529 mlir::LogicalResult mlirGen(PrintExprAST &call) {
530 auto arg = mlirGen(*call.getArg());
531 if (!arg)
532 return mlir::failure();
533
534 builder.create<PrintOp>(loc(call.loc()), arg);
535 return mlir::success();
536 }
537
538 /// Emit a constant for a single number (FIXME: semantic? broadcast?)
mlirGen(NumberExprAST & num)539 mlir::Value mlirGen(NumberExprAST &num) {
540 return builder.create<ConstantOp>(loc(num.loc()), num.getValue());
541 }
542
543 /// Dispatch codegen for the right expression subclass using RTTI.
mlirGen(ExprAST & expr)544 mlir::Value mlirGen(ExprAST &expr) {
545 switch (expr.getKind()) {
546 case toy::ExprAST::Expr_BinOp:
547 return mlirGen(cast<BinaryExprAST>(expr));
548 case toy::ExprAST::Expr_Var:
549 return mlirGen(cast<VariableExprAST>(expr));
550 case toy::ExprAST::Expr_Literal:
551 return mlirGen(cast<LiteralExprAST>(expr));
552 case toy::ExprAST::Expr_StructLiteral:
553 return mlirGen(cast<StructLiteralExprAST>(expr));
554 case toy::ExprAST::Expr_Call:
555 return mlirGen(cast<CallExprAST>(expr));
556 case toy::ExprAST::Expr_Num:
557 return mlirGen(cast<NumberExprAST>(expr));
558 default:
559 emitError(loc(expr.loc()))
560 << "MLIR codegen encountered an unhandled expr kind '"
561 << Twine(expr.getKind()) << "'";
562 return nullptr;
563 }
564 }
565
566 /// Handle a variable declaration, we'll codegen the expression that forms the
567 /// initializer and record the value in the symbol table before returning it.
568 /// Future expressions will be able to reference this variable through symbol
569 /// table lookup.
mlirGen(VarDeclExprAST & vardecl)570 mlir::Value mlirGen(VarDeclExprAST &vardecl) {
571 auto *init = vardecl.getInitVal();
572 if (!init) {
573 emitError(loc(vardecl.loc()),
574 "missing initializer in variable declaration");
575 return nullptr;
576 }
577
578 mlir::Value value = mlirGen(*init);
579 if (!value)
580 return nullptr;
581
582 // Handle the case where we are initializing a struct value.
583 VarType varType = vardecl.getType();
584 if (!varType.name.empty()) {
585 // Check that the initializer type is the same as the variable
586 // declaration.
587 mlir::Type type = getType(varType, vardecl.loc());
588 if (!type)
589 return nullptr;
590 if (type != value.getType()) {
591 emitError(loc(vardecl.loc()))
592 << "struct type of initializer is different than the variable "
593 "declaration. Got "
594 << value.getType() << ", but expected " << type;
595 return nullptr;
596 }
597
598 // Otherwise, we have the initializer value, but in case the variable was
599 // declared with specific shape, we emit a "reshape" operation. It will
600 // get optimized out later as needed.
601 } else if (!varType.shape.empty()) {
602 value = builder.create<ReshapeOp>(loc(vardecl.loc()),
603 getType(varType.shape), value);
604 }
605
606 // Register the value in the symbol table.
607 if (failed(declare(vardecl, value)))
608 return nullptr;
609 return value;
610 }
611
612 /// Codegen a list of expression, return failure if one of them hit an error.
mlirGen(ExprASTList & blockAST)613 mlir::LogicalResult mlirGen(ExprASTList &blockAST) {
614 SymbolTableScopeT varScope(symbolTable);
615 for (auto &expr : blockAST) {
616 // Specific handling for variable declarations, return statement, and
617 // print. These can only appear in block list and not in nested
618 // expressions.
619 if (auto *vardecl = dyn_cast<VarDeclExprAST>(expr.get())) {
620 if (!mlirGen(*vardecl))
621 return mlir::failure();
622 continue;
623 }
624 if (auto *ret = dyn_cast<ReturnExprAST>(expr.get()))
625 return mlirGen(*ret);
626 if (auto *print = dyn_cast<PrintExprAST>(expr.get())) {
627 if (mlir::failed(mlirGen(*print)))
628 return mlir::success();
629 continue;
630 }
631
632 // Generic expression dispatch codegen.
633 if (!mlirGen(*expr))
634 return mlir::failure();
635 }
636 return mlir::success();
637 }
638
639 /// Build a tensor type from a list of shape dimensions.
getType(ArrayRef<int64_t> shape)640 mlir::Type getType(ArrayRef<int64_t> shape) {
641 // If the shape is empty, then this type is unranked.
642 if (shape.empty())
643 return mlir::UnrankedTensorType::get(builder.getF64Type());
644
645 // Otherwise, we use the given shape.
646 return mlir::RankedTensorType::get(shape, builder.getF64Type());
647 }
648
649 /// Build an MLIR type from a Toy AST variable type (forward to the generic
650 /// getType above for non-struct types).
getType(const VarType & type,const Location & location)651 mlir::Type getType(const VarType &type, const Location &location) {
652 if (!type.name.empty()) {
653 auto it = structMap.find(type.name);
654 if (it == structMap.end()) {
655 emitError(loc(location))
656 << "error: unknown struct type '" << type.name << "'";
657 return nullptr;
658 }
659 return it->second.first;
660 }
661
662 return getType(type.shape);
663 }
664 };
665
666 } // namespace
667
668 namespace toy {
669
670 // The public API for codegen.
mlirGen(mlir::MLIRContext & context,ModuleAST & moduleAST)671 mlir::OwningOpRef<mlir::ModuleOp> mlirGen(mlir::MLIRContext &context,
672 ModuleAST &moduleAST) {
673 return MLIRGenImpl(context).mlirGen(moduleAST);
674 }
675
676 } // namespace toy
677