blob: 8303f57b14033b1cdfeda686c1e5021fb6500418 [file] [log] [blame]
Chris Lattner4c95a502018-06-23 16:03:42 -07001//===- AsmPrinter.cpp - MLIR Assembly Printer Implementation --------------===//
2//
3// Copyright 2019 The MLIR Authors.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16// =============================================================================
17//
18// This file implements the MLIR AsmPrinter class, which is used to implement
19// the various print() methods on the core IR objects.
20//
21//===----------------------------------------------------------------------===//
22
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -070023#include "mlir/IR/AffineExpr.h"
24#include "mlir/IR/AffineMap.h"
Chris Lattner7121b802018-07-04 20:45:39 -070025#include "mlir/IR/Attributes.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070026#include "mlir/IR/CFGFunction.h"
Uday Bondhugulabc535622018-08-07 14:24:38 -070027#include "mlir/IR/IntegerSet.h"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070028#include "mlir/IR/MLFunction.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070029#include "mlir/IR/Module.h"
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070030#include "mlir/IR/OpImplementation.h"
Chris Lattnerff0d5902018-07-05 09:12:11 -070031#include "mlir/IR/OperationSet.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070032#include "mlir/IR/StandardOps.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070033#include "mlir/IR/Statements.h"
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -070034#include "mlir/IR/StmtVisitor.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070035#include "mlir/IR/Types.h"
36#include "mlir/Support/STLExtras.h"
Chris Lattner0497c4b2018-08-15 09:09:54 -070037#include "llvm/ADT/APFloat.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070038#include "llvm/ADT/DenseMap.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070039#include "llvm/ADT/SmallString.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/ADT/StringSet.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070042using namespace mlir;
43
MLIR Team54b55a22018-07-18 10:16:05 -070044void Identifier::print(raw_ostream &os) const { os << str(); }
Chris Lattner4c95a502018-06-23 16:03:42 -070045
MLIR Team54b55a22018-07-18 10:16:05 -070046void Identifier::dump() const { print(llvm::errs()); }
Chris Lattner7121b802018-07-04 20:45:39 -070047
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070048OpAsmPrinter::~OpAsmPrinter() {}
49
Chris Lattner4c95a502018-06-23 16:03:42 -070050//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -070051// ModuleState
MLIR Team4718bc92018-07-17 16:56:54 -070052//===----------------------------------------------------------------------===//
53
54namespace {
MLIR Team54b55a22018-07-18 10:16:05 -070055class ModuleState {
56public:
Chris Lattner4fd59b02018-07-20 09:35:47 -070057 /// This is the operation set for the current context if it is knowable (a
58 /// context could be determined), otherwise this is null.
59 OperationSet *const operationSet;
MLIR Team4718bc92018-07-17 16:56:54 -070060
Chris Lattner4fd59b02018-07-20 09:35:47 -070061 explicit ModuleState(MLIRContext *context)
62 : operationSet(context ? &OperationSet::get(context) : nullptr) {}
63
64 // Initializes module state, populating affine map state.
MLIR Team4718bc92018-07-17 16:56:54 -070065 void initialize(const Module *module);
66
MLIR Team54b55a22018-07-18 10:16:05 -070067 int getAffineMapId(const AffineMap *affineMap) const {
MLIR Team4718bc92018-07-17 16:56:54 -070068 auto it = affineMapIds.find(affineMap);
69 if (it == affineMapIds.end()) {
70 return -1;
71 }
72 return it->second;
73 }
74
James Molloyc4666722018-07-24 09:48:31 -070075 ArrayRef<const AffineMap *> getAffineMapIds() const { return affineMapsById; }
Chris Lattner4fd59b02018-07-20 09:35:47 -070076
Uday Bondhugulabc535622018-08-07 14:24:38 -070077 int getIntegerSetId(const IntegerSet *integerSet) const {
78 auto it = integerSetIds.find(integerSet);
79 if (it == integerSetIds.end()) {
80 return -1;
81 }
82 return it->second;
83 }
84
85 ArrayRef<const IntegerSet *> getIntegerSetIds() const {
86 return integerSetsById;
87 }
88
MLIR Team54b55a22018-07-18 10:16:05 -070089private:
Chris Lattner4fd59b02018-07-20 09:35:47 -070090 void recordAffineMapReference(const AffineMap *affineMap) {
91 if (affineMapIds.count(affineMap) == 0) {
James Molloyc4666722018-07-24 09:48:31 -070092 affineMapIds[affineMap] = affineMapsById.size();
93 affineMapsById.push_back(affineMap);
Chris Lattner4fd59b02018-07-20 09:35:47 -070094 }
95 }
96
Uday Bondhugulabc535622018-08-07 14:24:38 -070097 void recordIntegerSetReference(const IntegerSet *integerSet) {
98 if (integerSetIds.count(integerSet) == 0) {
99 integerSetIds[integerSet] = integerSetsById.size();
100 integerSetsById.push_back(integerSet);
101 }
102 }
103
MLIR Team4718bc92018-07-17 16:56:54 -0700104 // Visit functions.
105 void visitFunction(const Function *fn);
106 void visitExtFunction(const ExtFunction *fn);
107 void visitCFGFunction(const CFGFunction *fn);
108 void visitMLFunction(const MLFunction *fn);
Uday Bondhugulabc535622018-08-07 14:24:38 -0700109 void visitStatement(const Statement *stmt);
110 void visitForStmt(const ForStmt *forStmt);
111 void visitIfStmt(const IfStmt *ifStmt);
112 void visitOperationStmt(const OperationStmt *opStmt);
MLIR Team4718bc92018-07-17 16:56:54 -0700113 void visitType(const Type *type);
MLIR Teamb61885d2018-07-18 16:29:21 -0700114 void visitAttribute(const Attribute *attr);
115 void visitOperation(const Operation *op);
116
MLIR Team54b55a22018-07-18 10:16:05 -0700117 DenseMap<const AffineMap *, int> affineMapIds;
James Molloyc4666722018-07-24 09:48:31 -0700118 std::vector<const AffineMap *> affineMapsById;
Uday Bondhugulabc535622018-08-07 14:24:38 -0700119
120 DenseMap<const IntegerSet *, int> integerSetIds;
121 std::vector<const IntegerSet *> integerSetsById;
MLIR Team4718bc92018-07-17 16:56:54 -0700122};
James Molloy87d81022018-07-23 11:44:40 -0700123} // end anonymous namespace
MLIR Team4718bc92018-07-17 16:56:54 -0700124
125// TODO Support visiting other types/instructions when implemented.
126void ModuleState::visitType(const Type *type) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700127 if (auto *funcType = dyn_cast<FunctionType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700128 // Visit input and result types for functions.
Chris Lattner3164ae62018-07-28 09:36:25 -0700129 for (auto *input : funcType->getInputs())
MLIR Team4718bc92018-07-17 16:56:54 -0700130 visitType(input);
Chris Lattner3164ae62018-07-28 09:36:25 -0700131 for (auto *result : funcType->getResults())
MLIR Team4718bc92018-07-17 16:56:54 -0700132 visitType(result);
Chris Lattner3164ae62018-07-28 09:36:25 -0700133 } else if (auto *memref = dyn_cast<MemRefType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700134 // Visit affine maps in memref type.
Chris Lattner3164ae62018-07-28 09:36:25 -0700135 for (auto *map : memref->getAffineMaps()) {
MLIR Team4718bc92018-07-17 16:56:54 -0700136 recordAffineMapReference(map);
137 }
138 }
139}
140
MLIR Teamb61885d2018-07-18 16:29:21 -0700141void ModuleState::visitAttribute(const Attribute *attr) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700142 if (auto *mapAttr = dyn_cast<AffineMapAttr>(attr)) {
143 recordAffineMapReference(mapAttr->getValue());
Uday Bondhugulabc535622018-08-07 14:24:38 -0700144 } else if (auto *arrayAttr = dyn_cast<ArrayAttr>(attr)) {
145 for (auto elt : arrayAttr->getValue()) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700146 visitAttribute(elt);
147 }
148 }
149}
150
151void ModuleState::visitOperation(const Operation *op) {
Chris Lattnerca2ee872018-07-31 18:32:59 -0700152 // Visit all the types used in the operation.
153 for (auto *operand : op->getOperands())
154 visitType(operand->getType());
155 for (auto *result : op->getResults())
156 visitType(result->getType());
157
158 // Visit each of the attributes.
159 for (auto elt : op->getAttrs())
MLIR Teamb61885d2018-07-18 16:29:21 -0700160 visitAttribute(elt.second);
MLIR Teamb61885d2018-07-18 16:29:21 -0700161}
162
MLIR Team4718bc92018-07-17 16:56:54 -0700163void ModuleState::visitExtFunction(const ExtFunction *fn) {
164 visitType(fn->getType());
165}
166
167void ModuleState::visitCFGFunction(const CFGFunction *fn) {
168 visitType(fn->getType());
MLIR Teamb61885d2018-07-18 16:29:21 -0700169 for (auto &block : *fn) {
170 for (auto &op : block.getOperations()) {
171 visitOperation(&op);
172 }
173 }
MLIR Team4718bc92018-07-17 16:56:54 -0700174}
175
Uday Bondhugulabc535622018-08-07 14:24:38 -0700176void ModuleState::visitIfStmt(const IfStmt *ifStmt) {
177 recordIntegerSetReference(ifStmt->getCondition());
Chris Lattnere787b322018-08-08 11:14:57 -0700178 for (auto &childStmt : *ifStmt->getThen())
Uday Bondhugulabc535622018-08-07 14:24:38 -0700179 visitStatement(&childStmt);
Chris Lattnere787b322018-08-08 11:14:57 -0700180 if (ifStmt->hasElse())
181 for (auto &childStmt : *ifStmt->getElse())
Uday Bondhugulabc535622018-08-07 14:24:38 -0700182 visitStatement(&childStmt);
183}
184
185void ModuleState::visitForStmt(const ForStmt *forStmt) {
186 for (auto &childStmt : *forStmt)
187 visitStatement(&childStmt);
188}
189
190void ModuleState::visitOperationStmt(const OperationStmt *opStmt) {
Chris Lattner0497c4b2018-08-15 09:09:54 -0700191 for (auto attr : opStmt->getAttrs())
192 visitAttribute(attr.second);
Uday Bondhugulabc535622018-08-07 14:24:38 -0700193}
194
195void ModuleState::visitStatement(const Statement *stmt) {
196 switch (stmt->getKind()) {
197 case Statement::Kind::If:
198 return visitIfStmt(cast<IfStmt>(stmt));
199 case Statement::Kind::For:
200 return visitForStmt(cast<ForStmt>(stmt));
201 case Statement::Kind::Operation:
202 return visitOperationStmt(cast<OperationStmt>(stmt));
203 default:
204 return;
205 }
206}
207
MLIR Team4718bc92018-07-17 16:56:54 -0700208void ModuleState::visitMLFunction(const MLFunction *fn) {
209 visitType(fn->getType());
Uday Bondhugulabc535622018-08-07 14:24:38 -0700210 for (auto &stmt : *fn) {
211 ModuleState::visitStatement(&stmt);
212 }
MLIR Team4718bc92018-07-17 16:56:54 -0700213}
214
215void ModuleState::visitFunction(const Function *fn) {
216 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700217 case Function::Kind::ExtFunc:
218 return visitExtFunction(cast<ExtFunction>(fn));
219 case Function::Kind::CFGFunc:
220 return visitCFGFunction(cast<CFGFunction>(fn));
221 case Function::Kind::MLFunc:
222 return visitMLFunction(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700223 }
224}
225
Uday Bondhugulabc535622018-08-07 14:24:38 -0700226// Initializes module state, populating affine map and integer set state.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700227void ModuleState::initialize(const Module *module) {
Chris Lattnera8e47672018-07-25 14:08:16 -0700228 for (auto &fn : *module) {
229 visitFunction(&fn);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700230 }
231}
232
233//===----------------------------------------------------------------------===//
234// ModulePrinter
235//===----------------------------------------------------------------------===//
236
237namespace {
238class ModulePrinter {
239public:
240 ModulePrinter(raw_ostream &os, ModuleState &state) : os(os), state(state) {}
241 explicit ModulePrinter(const ModulePrinter &printer)
242 : os(printer.os), state(printer.state) {}
243
244 template <typename Container, typename UnaryFunctor>
245 inline void interleaveComma(const Container &c, UnaryFunctor each_fn) const {
246 interleave(c.begin(), c.end(), each_fn, [&]() { os << ", "; });
247 }
248
249 void print(const Module *module);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700250 void printAttribute(const Attribute *attr);
251 void printType(const Type *type);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700252 void print(const Function *fn);
253 void print(const ExtFunction *fn);
254 void print(const CFGFunction *fn);
255 void print(const MLFunction *fn);
256
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700257 void printAffineMap(const AffineMap *map);
258 void printAffineExpr(const AffineExpr *expr);
Uday Bondhugulabc535622018-08-07 14:24:38 -0700259 void printAffineConstraint(const AffineExpr *expr, bool isEq);
260 void printIntegerSet(const IntegerSet *set);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700261
262protected:
263 raw_ostream &os;
264 ModuleState &state;
265
266 void printFunctionSignature(const Function *fn);
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -0700267 void printFunctionResultType(const FunctionType *type);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700268 void printAffineMapId(int affineMapId) const;
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700269 void printAffineMapReference(const AffineMap *affineMap);
Uday Bondhugulabc535622018-08-07 14:24:38 -0700270 void printIntegerSetId(int integerSetId) const;
271 void printIntegerSetReference(const IntegerSet *integerSet);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700272
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700273 /// This enum is used to represent the binding stength of the enclosing
274 /// context that an AffineExpr is being printed in, so we can intelligently
275 /// produce parens.
276 enum class BindingStrength {
277 Weak, // + and -
278 Strong, // All other binary operators.
279 };
280 void printAffineExprInternal(const AffineExpr *expr,
281 BindingStrength enclosingTightness);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700282};
283} // end anonymous namespace
284
MLIR Team4718bc92018-07-17 16:56:54 -0700285// Prints function with initialized module state.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700286void ModulePrinter::print(const Function *fn) {
MLIR Team4718bc92018-07-17 16:56:54 -0700287 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700288 case Function::Kind::ExtFunc:
289 return print(cast<ExtFunction>(fn));
290 case Function::Kind::CFGFunc:
291 return print(cast<CFGFunction>(fn));
292 case Function::Kind::MLFunc:
293 return print(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700294 }
295}
296
297// Prints affine map identifier.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700298void ModulePrinter::printAffineMapId(int affineMapId) const {
MLIR Team4718bc92018-07-17 16:56:54 -0700299 os << "#map" << affineMapId;
300}
301
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700302void ModulePrinter::printAffineMapReference(const AffineMap *affineMap) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700303 int mapId = state.getAffineMapId(affineMap);
MLIR Teamb61885d2018-07-18 16:29:21 -0700304 if (mapId >= 0) {
305 // Map will be printed at top of module so print reference to its id.
306 printAffineMapId(mapId);
307 } else {
308 // Map not in module state so print inline.
309 affineMap->print(os);
310 }
311}
312
Uday Bondhugulabc535622018-08-07 14:24:38 -0700313// Prints integer set identifier.
314void ModulePrinter::printIntegerSetId(int integerSetId) const {
315 os << "@@set" << integerSetId;
316}
317
318void ModulePrinter::printIntegerSetReference(const IntegerSet *integerSet) {
319 int setId;
320 if ((setId = state.getIntegerSetId(integerSet)) >= 0) {
321 // The set will be printed at top of module; so print reference to its id.
322 printIntegerSetId(setId);
323 } else {
324 // Set not in module state so print inline.
325 integerSet->print(os);
326 }
327}
328
Chris Lattner4fd59b02018-07-20 09:35:47 -0700329void ModulePrinter::print(const Module *module) {
James Molloyc4666722018-07-24 09:48:31 -0700330 for (const auto &map : state.getAffineMapIds()) {
331 printAffineMapId(state.getAffineMapId(map));
MLIR Team4718bc92018-07-17 16:56:54 -0700332 os << " = ";
James Molloyc4666722018-07-24 09:48:31 -0700333 map->print(os);
MLIR Team4718bc92018-07-17 16:56:54 -0700334 os << '\n';
335 }
Uday Bondhugulabc535622018-08-07 14:24:38 -0700336 for (const auto &set : state.getIntegerSetIds()) {
337 printIntegerSetId(state.getIntegerSetId(set));
338 os << " = ";
339 set->print(os);
340 os << '\n';
341 }
Chris Lattnera8e47672018-07-25 14:08:16 -0700342 for (auto const &fn : *module)
343 print(&fn);
MLIR Team4718bc92018-07-17 16:56:54 -0700344}
345
Chris Lattner0497c4b2018-08-15 09:09:54 -0700346/// Print a floating point value in a way that the parser will be able to
347/// round-trip losslessly.
348static void printFloatValue(double value, raw_ostream &os) {
349 APFloat apValue(value);
350
351 // We would like to output the FP constant value in exponential notation,
352 // but we cannot do this if doing so will lose precision. Check here to
353 // make sure that we only output it in exponential format if we can parse
354 // the value back and get the same value.
355 bool isInf = apValue.isInfinity();
356 bool isNaN = apValue.isNaN();
357 if (!isInf && !isNaN) {
358 SmallString<128> strValue;
359 apValue.toString(strValue, 6, 0, false);
360
361 // Check to make sure that the stringized number is not some string like
362 // "Inf" or NaN, that atof will accept, but the lexer will not. Check
363 // that the string matches the "[-+]?[0-9]" regex.
364 assert(((strValue[0] >= '0' && strValue[0] <= '9') ||
365 ((strValue[0] == '-' || strValue[0] == '+') &&
366 (strValue[1] >= '0' && strValue[1] <= '9'))) &&
367 "[-+]?[0-9] regex does not match!");
368 // Reparse stringized version!
369 if (APFloat(APFloat::IEEEdouble(), strValue).convertToDouble() == value) {
370 os << strValue;
371 return;
372 }
373 }
374
375 // Otherwise, print it in a hexadecimal form. Convert it to an integer so we
376 // can print it out using integer math.
377 union {
378 double doubleValue;
379 uint64_t integerValue;
380 };
381 doubleValue = value;
382 os << "0x";
383 // Print out 16 nibbles worth of hex digit.
384 for (unsigned i = 0; i != 16; ++i) {
385 os << llvm::hexdigit(integerValue >> 60);
386 integerValue <<= 4;
387 }
388}
389
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700390void ModulePrinter::printAttribute(const Attribute *attr) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700391 switch (attr->getKind()) {
392 case Attribute::Kind::Bool:
393 os << (cast<BoolAttr>(attr)->getValue() ? "true" : "false");
394 break;
395 case Attribute::Kind::Integer:
396 os << cast<IntegerAttr>(attr)->getValue();
397 break;
398 case Attribute::Kind::Float:
Chris Lattner0497c4b2018-08-15 09:09:54 -0700399 printFloatValue(cast<FloatAttr>(attr)->getValue(), os);
MLIR Teamb61885d2018-07-18 16:29:21 -0700400 break;
401 case Attribute::Kind::String:
Chris Lattner0497c4b2018-08-15 09:09:54 -0700402 os << '"';
403 printEscapedString(cast<StringAttr>(attr)->getValue(), os);
404 os << '"';
MLIR Teamb61885d2018-07-18 16:29:21 -0700405 break;
Chris Lattner0497c4b2018-08-15 09:09:54 -0700406 case Attribute::Kind::Array:
MLIR Teamb61885d2018-07-18 16:29:21 -0700407 os << '[';
Chris Lattner0497c4b2018-08-15 09:09:54 -0700408 interleaveComma(cast<ArrayAttr>(attr)->getValue(),
409 [&](Attribute *attr) { printAttribute(attr); });
MLIR Teamb61885d2018-07-18 16:29:21 -0700410 os << ']';
411 break;
MLIR Teamb61885d2018-07-18 16:29:21 -0700412 case Attribute::Kind::AffineMap:
413 printAffineMapReference(cast<AffineMapAttr>(attr)->getValue());
414 break;
James Molloyf0d2f442018-08-03 01:54:46 -0700415 case Attribute::Kind::Type:
416 printType(cast<TypeAttr>(attr)->getValue());
417 break;
Chris Lattner4613d9e2018-08-19 21:17:22 -0700418 case Attribute::Kind::Function: {
419 auto *function = cast<FunctionAttr>(attr)->getValue();
420 if (!function) {
421 os << "<<FUNCTION ATTR FOR DELETED FUNCTION>>";
422 } else {
423 os << '@' << function->getName() << " : ";
424 printType(function->getType());
425 }
426 break;
427 }
MLIR Teamb61885d2018-07-18 16:29:21 -0700428 }
429}
430
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700431void ModulePrinter::printType(const Type *type) {
MLIR Team4718bc92018-07-17 16:56:54 -0700432 switch (type->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700433 case Type::Kind::AffineInt:
434 os << "affineint";
435 return;
436 case Type::Kind::BF16:
437 os << "bf16";
438 return;
439 case Type::Kind::F16:
440 os << "f16";
441 return;
442 case Type::Kind::F32:
443 os << "f32";
444 return;
445 case Type::Kind::F64:
446 os << "f64";
447 return;
Jacques Pienaarc0d69302018-07-27 11:07:12 -0700448 case Type::Kind::TFControl:
449 os << "tf_control";
450 return;
James Molloy72b0cbe2018-08-01 12:55:27 -0700451 case Type::Kind::TFString:
452 os << "tf_string";
453 return;
MLIR Team4718bc92018-07-17 16:56:54 -0700454
455 case Type::Kind::Integer: {
456 auto *integer = cast<IntegerType>(type);
457 os << 'i' << integer->getWidth();
458 return;
459 }
460 case Type::Kind::Function: {
461 auto *func = cast<FunctionType>(type);
462 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700463 interleaveComma(func->getInputs(), [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700464 os << ") -> ";
465 auto results = func->getResults();
466 if (results.size() == 1)
467 os << *results[0];
468 else {
469 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700470 interleaveComma(results, [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700471 os << ')';
472 }
473 return;
474 }
475 case Type::Kind::Vector: {
476 auto *v = cast<VectorType>(type);
477 os << "vector<";
James Molloy87d81022018-07-23 11:44:40 -0700478 for (auto dim : v->getShape())
479 os << dim << 'x';
MLIR Team4718bc92018-07-17 16:56:54 -0700480 os << *v->getElementType() << '>';
481 return;
482 }
483 case Type::Kind::RankedTensor: {
484 auto *v = cast<RankedTensorType>(type);
485 os << "tensor<";
486 for (auto dim : v->getShape()) {
487 if (dim < 0)
488 os << '?';
489 else
490 os << dim;
491 os << 'x';
492 }
493 os << *v->getElementType() << '>';
494 return;
495 }
496 case Type::Kind::UnrankedTensor: {
497 auto *v = cast<UnrankedTensorType>(type);
Chris Lattner413db6a2018-07-25 12:55:50 -0700498 os << "tensor<??";
499 printType(v->getElementType());
500 os << '>';
MLIR Team4718bc92018-07-17 16:56:54 -0700501 return;
502 }
503 case Type::Kind::MemRef: {
504 auto *v = cast<MemRefType>(type);
505 os << "memref<";
506 for (auto dim : v->getShape()) {
507 if (dim < 0)
508 os << '?';
509 else
510 os << dim;
511 os << 'x';
512 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700513 printType(v->getElementType());
MLIR Team4718bc92018-07-17 16:56:54 -0700514 for (auto map : v->getAffineMaps()) {
515 os << ", ";
MLIR Teamb61885d2018-07-18 16:29:21 -0700516 printAffineMapReference(map);
MLIR Team4718bc92018-07-17 16:56:54 -0700517 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700518 // Only print the memory space if it is the non-default one.
519 if (v->getMemorySpace())
520 os << ", " << v->getMemorySpace();
MLIR Team4718bc92018-07-17 16:56:54 -0700521 os << '>';
522 return;
523 }
524 }
525}
526
527//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -0700528// Affine expressions and maps
529//===----------------------------------------------------------------------===//
530
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700531void ModulePrinter::printAffineExpr(const AffineExpr *expr) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700532 printAffineExprInternal(expr, BindingStrength::Weak);
533}
534
535void ModulePrinter::printAffineExprInternal(
536 const AffineExpr *expr, BindingStrength enclosingTightness) {
537 const char *binopSpelling = nullptr;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700538 switch (expr->getKind()) {
539 case AffineExpr::Kind::SymbolId:
540 os << 's' << cast<AffineSymbolExpr>(expr)->getPosition();
541 return;
542 case AffineExpr::Kind::DimId:
543 os << 'd' << cast<AffineDimExpr>(expr)->getPosition();
544 return;
545 case AffineExpr::Kind::Constant:
546 os << cast<AffineConstantExpr>(expr)->getValue();
547 return;
548 case AffineExpr::Kind::Add:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700549 binopSpelling = " + ";
550 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700551 case AffineExpr::Kind::Mul:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700552 binopSpelling = " * ";
553 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700554 case AffineExpr::Kind::FloorDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700555 binopSpelling = " floordiv ";
556 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700557 case AffineExpr::Kind::CeilDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700558 binopSpelling = " ceildiv ";
559 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700560 case AffineExpr::Kind::Mod:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700561 binopSpelling = " mod ";
562 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700563 }
Chris Lattner4fd59b02018-07-20 09:35:47 -0700564
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700565 auto *binOp = cast<AffineBinaryOpExpr>(expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700566
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700567 // Handle tightly binding binary operators.
568 if (binOp->getKind() != AffineExpr::Kind::Add) {
569 if (enclosingTightness == BindingStrength::Strong)
570 os << '(';
571
572 printAffineExprInternal(binOp->getLHS(), BindingStrength::Strong);
573 os << binopSpelling;
574 printAffineExprInternal(binOp->getRHS(), BindingStrength::Strong);
575
576 if (enclosingTightness == BindingStrength::Strong)
577 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700578 return;
579 }
580
581 // Print out special "pretty" forms for add.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700582 if (enclosingTightness == BindingStrength::Strong)
583 os << '(';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700584
585 // Pretty print addition to a product that has a negative operand as a
586 // subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700587 if (auto *rhs = dyn_cast<AffineBinaryOpExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700588 if (rhs->getKind() == AffineExpr::Kind::Mul) {
589 if (auto *rrhs = dyn_cast<AffineConstantExpr>(rhs->getRHS())) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700590 if (rrhs->getValue() == -1) {
591 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
592 os << " - ";
593 printAffineExprInternal(rhs->getLHS(), BindingStrength::Weak);
594
595 if (enclosingTightness == BindingStrength::Strong)
596 os << ')';
597 return;
598 }
599
600 if (rrhs->getValue() < -1) {
601 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700602 os << " - ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700603 printAffineExprInternal(rhs->getLHS(), BindingStrength::Strong);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700604 os << " * " << -rrhs->getValue();
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700605 if (enclosingTightness == BindingStrength::Strong)
606 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700607 return;
608 }
609 }
610 }
611 }
612
613 // Pretty print addition to a negative number as a subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700614 if (auto *rhs = dyn_cast<AffineConstantExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700615 if (rhs->getValue() < 0) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700616 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Uday Bondhugulabc535622018-08-07 14:24:38 -0700617 os << " - " << -rhs->getValue();
618 if (enclosingTightness == BindingStrength::Strong)
619 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700620 return;
621 }
622 }
623
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700624 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700625 os << " + ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700626 printAffineExprInternal(binOp->getRHS(), BindingStrength::Weak);
627
628 if (enclosingTightness == BindingStrength::Strong)
629 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700630}
631
Uday Bondhugulabc535622018-08-07 14:24:38 -0700632void ModulePrinter::printAffineConstraint(const AffineExpr *expr, bool isEq) {
633 printAffineExprInternal(expr, BindingStrength::Weak);
634 isEq ? os << " == 0" : os << " >= 0";
635}
636
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700637void ModulePrinter::printAffineMap(const AffineMap *map) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700638 // Dimension identifiers.
639 os << '(';
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700640 for (int i = 0; i < (int)map->getNumDims() - 1; ++i)
641 os << 'd' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700642 if (map->getNumDims() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700643 os << 'd' << map->getNumDims() - 1;
644 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700645
646 // Symbolic identifiers.
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700647 if (map->getNumSymbols() != 0) {
648 os << '[';
649 for (unsigned i = 0; i < map->getNumSymbols() - 1; ++i)
650 os << 's' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700651 if (map->getNumSymbols() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700652 os << 's' << map->getNumSymbols() - 1;
653 os << ']';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700654 }
655
656 // AffineMap should have at least one result.
657 assert(!map->getResults().empty());
658 // Result affine expressions.
659 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700660 interleaveComma(map->getResults(),
661 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700662 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700663
664 if (!map->isBounded()) {
665 return;
666 }
667
668 // Print range sizes for bounded affine maps.
669 os << " size (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700670 interleaveComma(map->getRangeSizes(),
671 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700672 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700673}
674
Uday Bondhugulabc535622018-08-07 14:24:38 -0700675void ModulePrinter::printIntegerSet(const IntegerSet *set) {
676 // Dimension identifiers.
677 os << '(';
678 for (unsigned i = 1; i < set->getNumDims(); ++i)
679 os << 'd' << i - 1 << ", ";
680 if (set->getNumDims() >= 1)
681 os << 'd' << set->getNumDims() - 1;
682 os << ')';
683
684 // Symbolic identifiers.
685 if (set->getNumSymbols() != 0) {
686 os << '[';
687 for (unsigned i = 0; i < set->getNumSymbols() - 1; ++i)
688 os << 's' << i << ", ";
689 if (set->getNumSymbols() >= 1)
690 os << 's' << set->getNumSymbols() - 1;
691 os << ']';
692 }
693
694 // Print constraints.
695 os << " : (";
696 auto numConstraints = set->getNumConstraints();
697 for (int i = 1; i < numConstraints; ++i) {
698 printAffineConstraint(set->getConstraint(i - 1), set->isEq(i - 1));
699 os << ", ";
700 }
701 if (numConstraints >= 1)
702 printAffineConstraint(set->getConstraint(numConstraints - 1),
703 set->isEq(numConstraints - 1));
704 os << ')';
705}
706
Chris Lattner4fd59b02018-07-20 09:35:47 -0700707//===----------------------------------------------------------------------===//
Chris Lattner4c95a502018-06-23 16:03:42 -0700708// Function printing
709//===----------------------------------------------------------------------===//
710
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -0700711void ModulePrinter::printFunctionResultType(const FunctionType *type) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700712 switch (type->getResults().size()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700713 case 0:
714 break;
Chris Lattner4c95a502018-06-23 16:03:42 -0700715 case 1:
MLIR Team4718bc92018-07-17 16:56:54 -0700716 os << " -> ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700717 printType(type->getResults()[0]);
Chris Lattner4c95a502018-06-23 16:03:42 -0700718 break;
719 default:
720 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700721 interleaveComma(type->getResults(),
722 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700723 os << ')';
724 break;
725 }
726}
727
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -0700728void ModulePrinter::printFunctionSignature(const Function *fn) {
729 auto type = fn->getType();
730
731 os << "@" << fn->getName() << '(';
732 interleaveComma(type->getInputs(),
733 [&](Type *eltType) { printType(eltType); });
734 os << ')';
735
736 printFunctionResultType(type);
737}
738
Chris Lattner4fd59b02018-07-20 09:35:47 -0700739void ModulePrinter::print(const ExtFunction *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700740 os << "extfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700741 printFunctionSignature(fn);
MLIR Team54b55a22018-07-18 10:16:05 -0700742 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700743}
744
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700745namespace {
746
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700747// FunctionPrinter contains common functionality for printing
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700748// CFG and ML functions.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700749class FunctionPrinter : public ModulePrinter, private OpAsmPrinter {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700750public:
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700751 FunctionPrinter(const ModulePrinter &other) : ModulePrinter(other) {}
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700752
753 void printOperation(const Operation *op);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700754 void printDefaultOp(const Operation *op);
755
756 // Implement OpAsmPrinter.
757 raw_ostream &getStream() const { return os; }
758 void printType(const Type *type) { ModulePrinter::printType(type); }
759 void printAttribute(const Attribute *attr) {
760 ModulePrinter::printAttribute(attr);
761 }
762 void printAffineMap(const AffineMap *map) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700763 return ModulePrinter::printAffineMapReference(map);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700764 }
Uday Bondhugulabc535622018-08-07 14:24:38 -0700765 void printIntegerSet(const IntegerSet *set) {
766 return ModulePrinter::printIntegerSetReference(set);
767 }
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700768 void printAffineExpr(const AffineExpr *expr) {
769 return ModulePrinter::printAffineExpr(expr);
770 }
771
772 void printOperand(const SSAValue *value) { printValueID(value); }
Tatiana Shpeismanc335d182018-08-03 11:12:34 -0700773
Chris Lattner85cf26d2018-08-02 16:54:36 -0700774 void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
775 ArrayRef<const char *> elidedAttrs = {}) override;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700776
Chris Lattnerd4964212018-08-01 10:43:18 -0700777 enum { nameSentinel = ~0U };
778
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700779protected:
Chris Lattnerf8cce872018-07-20 09:28:54 -0700780 void numberValueID(const SSAValue *value) {
781 assert(!valueIDs.count(value) && "Value numbered multiple times");
Chris Lattnerd4964212018-08-01 10:43:18 -0700782
783 SmallString<32> specialNameBuffer;
784 llvm::raw_svector_ostream specialName(specialNameBuffer);
785
786 // Give constant integers special names.
787 if (auto *op = value->getDefiningOperation()) {
788 if (auto intOp = op->getAs<ConstantIntOp>()) {
Chris Lattner384da8c2018-08-02 17:16:58 -0700789 // i1 constants get special names.
790 if (intOp->getType()->isInteger(1)) {
791 specialName << (intOp->getValue() ? "true" : "false");
792 } else {
Chris Lattner992a1272018-08-07 12:02:37 -0700793 specialName << 'c' << intOp->getValue() << '_' << *intOp->getType();
Chris Lattner384da8c2018-08-02 17:16:58 -0700794 }
Chris Lattner992a1272018-08-07 12:02:37 -0700795 } else if (auto intOp = op->getAs<ConstantAffineIntOp>()) {
796 specialName << 'c' << intOp->getValue();
Chris Lattner4613d9e2018-08-19 21:17:22 -0700797 } else if (auto constant = op->getAs<ConstantOp>()) {
798 if (isa<FunctionAttr>(constant->getValue()))
799 specialName << 'f';
800 else
801 specialName << "cst";
Chris Lattnerd4964212018-08-01 10:43:18 -0700802 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700803 }
Chris Lattnerd4964212018-08-01 10:43:18 -0700804
805 if (specialNameBuffer.empty()) {
806 switch (value->getKind()) {
807 case SSAValueKind::BBArgument:
808 // If this is an argument to the function, give it an 'arg' name.
809 if (auto *bb = cast<BBArgument>(value)->getOwner())
810 if (auto *fn = bb->getFunction())
811 if (&fn->front() == bb) {
812 specialName << "arg" << nextArgumentID++;
813 break;
814 }
815 // Otherwise number it normally.
816 LLVM_FALLTHROUGH;
817 case SSAValueKind::InstResult:
818 case SSAValueKind::StmtResult:
819 // This is an uninteresting result, give it a boring number and be
820 // done with it.
821 valueIDs[value] = nextValueID++;
822 return;
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -0700823 case SSAValueKind::MLFuncArgument:
Chris Lattnerd4964212018-08-01 10:43:18 -0700824 specialName << "arg" << nextArgumentID++;
825 break;
826 case SSAValueKind::ForStmt:
827 specialName << 'i' << nextLoopID++;
828 break;
829 }
830 }
831
832 // Ok, this value had an interesting name. Remember it with a sentinel.
833 valueIDs[value] = nameSentinel;
834
835 // Remember that we've used this name, checking to see if we had a conflict.
836 auto insertRes = usedNames.insert(specialName.str());
837 if (insertRes.second) {
838 // If this is the first use of the name, then we're successful!
839 valueNames[value] = insertRes.first->first();
840 return;
841 }
842
843 // Otherwise, we had a conflict - probe until we find a unique name. This
844 // is guaranteed to terminate (and usually in a single iteration) because it
845 // generates new names by incrementing nextConflictID.
846 while (1) {
847 std::string probeName =
848 specialName.str().str() + "_" + llvm::utostr(nextConflictID++);
849 insertRes = usedNames.insert(probeName);
850 if (insertRes.second) {
851 // If this is the first use of the name, then we're successful!
852 valueNames[value] = insertRes.first->first();
853 return;
854 }
855 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700856 }
857
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700858 void printValueID(const SSAValue *value, bool printResultNo = true) const {
Chris Lattner6119d382018-07-20 18:41:34 -0700859 int resultNo = -1;
860 auto lookupValue = value;
861
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700862 // If this is a reference to the result of a multi-result instruction or
863 // statement, print out the # identifier and make sure to map our lookup
864 // to the first result of the instruction.
Chris Lattner6119d382018-07-20 18:41:34 -0700865 if (auto *result = dyn_cast<InstResult>(value)) {
866 if (result->getOwner()->getNumResults() != 1) {
867 resultNo = result->getResultNumber();
868 lookupValue = result->getOwner()->getResult(0);
869 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700870 } else if (auto *result = dyn_cast<StmtResult>(value)) {
871 if (result->getOwner()->getNumResults() != 1) {
872 resultNo = result->getResultNumber();
873 lookupValue = result->getOwner()->getResult(0);
874 }
Chris Lattner6119d382018-07-20 18:41:34 -0700875 }
876
877 auto it = valueIDs.find(lookupValue);
878 if (it == valueIDs.end()) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700879 os << "<<INVALID SSA VALUE>>";
Chris Lattner6119d382018-07-20 18:41:34 -0700880 return;
881 }
882
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700883 os << '%';
Chris Lattnerd4964212018-08-01 10:43:18 -0700884 if (it->second != nameSentinel) {
885 os << it->second;
886 } else {
887 auto nameIt = valueNames.find(lookupValue);
888 assert(nameIt != valueNames.end() && "Didn't have a name entry?");
889 os << nameIt->second;
890 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700891
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700892 if (resultNo != -1 && printResultNo)
Chris Lattner6119d382018-07-20 18:41:34 -0700893 os << '#' << resultNo;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700894 }
895
896private:
Chris Lattnerd4964212018-08-01 10:43:18 -0700897 /// This is the value ID for each SSA value in the current function. If this
898 /// returns ~0, then the valueID has an entry in valueNames.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700899 DenseMap<const SSAValue *, unsigned> valueIDs;
Chris Lattnerd4964212018-08-01 10:43:18 -0700900 DenseMap<const SSAValue *, StringRef> valueNames;
901
902 /// This keeps track of all of the non-numeric names that are in flight,
903 /// allowing us to check for duplicates.
904 llvm::StringSet<> usedNames;
905
906 /// This is the next value ID to assign in numbering.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700907 unsigned nextValueID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700908 /// This is the ID to assign to the next induction variable.
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -0700909 unsigned nextLoopID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700910 /// This is the next ID to assign to an MLFunction argument.
911 unsigned nextArgumentID = 0;
912
913 /// This is the next ID to assign when a name conflict is detected.
914 unsigned nextConflictID = 0;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700915};
James Molloy87d81022018-07-23 11:44:40 -0700916} // end anonymous namespace
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700917
Chris Lattner85cf26d2018-08-02 16:54:36 -0700918void FunctionPrinter::printOptionalAttrDict(
919 ArrayRef<NamedAttribute> attrs, ArrayRef<const char *> elidedAttrs) {
920 // If there are no attributes, then there is nothing to be done.
921 if (attrs.empty())
922 return;
923
924 // Filter out any attributes that shouldn't be included.
925 SmallVector<NamedAttribute, 8> filteredAttrs;
926 for (auto attr : attrs) {
Chris Lattner4613d9e2018-08-19 21:17:22 -0700927 auto attrName = attr.first.strref();
Chris Lattner85cf26d2018-08-02 16:54:36 -0700928 // Never print attributes that start with a colon. These are internal
929 // attributes that represent location or other internal metadata.
930 if (attrName.startswith(":"))
931 continue;
932
933 // If the caller has requested that this attribute be ignored, then drop it.
934 bool ignore = false;
935 for (const char *elide : elidedAttrs)
936 ignore |= attrName == StringRef(elide);
937
938 // Otherwise add it to our filteredAttrs list.
939 if (!ignore)
940 filteredAttrs.push_back(attr);
941 }
942
943 // If there are no attributes left to print after filtering, then we're done.
944 if (filteredAttrs.empty())
945 return;
946
947 // Otherwise, print them all out in braces.
948 os << " {";
949 interleaveComma(filteredAttrs, [&](NamedAttribute attr) {
950 os << attr.first << ": ";
951 printAttribute(attr.second);
952 });
953 os << '}';
954}
955
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700956void FunctionPrinter::printOperation(const Operation *op) {
Chris Lattnerac591f12018-07-22 21:02:26 -0700957 if (op->getNumResults()) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700958 printValueID(op->getResult(0), /*printResultNo=*/false);
Chris Lattnerac591f12018-07-22 21:02:26 -0700959 os << " = ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700960 }
961
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700962 // Check to see if this is a known operation. If so, use the registered
963 // custom printer hook.
Chris Lattner4613d9e2018-08-19 21:17:22 -0700964 if (auto *opInfo = state.operationSet->lookup(op->getName())) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700965 opInfo->printAssembly(op, this);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700966 return;
967 }
968
Chris Lattnerf8cce872018-07-20 09:28:54 -0700969 // Otherwise use the standard verbose printing approach.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700970 printDefaultOp(op);
971}
Chris Lattnerf8cce872018-07-20 09:28:54 -0700972
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700973void FunctionPrinter::printDefaultOp(const Operation *op) {
Chris Lattner0497c4b2018-08-15 09:09:54 -0700974 os << '"';
Chris Lattner4613d9e2018-08-19 21:17:22 -0700975 printEscapedString(op->getName(), os);
Chris Lattner0497c4b2018-08-15 09:09:54 -0700976 os << "\"(";
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700977
Chris Lattnerac591f12018-07-22 21:02:26 -0700978 interleaveComma(op->getOperands(),
979 [&](const SSAValue *value) { printValueID(value); });
Chris Lattner7f9cc272018-07-19 08:35:28 -0700980
Chris Lattnerf8cce872018-07-20 09:28:54 -0700981 os << ')';
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700982 auto attrs = op->getAttrs();
Chris Lattner85cf26d2018-08-02 16:54:36 -0700983 printOptionalAttrDict(attrs);
Chris Lattner3b2ef762018-07-18 15:31:25 -0700984
Chris Lattnerac591f12018-07-22 21:02:26 -0700985 // Print the type signature of the operation.
986 os << " : (";
987 interleaveComma(op->getOperands(),
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700988 [&](const SSAValue *value) { printType(value->getType()); });
Chris Lattnerac591f12018-07-22 21:02:26 -0700989 os << ") -> ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700990
Chris Lattnerac591f12018-07-22 21:02:26 -0700991 if (op->getNumResults() == 1) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700992 printType(op->getResult(0)->getType());
Chris Lattnerac591f12018-07-22 21:02:26 -0700993 } else {
994 os << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700995 interleaveComma(op->getResults(), [&](const SSAValue *result) {
996 printType(result->getType());
997 });
Chris Lattnerac591f12018-07-22 21:02:26 -0700998 os << ')';
Chris Lattnerf8cce872018-07-20 09:28:54 -0700999 }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -07001000}
1001
Chris Lattner4c95a502018-06-23 16:03:42 -07001002//===----------------------------------------------------------------------===//
1003// CFG Function printing
1004//===----------------------------------------------------------------------===//
1005
1006namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001007class CFGFunctionPrinter : public FunctionPrinter {
Chris Lattner4c95a502018-06-23 16:03:42 -07001008public:
Chris Lattner4fd59b02018-07-20 09:35:47 -07001009 CFGFunctionPrinter(const CFGFunction *function, const ModulePrinter &other);
Chris Lattner4c95a502018-06-23 16:03:42 -07001010
1011 const CFGFunction *getFunction() const { return function; }
1012
1013 void print();
1014 void print(const BasicBlock *block);
Chris Lattnered65a732018-06-28 20:45:33 -07001015
1016 void print(const Instruction *inst);
1017 void print(const OperationInst *inst);
1018 void print(const ReturnInst *inst);
1019 void print(const BranchInst *inst);
James Molloy4f788372018-07-24 15:01:27 -07001020 void print(const CondBranchInst *inst);
Chris Lattner4c95a502018-06-23 16:03:42 -07001021
1022 unsigned getBBID(const BasicBlock *block) {
1023 auto it = basicBlockIDs.find(block);
1024 assert(it != basicBlockIDs.end() && "Block not in this function?");
1025 return it->second;
1026 }
1027
1028private:
1029 const CFGFunction *function;
MLIR Team54b55a22018-07-18 10:16:05 -07001030 DenseMap<const BasicBlock *, unsigned> basicBlockIDs;
Chris Lattnerf8cce872018-07-20 09:28:54 -07001031
Chris Lattner4fd59b02018-07-20 09:35:47 -07001032 void numberValuesInBlock(const BasicBlock *block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001033};
James Molloy87d81022018-07-23 11:44:40 -07001034} // end anonymous namespace
Chris Lattner4c95a502018-06-23 16:03:42 -07001035
Chris Lattner4fd59b02018-07-20 09:35:47 -07001036CFGFunctionPrinter::CFGFunctionPrinter(const CFGFunction *function,
1037 const ModulePrinter &other)
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001038 : FunctionPrinter(other), function(function) {
Chris Lattner4c95a502018-06-23 16:03:42 -07001039 // Each basic block gets a unique ID per function.
1040 unsigned blockID = 0;
Chris Lattnerf8cce872018-07-20 09:28:54 -07001041 for (auto &block : *function) {
1042 basicBlockIDs[&block] = blockID++;
Chris Lattner4fd59b02018-07-20 09:35:47 -07001043 numberValuesInBlock(&block);
Chris Lattnerf8cce872018-07-20 09:28:54 -07001044 }
1045}
1046
1047/// Number all of the SSA values in the specified basic block.
Chris Lattner4fd59b02018-07-20 09:35:47 -07001048void CFGFunctionPrinter::numberValuesInBlock(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -07001049 for (auto *arg : block->getArguments()) {
1050 numberValueID(arg);
1051 }
Chris Lattnerf8cce872018-07-20 09:28:54 -07001052 for (auto &op : *block) {
1053 // We number instruction that have results, and we only number the first
1054 // result.
1055 if (op.getNumResults() != 0)
1056 numberValueID(op.getResult(0));
1057 }
1058
1059 // Terminators do not define values.
Chris Lattner4c95a502018-06-23 16:03:42 -07001060}
1061
Chris Lattner4fd59b02018-07-20 09:35:47 -07001062void CFGFunctionPrinter::print() {
Chris Lattner4c95a502018-06-23 16:03:42 -07001063 os << "cfgfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -07001064 printFunctionSignature(getFunction());
Chris Lattner4c95a502018-06-23 16:03:42 -07001065 os << " {\n";
1066
James Molloy87d81022018-07-23 11:44:40 -07001067 for (auto &block : *function)
1068 print(&block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001069 os << "}\n\n";
1070}
1071
Chris Lattner4fd59b02018-07-20 09:35:47 -07001072void CFGFunctionPrinter::print(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -07001073 os << "bb" << getBBID(block);
Chris Lattner4c95a502018-06-23 16:03:42 -07001074
James Molloy61a656c2018-07-22 15:45:24 -07001075 if (!block->args_empty()) {
1076 os << '(';
1077 interleaveComma(block->getArguments(), [&](const BBArgument *arg) {
1078 printValueID(arg);
1079 os << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001080 printType(arg->getType());
James Molloy61a656c2018-07-22 15:45:24 -07001081 });
1082 os << ')';
1083 }
Chris Lattner25ce3062018-07-27 11:10:12 -07001084 os << ':';
1085
1086 // Print out some context information about the predecessors of this block.
1087 if (!block->getFunction()) {
1088 os << "\t// block is not in a function!";
1089 } else if (block->hasNoPredecessors()) {
1090 // Don't print "no predecessors" for the entry block.
1091 if (block != &block->getFunction()->front())
1092 os << "\t// no predecessors";
1093 } else if (auto *pred = block->getSinglePredecessor()) {
1094 os << "\t// pred: bb" << getBBID(pred);
1095 } else {
1096 // We want to print the predecessors in increasing numeric order, not in
1097 // whatever order the use-list is in, so gather and sort them.
1098 SmallVector<unsigned, 4> predIDs;
1099 for (auto *pred : block->getPredecessors())
1100 predIDs.push_back(getBBID(pred));
1101 llvm::array_pod_sort(predIDs.begin(), predIDs.end());
1102
1103 os << "\t// " << predIDs.size() << " preds: ";
1104
1105 interleaveComma(predIDs, [&](unsigned predID) { os << "bb" << predID; });
1106 }
1107 os << '\n';
James Molloy61a656c2018-07-22 15:45:24 -07001108
Jacques Pienaarb020c542018-07-15 00:06:54 -07001109 for (auto &inst : block->getOperations()) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001110 os << " ";
Chris Lattner3a467cc2018-07-01 20:28:00 -07001111 print(&inst);
James Molloy61a656c2018-07-22 15:45:24 -07001112 os << '\n';
Jacques Pienaarb020c542018-07-15 00:06:54 -07001113 }
Chris Lattner4c95a502018-06-23 16:03:42 -07001114
James Molloy6e4519b2018-08-03 03:51:38 -07001115 os << " ";
Chris Lattner4c95a502018-06-23 16:03:42 -07001116 print(block->getTerminator());
James Molloy61a656c2018-07-22 15:45:24 -07001117 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -07001118}
1119
Chris Lattner4fd59b02018-07-20 09:35:47 -07001120void CFGFunctionPrinter::print(const Instruction *inst) {
Chris Lattner4c95a502018-06-23 16:03:42 -07001121 switch (inst->getKind()) {
Chris Lattnered65a732018-06-28 20:45:33 -07001122 case Instruction::Kind::Operation:
1123 return print(cast<OperationInst>(inst));
Chris Lattnerf6d80a02018-06-24 11:18:29 -07001124 case TerminatorInst::Kind::Branch:
Chris Lattnered65a732018-06-28 20:45:33 -07001125 return print(cast<BranchInst>(inst));
James Molloy4f788372018-07-24 15:01:27 -07001126 case TerminatorInst::Kind::CondBranch:
1127 return print(cast<CondBranchInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -07001128 case TerminatorInst::Kind::Return:
Chris Lattnered65a732018-06-28 20:45:33 -07001129 return print(cast<ReturnInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -07001130 }
1131}
1132
Chris Lattner4fd59b02018-07-20 09:35:47 -07001133void CFGFunctionPrinter::print(const OperationInst *inst) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -07001134 printOperation(inst);
Chris Lattner3b2ef762018-07-18 15:31:25 -07001135}
Chris Lattner1604e472018-07-23 08:42:19 -07001136
Chris Lattner4fd59b02018-07-20 09:35:47 -07001137void CFGFunctionPrinter::print(const BranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001138 os << "br bb" << getBBID(inst->getDest());
Chris Lattner1604e472018-07-23 08:42:19 -07001139
1140 if (inst->getNumOperands() != 0) {
1141 os << '(';
Chris Lattner0497c4b2018-08-15 09:09:54 -07001142 interleaveComma(inst->getOperands(),
1143 [&](const CFGValue *operand) { printValueID(operand); });
Chris Lattner1604e472018-07-23 08:42:19 -07001144 os << ") : ";
Chris Lattner0497c4b2018-08-15 09:09:54 -07001145 interleaveComma(inst->getOperands(), [&](const CFGValue *operand) {
1146 printType(operand->getType());
Chris Lattner1604e472018-07-23 08:42:19 -07001147 });
1148 }
Chris Lattnered65a732018-06-28 20:45:33 -07001149}
Chris Lattner1604e472018-07-23 08:42:19 -07001150
James Molloy4f788372018-07-24 15:01:27 -07001151void CFGFunctionPrinter::print(const CondBranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001152 os << "cond_br ";
James Molloy4f788372018-07-24 15:01:27 -07001153 printValueID(inst->getCondition());
1154
1155 os << ", bb" << getBBID(inst->getTrueDest());
1156 if (inst->getNumTrueOperands() != 0) {
1157 os << '(';
1158 interleaveComma(inst->getTrueOperands(),
1159 [&](const CFGValue *operand) { printValueID(operand); });
1160 os << " : ";
1161 interleaveComma(inst->getTrueOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001162 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -07001163 });
1164 os << ")";
1165 }
1166
1167 os << ", bb" << getBBID(inst->getFalseDest());
1168 if (inst->getNumFalseOperands() != 0) {
1169 os << '(';
1170 interleaveComma(inst->getFalseOperands(),
1171 [&](const CFGValue *operand) { printValueID(operand); });
1172 os << " : ";
1173 interleaveComma(inst->getFalseOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001174 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -07001175 });
1176 os << ")";
1177 }
1178}
1179
Chris Lattner40746442018-07-21 14:32:09 -07001180void CFGFunctionPrinter::print(const ReturnInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001181 os << "return";
Chris Lattner40746442018-07-21 14:32:09 -07001182
James Molloy6bf60c22018-08-02 08:28:20 -07001183 if (inst->getNumOperands() == 0)
1184 return;
Chris Lattner40746442018-07-21 14:32:09 -07001185
James Molloy6bf60c22018-08-02 08:28:20 -07001186 os << ' ';
James Molloy4f788372018-07-24 15:01:27 -07001187 interleaveComma(inst->getOperands(),
1188 [&](const CFGValue *operand) { printValueID(operand); });
1189 os << " : ";
Chris Lattnerac591f12018-07-22 21:02:26 -07001190 interleaveComma(inst->getOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001191 printType(operand->getType());
Chris Lattner40746442018-07-21 14:32:09 -07001192 });
1193}
MLIR Team54b55a22018-07-18 10:16:05 -07001194
Chris Lattner4fd59b02018-07-20 09:35:47 -07001195void ModulePrinter::print(const CFGFunction *fn) {
1196 CFGFunctionPrinter(fn, *this).print();
Chris Lattnered65a732018-06-28 20:45:33 -07001197}
1198
Chris Lattner4c95a502018-06-23 16:03:42 -07001199//===----------------------------------------------------------------------===//
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001200// ML Function printing
Chris Lattner4c95a502018-06-23 16:03:42 -07001201//===----------------------------------------------------------------------===//
1202
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001203namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001204class MLFunctionPrinter : public FunctionPrinter {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001205public:
Chris Lattner4fd59b02018-07-20 09:35:47 -07001206 MLFunctionPrinter(const MLFunction *function, const ModulePrinter &other);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001207
1208 const MLFunction *getFunction() const { return function; }
1209
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001210 // Prints ML function
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001211 void print();
1212
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001213 // Prints ML function signature
1214 void printFunctionSignature();
1215
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001216 // Methods to print ML function statements
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001217 void print(const Statement *stmt);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -07001218 void print(const OperationStmt *stmt);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001219 void print(const ForStmt *stmt);
1220 void print(const IfStmt *stmt);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001221 void print(const StmtBlock *block);
1222
1223 // Number of spaces used for indenting nested statements
1224 const static unsigned indentWidth = 2;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001225
1226private:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001227 void numberValues();
1228
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001229 const MLFunction *function;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001230 int numSpaces;
1231};
James Molloy87d81022018-07-23 11:44:40 -07001232} // end anonymous namespace
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001233
Chris Lattner4fd59b02018-07-20 09:35:47 -07001234MLFunctionPrinter::MLFunctionPrinter(const MLFunction *function,
1235 const ModulePrinter &other)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001236 : FunctionPrinter(other), function(function), numSpaces(0) {
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001237 assert(function && "Cannot print nullptr function");
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001238 numberValues();
1239}
1240
1241/// Number all of the SSA values in this ML function.
1242void MLFunctionPrinter::numberValues() {
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001243 // Numbers ML function arguments
1244 for (auto *arg : function->getArguments())
1245 numberValueID(arg);
1246
1247 // Walks ML function statements and numbers for statements and
1248 // the first result of the operation statements.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001249 struct NumberValuesPass : public StmtWalker<NumberValuesPass> {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001250 NumberValuesPass(MLFunctionPrinter *printer) : printer(printer) {}
1251 void visitOperationStmt(OperationStmt *stmt) {
1252 if (stmt->getNumResults() != 0)
1253 printer->numberValueID(stmt->getResult(0));
1254 }
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001255 void visitForStmt(ForStmt *stmt) { printer->numberValueID(stmt); }
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001256 MLFunctionPrinter *printer;
1257 };
1258
1259 NumberValuesPass pass(this);
Chris Lattner0497c4b2018-08-15 09:09:54 -07001260 // TODO: it'd be cleaner to have constant visitor instead of using const_cast.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001261 pass.walk(const_cast<MLFunction *>(function));
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001262}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001263
Chris Lattner4fd59b02018-07-20 09:35:47 -07001264void MLFunctionPrinter::print() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001265 os << "mlfunc ";
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001266 printFunctionSignature();
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001267 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001268 print(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001269 os << "}\n\n";
1270}
1271
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001272void MLFunctionPrinter::printFunctionSignature() {
1273 auto type = function->getType();
1274
1275 os << "@" << function->getName() << '(';
1276
1277 for (unsigned i = 0, e = function->getNumArguments(); i != e; ++i) {
1278 if (i > 0)
1279 os << ", ";
1280 auto *arg = function->getArgument(i);
1281 printOperand(arg);
1282 os << " : ";
1283 printType(arg->getType());
1284 }
1285 os << ")";
1286 printFunctionResultType(type);
1287}
1288
Chris Lattner4fd59b02018-07-20 09:35:47 -07001289void MLFunctionPrinter::print(const StmtBlock *block) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001290 numSpaces += indentWidth;
Jacques Pienaarb020c542018-07-15 00:06:54 -07001291 for (auto &stmt : block->getStatements()) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001292 print(&stmt);
Jacques Pienaarb020c542018-07-15 00:06:54 -07001293 os << "\n";
1294 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001295 numSpaces -= indentWidth;
1296}
1297
Chris Lattner4fd59b02018-07-20 09:35:47 -07001298void MLFunctionPrinter::print(const Statement *stmt) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001299 switch (stmt->getKind()) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001300 case Statement::Kind::Operation:
1301 return print(cast<OperationStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001302 case Statement::Kind::For:
1303 return print(cast<ForStmt>(stmt));
1304 case Statement::Kind::If:
1305 return print(cast<IfStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001306 }
1307}
1308
Chris Lattner4fd59b02018-07-20 09:35:47 -07001309void MLFunctionPrinter::print(const OperationStmt *stmt) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001310 os.indent(numSpaces);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001311 printOperation(stmt);
1312}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001313
Chris Lattner4fd59b02018-07-20 09:35:47 -07001314void MLFunctionPrinter::print(const ForStmt *stmt) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001315 os.indent(numSpaces) << "for ";
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001316 printOperand(stmt);
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001317 os << " = " << *stmt->getLowerBound();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001318 os << " to " << *stmt->getUpperBound();
1319 if (stmt->getStep()->getValue() != 1)
1320 os << " step " << *stmt->getStep();
1321
1322 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001323 print(static_cast<const StmtBlock *>(stmt));
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001324 os.indent(numSpaces) << "}";
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001325}
1326
Chris Lattner4fd59b02018-07-20 09:35:47 -07001327void MLFunctionPrinter::print(const IfStmt *stmt) {
Uday Bondhugulabc535622018-08-07 14:24:38 -07001328 os.indent(numSpaces) << "if (";
1329 printIntegerSetReference(stmt->getCondition());
1330 os << ") {\n";
Chris Lattnere787b322018-08-08 11:14:57 -07001331 print(stmt->getThen());
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001332 os.indent(numSpaces) << "}";
Chris Lattnere787b322018-08-08 11:14:57 -07001333 if (stmt->hasElse()) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001334 os << " else {\n";
Chris Lattnere787b322018-08-08 11:14:57 -07001335 print(stmt->getElse());
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001336 os.indent(numSpaces) << "}";
1337 }
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001338}
1339
Chris Lattner4fd59b02018-07-20 09:35:47 -07001340void ModulePrinter::print(const MLFunction *fn) {
1341 MLFunctionPrinter(fn, *this).print();
MLIR Team4718bc92018-07-17 16:56:54 -07001342}
1343
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001344//===----------------------------------------------------------------------===//
1345// print and dump methods
1346//===----------------------------------------------------------------------===//
Chris Lattnered65a732018-06-28 20:45:33 -07001347
MLIR Teamb61885d2018-07-18 16:29:21 -07001348void Attribute::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001349 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001350 ModulePrinter(os, state).printAttribute(this);
MLIR Teamb61885d2018-07-18 16:29:21 -07001351}
1352
James Molloy87d81022018-07-23 11:44:40 -07001353void Attribute::dump() const { print(llvm::errs()); }
MLIR Teamb61885d2018-07-18 16:29:21 -07001354
MLIR Team4718bc92018-07-17 16:56:54 -07001355void Type::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001356 ModuleState state(getContext());
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001357 ModulePrinter(os, state).printType(this);
MLIR Team4718bc92018-07-17 16:56:54 -07001358}
1359
MLIR Team54b55a22018-07-18 10:16:05 -07001360void Type::dump() const { print(llvm::errs()); }
MLIR Team4718bc92018-07-17 16:56:54 -07001361
MLIR Team718c82f2018-07-16 09:45:22 -07001362void AffineMap::dump() const {
1363 print(llvm::errs());
1364 llvm::errs() << "\n";
1365}
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001366
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001367void AffineExpr::dump() const {
1368 print(llvm::errs());
1369 llvm::errs() << "\n";
1370}
1371
Uday Bondhugulabc535622018-08-07 14:24:38 -07001372void IntegerSet::dump() const {
1373 print(llvm::errs());
1374 llvm::errs() << "\n";
1375}
1376
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001377void AffineExpr::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001378 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001379 ModulePrinter(os, state).printAffineExpr(this);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001380}
1381
1382void AffineMap::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001383 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001384 ModulePrinter(os, state).printAffineMap(this);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001385}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001386
Uday Bondhugulabc535622018-08-07 14:24:38 -07001387void IntegerSet::print(raw_ostream &os) const {
1388 ModuleState state(/*no context is known*/ nullptr);
1389 ModulePrinter(os, state).printIntegerSet(this);
1390}
1391
Chris Lattner384da8c2018-08-02 17:16:58 -07001392void SSAValue::print(raw_ostream &os) const {
1393 switch (getKind()) {
1394 case SSAValueKind::BBArgument:
1395 // TODO: Improve this.
1396 os << "<bb argument>\n";
1397 return;
1398 case SSAValueKind::InstResult:
1399 return getDefiningInst()->print(os);
Tatiana Shpeismanbc3c7492018-08-06 11:54:39 -07001400 case SSAValueKind::MLFuncArgument:
Chris Lattner384da8c2018-08-02 17:16:58 -07001401 // TODO: Improve this.
1402 os << "<function argument>\n";
1403 return;
1404 case SSAValueKind::StmtResult:
1405 return getDefiningStmt()->print(os);
1406 case SSAValueKind::ForStmt:
1407 return cast<ForStmt>(this)->print(os);
1408 }
1409}
1410
1411void SSAValue::dump() const { print(llvm::errs()); }
1412
Chris Lattner4fd59b02018-07-20 09:35:47 -07001413void Instruction::print(raw_ostream &os) const {
Tatiana Shpeismanc335d182018-08-03 11:12:34 -07001414 if (!getFunction()) {
1415 os << "<<UNLINKED INSTRUCTION>>\n";
1416 return;
1417 }
Chris Lattner4fd59b02018-07-20 09:35:47 -07001418 ModuleState state(getFunction()->getContext());
1419 ModulePrinter modulePrinter(os, state);
1420 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
1421}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001422
Chris Lattner4fd59b02018-07-20 09:35:47 -07001423void Instruction::dump() const {
1424 print(llvm::errs());
1425 llvm::errs() << "\n";
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001426}
1427
Chris Lattner4c95a502018-06-23 16:03:42 -07001428void BasicBlock::print(raw_ostream &os) const {
Tatiana Shpeismanc335d182018-08-03 11:12:34 -07001429 if (!getFunction()) {
1430 os << "<<UNLINKED BLOCK>>\n";
1431 return;
1432 }
Chris Lattner4fd59b02018-07-20 09:35:47 -07001433 ModuleState state(getFunction()->getContext());
1434 ModulePrinter modulePrinter(os, state);
1435 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001436}
1437
MLIR Team54b55a22018-07-18 10:16:05 -07001438void BasicBlock::dump() const { print(llvm::errs()); }
Chris Lattner4c95a502018-06-23 16:03:42 -07001439
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001440void Statement::print(raw_ostream &os) const {
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001441 MLFunction *function = findFunction();
Tatiana Shpeismanc335d182018-08-03 11:12:34 -07001442 if (!function) {
1443 os << "<<UNLINKED STATEMENT>>\n";
1444 return;
1445 }
1446
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001447 ModuleState state(function->getContext());
Chris Lattner4fd59b02018-07-20 09:35:47 -07001448 ModulePrinter modulePrinter(os, state);
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001449 MLFunctionPrinter(function, modulePrinter).print(this);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001450}
1451
MLIR Team54b55a22018-07-18 10:16:05 -07001452void Statement::dump() const { print(llvm::errs()); }
Jacques Pienaarb020c542018-07-15 00:06:54 -07001453
Chris Lattnere787b322018-08-08 11:14:57 -07001454void StmtBlock::printBlock(raw_ostream &os) const {
Uday Bondhugula84b80952018-08-03 13:22:26 -07001455 MLFunction *function = findFunction();
1456 ModuleState state(function->getContext());
1457 ModulePrinter modulePrinter(os, state);
1458 MLFunctionPrinter(function, modulePrinter).print(this);
1459}
1460
Chris Lattnere787b322018-08-08 11:14:57 -07001461void StmtBlock::dumpBlock() const { printBlock(llvm::errs()); }
Uday Bondhugula84b80952018-08-03 13:22:26 -07001462
Chris Lattner4c95a502018-06-23 16:03:42 -07001463void Function::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001464 ModuleState state(getContext());
1465 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001466}
1467
MLIR Team54b55a22018-07-18 10:16:05 -07001468void Function::dump() const { print(llvm::errs()); }
1469
Chris Lattner4c95a502018-06-23 16:03:42 -07001470void Module::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001471 ModuleState state(getContext());
1472 state.initialize(this);
1473 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001474}
1475
MLIR Team54b55a22018-07-18 10:16:05 -07001476void Module::dump() const { print(llvm::errs()); }