blob: 6177e195c38ff5c4d3451994643deb462944ed80 [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"
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -070027#include "mlir/IR/MLFunction.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070028#include "mlir/IR/Module.h"
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070029#include "mlir/IR/OpImplementation.h"
Chris Lattnerff0d5902018-07-05 09:12:11 -070030#include "mlir/IR/OperationSet.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070031#include "mlir/IR/StandardOps.h"
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -070032#include "mlir/IR/Statements.h"
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -070033#include "mlir/IR/StmtVisitor.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070034#include "mlir/IR/Types.h"
35#include "mlir/Support/STLExtras.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070036#include "llvm/ADT/DenseMap.h"
Chris Lattnerd4964212018-08-01 10:43:18 -070037#include "llvm/ADT/SmallString.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/ADT/StringSet.h"
Chris Lattner4c95a502018-06-23 16:03:42 -070040using namespace mlir;
41
MLIR Team54b55a22018-07-18 10:16:05 -070042void Identifier::print(raw_ostream &os) const { os << str(); }
Chris Lattner4c95a502018-06-23 16:03:42 -070043
MLIR Team54b55a22018-07-18 10:16:05 -070044void Identifier::dump() const { print(llvm::errs()); }
Chris Lattner7121b802018-07-04 20:45:39 -070045
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -070046OpAsmPrinter::~OpAsmPrinter() {}
47
Chris Lattner4c95a502018-06-23 16:03:42 -070048//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -070049// ModuleState
MLIR Team4718bc92018-07-17 16:56:54 -070050//===----------------------------------------------------------------------===//
51
52namespace {
MLIR Team54b55a22018-07-18 10:16:05 -070053class ModuleState {
54public:
Chris Lattner4fd59b02018-07-20 09:35:47 -070055 /// This is the operation set for the current context if it is knowable (a
56 /// context could be determined), otherwise this is null.
57 OperationSet *const operationSet;
MLIR Team4718bc92018-07-17 16:56:54 -070058
Chris Lattner4fd59b02018-07-20 09:35:47 -070059 explicit ModuleState(MLIRContext *context)
60 : operationSet(context ? &OperationSet::get(context) : nullptr) {}
61
62 // Initializes module state, populating affine map state.
MLIR Team4718bc92018-07-17 16:56:54 -070063 void initialize(const Module *module);
64
MLIR Team54b55a22018-07-18 10:16:05 -070065 int getAffineMapId(const AffineMap *affineMap) const {
MLIR Team4718bc92018-07-17 16:56:54 -070066 auto it = affineMapIds.find(affineMap);
67 if (it == affineMapIds.end()) {
68 return -1;
69 }
70 return it->second;
71 }
72
James Molloyc4666722018-07-24 09:48:31 -070073 ArrayRef<const AffineMap *> getAffineMapIds() const { return affineMapsById; }
Chris Lattner4fd59b02018-07-20 09:35:47 -070074
MLIR Team54b55a22018-07-18 10:16:05 -070075private:
Chris Lattner4fd59b02018-07-20 09:35:47 -070076 void recordAffineMapReference(const AffineMap *affineMap) {
77 if (affineMapIds.count(affineMap) == 0) {
James Molloyc4666722018-07-24 09:48:31 -070078 affineMapIds[affineMap] = affineMapsById.size();
79 affineMapsById.push_back(affineMap);
Chris Lattner4fd59b02018-07-20 09:35:47 -070080 }
81 }
82
MLIR Team4718bc92018-07-17 16:56:54 -070083 // Visit functions.
84 void visitFunction(const Function *fn);
85 void visitExtFunction(const ExtFunction *fn);
86 void visitCFGFunction(const CFGFunction *fn);
87 void visitMLFunction(const MLFunction *fn);
88 void visitType(const Type *type);
MLIR Teamb61885d2018-07-18 16:29:21 -070089 void visitAttribute(const Attribute *attr);
90 void visitOperation(const Operation *op);
91
MLIR Team54b55a22018-07-18 10:16:05 -070092 DenseMap<const AffineMap *, int> affineMapIds;
James Molloyc4666722018-07-24 09:48:31 -070093 std::vector<const AffineMap *> affineMapsById;
MLIR Team4718bc92018-07-17 16:56:54 -070094};
James Molloy87d81022018-07-23 11:44:40 -070095} // end anonymous namespace
MLIR Team4718bc92018-07-17 16:56:54 -070096
97// TODO Support visiting other types/instructions when implemented.
98void ModuleState::visitType(const Type *type) {
Chris Lattner3164ae62018-07-28 09:36:25 -070099 if (auto *funcType = dyn_cast<FunctionType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700100 // Visit input and result types for functions.
Chris Lattner3164ae62018-07-28 09:36:25 -0700101 for (auto *input : funcType->getInputs())
MLIR Team4718bc92018-07-17 16:56:54 -0700102 visitType(input);
Chris Lattner3164ae62018-07-28 09:36:25 -0700103 for (auto *result : funcType->getResults())
MLIR Team4718bc92018-07-17 16:56:54 -0700104 visitType(result);
Chris Lattner3164ae62018-07-28 09:36:25 -0700105 } else if (auto *memref = dyn_cast<MemRefType>(type)) {
MLIR Team4718bc92018-07-17 16:56:54 -0700106 // Visit affine maps in memref type.
Chris Lattner3164ae62018-07-28 09:36:25 -0700107 for (auto *map : memref->getAffineMaps()) {
MLIR Team4718bc92018-07-17 16:56:54 -0700108 recordAffineMapReference(map);
109 }
110 }
111}
112
MLIR Teamb61885d2018-07-18 16:29:21 -0700113void ModuleState::visitAttribute(const Attribute *attr) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700114 if (auto *mapAttr = dyn_cast<AffineMapAttr>(attr)) {
115 recordAffineMapReference(mapAttr->getValue());
116 } else if (auto *array = dyn_cast<ArrayAttr>(attr)) {
117 for (auto elt : array->getValue()) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700118 visitAttribute(elt);
119 }
120 }
121}
122
123void ModuleState::visitOperation(const Operation *op) {
Chris Lattnerca2ee872018-07-31 18:32:59 -0700124 // Visit all the types used in the operation.
125 for (auto *operand : op->getOperands())
126 visitType(operand->getType());
127 for (auto *result : op->getResults())
128 visitType(result->getType());
129
130 // Visit each of the attributes.
131 for (auto elt : op->getAttrs())
MLIR Teamb61885d2018-07-18 16:29:21 -0700132 visitAttribute(elt.second);
MLIR Teamb61885d2018-07-18 16:29:21 -0700133}
134
MLIR Team4718bc92018-07-17 16:56:54 -0700135void ModuleState::visitExtFunction(const ExtFunction *fn) {
136 visitType(fn->getType());
137}
138
139void ModuleState::visitCFGFunction(const CFGFunction *fn) {
140 visitType(fn->getType());
MLIR Teamb61885d2018-07-18 16:29:21 -0700141 for (auto &block : *fn) {
142 for (auto &op : block.getOperations()) {
143 visitOperation(&op);
144 }
145 }
MLIR Team4718bc92018-07-17 16:56:54 -0700146}
147
148void ModuleState::visitMLFunction(const MLFunction *fn) {
149 visitType(fn->getType());
MLIR Teamb61885d2018-07-18 16:29:21 -0700150 // TODO Visit function body statements (and attributes if required).
MLIR Team4718bc92018-07-17 16:56:54 -0700151}
152
153void ModuleState::visitFunction(const Function *fn) {
154 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700155 case Function::Kind::ExtFunc:
156 return visitExtFunction(cast<ExtFunction>(fn));
157 case Function::Kind::CFGFunc:
158 return visitCFGFunction(cast<CFGFunction>(fn));
159 case Function::Kind::MLFunc:
160 return visitMLFunction(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700161 }
162}
163
Chris Lattner4fd59b02018-07-20 09:35:47 -0700164// Initializes module state, populating affine map state.
165void ModuleState::initialize(const Module *module) {
Chris Lattnera8e47672018-07-25 14:08:16 -0700166 for (auto &fn : *module) {
167 visitFunction(&fn);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700168 }
169}
170
171//===----------------------------------------------------------------------===//
172// ModulePrinter
173//===----------------------------------------------------------------------===//
174
175namespace {
176class ModulePrinter {
177public:
178 ModulePrinter(raw_ostream &os, ModuleState &state) : os(os), state(state) {}
179 explicit ModulePrinter(const ModulePrinter &printer)
180 : os(printer.os), state(printer.state) {}
181
182 template <typename Container, typename UnaryFunctor>
183 inline void interleaveComma(const Container &c, UnaryFunctor each_fn) const {
184 interleave(c.begin(), c.end(), each_fn, [&]() { os << ", "; });
185 }
186
187 void print(const Module *module);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700188 void printAttribute(const Attribute *attr);
189 void printType(const Type *type);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700190 void print(const Function *fn);
191 void print(const ExtFunction *fn);
192 void print(const CFGFunction *fn);
193 void print(const MLFunction *fn);
194
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700195 void printAffineMap(const AffineMap *map);
196 void printAffineExpr(const AffineExpr *expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700197
198protected:
199 raw_ostream &os;
200 ModuleState &state;
201
202 void printFunctionSignature(const Function *fn);
203 void printAffineMapId(int affineMapId) const;
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700204 void printAffineMapReference(const AffineMap *affineMap);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700205
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700206 /// This enum is used to represent the binding stength of the enclosing
207 /// context that an AffineExpr is being printed in, so we can intelligently
208 /// produce parens.
209 enum class BindingStrength {
210 Weak, // + and -
211 Strong, // All other binary operators.
212 };
213 void printAffineExprInternal(const AffineExpr *expr,
214 BindingStrength enclosingTightness);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700215};
216} // end anonymous namespace
217
MLIR Team4718bc92018-07-17 16:56:54 -0700218// Prints function with initialized module state.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700219void ModulePrinter::print(const Function *fn) {
MLIR Team4718bc92018-07-17 16:56:54 -0700220 switch (fn->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700221 case Function::Kind::ExtFunc:
222 return print(cast<ExtFunction>(fn));
223 case Function::Kind::CFGFunc:
224 return print(cast<CFGFunction>(fn));
225 case Function::Kind::MLFunc:
226 return print(cast<MLFunction>(fn));
MLIR Team4718bc92018-07-17 16:56:54 -0700227 }
228}
229
230// Prints affine map identifier.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700231void ModulePrinter::printAffineMapId(int affineMapId) const {
MLIR Team4718bc92018-07-17 16:56:54 -0700232 os << "#map" << affineMapId;
233}
234
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700235void ModulePrinter::printAffineMapReference(const AffineMap *affineMap) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700236 int mapId = state.getAffineMapId(affineMap);
MLIR Teamb61885d2018-07-18 16:29:21 -0700237 if (mapId >= 0) {
238 // Map will be printed at top of module so print reference to its id.
239 printAffineMapId(mapId);
240 } else {
241 // Map not in module state so print inline.
242 affineMap->print(os);
243 }
244}
245
Chris Lattner4fd59b02018-07-20 09:35:47 -0700246void ModulePrinter::print(const Module *module) {
James Molloyc4666722018-07-24 09:48:31 -0700247 for (const auto &map : state.getAffineMapIds()) {
248 printAffineMapId(state.getAffineMapId(map));
MLIR Team4718bc92018-07-17 16:56:54 -0700249 os << " = ";
James Molloyc4666722018-07-24 09:48:31 -0700250 map->print(os);
MLIR Team4718bc92018-07-17 16:56:54 -0700251 os << '\n';
252 }
Chris Lattnera8e47672018-07-25 14:08:16 -0700253 for (auto const &fn : *module)
254 print(&fn);
MLIR Team4718bc92018-07-17 16:56:54 -0700255}
256
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700257void ModulePrinter::printAttribute(const Attribute *attr) {
MLIR Teamb61885d2018-07-18 16:29:21 -0700258 switch (attr->getKind()) {
259 case Attribute::Kind::Bool:
260 os << (cast<BoolAttr>(attr)->getValue() ? "true" : "false");
261 break;
262 case Attribute::Kind::Integer:
263 os << cast<IntegerAttr>(attr)->getValue();
264 break;
265 case Attribute::Kind::Float:
266 // FIXME: this isn't precise, we should print with a hex format.
267 os << cast<FloatAttr>(attr)->getValue();
268 break;
269 case Attribute::Kind::String:
270 // FIXME: should escape the string.
271 os << '"' << cast<StringAttr>(attr)->getValue() << '"';
272 break;
273 case Attribute::Kind::Array: {
274 auto elts = cast<ArrayAttr>(attr)->getValue();
275 os << '[';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700276 interleaveComma(elts, [&](Attribute *attr) { printAttribute(attr); });
MLIR Teamb61885d2018-07-18 16:29:21 -0700277 os << ']';
278 break;
279 }
280 case Attribute::Kind::AffineMap:
281 printAffineMapReference(cast<AffineMapAttr>(attr)->getValue());
282 break;
283 }
284}
285
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700286void ModulePrinter::printType(const Type *type) {
MLIR Team4718bc92018-07-17 16:56:54 -0700287 switch (type->getKind()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700288 case Type::Kind::AffineInt:
289 os << "affineint";
290 return;
291 case Type::Kind::BF16:
292 os << "bf16";
293 return;
294 case Type::Kind::F16:
295 os << "f16";
296 return;
297 case Type::Kind::F32:
298 os << "f32";
299 return;
300 case Type::Kind::F64:
301 os << "f64";
302 return;
Jacques Pienaarc0d69302018-07-27 11:07:12 -0700303 case Type::Kind::TFControl:
304 os << "tf_control";
305 return;
James Molloy72b0cbe2018-08-01 12:55:27 -0700306 case Type::Kind::TFString:
307 os << "tf_string";
308 return;
MLIR Team4718bc92018-07-17 16:56:54 -0700309
310 case Type::Kind::Integer: {
311 auto *integer = cast<IntegerType>(type);
312 os << 'i' << integer->getWidth();
313 return;
314 }
315 case Type::Kind::Function: {
316 auto *func = cast<FunctionType>(type);
317 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700318 interleaveComma(func->getInputs(), [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700319 os << ") -> ";
320 auto results = func->getResults();
321 if (results.size() == 1)
322 os << *results[0];
323 else {
324 os << '(';
Chris Lattner413db6a2018-07-25 12:55:50 -0700325 interleaveComma(results, [&](Type *type) { printType(type); });
MLIR Team4718bc92018-07-17 16:56:54 -0700326 os << ')';
327 }
328 return;
329 }
330 case Type::Kind::Vector: {
331 auto *v = cast<VectorType>(type);
332 os << "vector<";
James Molloy87d81022018-07-23 11:44:40 -0700333 for (auto dim : v->getShape())
334 os << dim << 'x';
MLIR Team4718bc92018-07-17 16:56:54 -0700335 os << *v->getElementType() << '>';
336 return;
337 }
338 case Type::Kind::RankedTensor: {
339 auto *v = cast<RankedTensorType>(type);
340 os << "tensor<";
341 for (auto dim : v->getShape()) {
342 if (dim < 0)
343 os << '?';
344 else
345 os << dim;
346 os << 'x';
347 }
348 os << *v->getElementType() << '>';
349 return;
350 }
351 case Type::Kind::UnrankedTensor: {
352 auto *v = cast<UnrankedTensorType>(type);
Chris Lattner413db6a2018-07-25 12:55:50 -0700353 os << "tensor<??";
354 printType(v->getElementType());
355 os << '>';
MLIR Team4718bc92018-07-17 16:56:54 -0700356 return;
357 }
358 case Type::Kind::MemRef: {
359 auto *v = cast<MemRefType>(type);
360 os << "memref<";
361 for (auto dim : v->getShape()) {
362 if (dim < 0)
363 os << '?';
364 else
365 os << dim;
366 os << 'x';
367 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700368 printType(v->getElementType());
MLIR Team4718bc92018-07-17 16:56:54 -0700369 for (auto map : v->getAffineMaps()) {
370 os << ", ";
MLIR Teamb61885d2018-07-18 16:29:21 -0700371 printAffineMapReference(map);
MLIR Team4718bc92018-07-17 16:56:54 -0700372 }
Chris Lattner413db6a2018-07-25 12:55:50 -0700373 // Only print the memory space if it is the non-default one.
374 if (v->getMemorySpace())
375 os << ", " << v->getMemorySpace();
MLIR Team4718bc92018-07-17 16:56:54 -0700376 os << '>';
377 return;
378 }
379 }
380}
381
382//===----------------------------------------------------------------------===//
Chris Lattner4fd59b02018-07-20 09:35:47 -0700383// Affine expressions and maps
384//===----------------------------------------------------------------------===//
385
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700386void ModulePrinter::printAffineExpr(const AffineExpr *expr) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700387 printAffineExprInternal(expr, BindingStrength::Weak);
388}
389
390void ModulePrinter::printAffineExprInternal(
391 const AffineExpr *expr, BindingStrength enclosingTightness) {
392 const char *binopSpelling = nullptr;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700393 switch (expr->getKind()) {
394 case AffineExpr::Kind::SymbolId:
395 os << 's' << cast<AffineSymbolExpr>(expr)->getPosition();
396 return;
397 case AffineExpr::Kind::DimId:
398 os << 'd' << cast<AffineDimExpr>(expr)->getPosition();
399 return;
400 case AffineExpr::Kind::Constant:
401 os << cast<AffineConstantExpr>(expr)->getValue();
402 return;
403 case AffineExpr::Kind::Add:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700404 binopSpelling = " + ";
405 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700406 case AffineExpr::Kind::Mul:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700407 binopSpelling = " * ";
408 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700409 case AffineExpr::Kind::FloorDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700410 binopSpelling = " floordiv ";
411 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700412 case AffineExpr::Kind::CeilDiv:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700413 binopSpelling = " ceildiv ";
414 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700415 case AffineExpr::Kind::Mod:
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700416 binopSpelling = " mod ";
417 break;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700418 }
Chris Lattner4fd59b02018-07-20 09:35:47 -0700419
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700420 auto *binOp = cast<AffineBinaryOpExpr>(expr);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700421
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700422 // Handle tightly binding binary operators.
423 if (binOp->getKind() != AffineExpr::Kind::Add) {
424 if (enclosingTightness == BindingStrength::Strong)
425 os << '(';
426
427 printAffineExprInternal(binOp->getLHS(), BindingStrength::Strong);
428 os << binopSpelling;
429 printAffineExprInternal(binOp->getRHS(), BindingStrength::Strong);
430
431 if (enclosingTightness == BindingStrength::Strong)
432 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700433 return;
434 }
435
436 // Print out special "pretty" forms for add.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700437 if (enclosingTightness == BindingStrength::Strong)
438 os << '(';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700439
440 // Pretty print addition to a product that has a negative operand as a
441 // subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700442 if (auto *rhs = dyn_cast<AffineBinaryOpExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700443 if (rhs->getKind() == AffineExpr::Kind::Mul) {
444 if (auto *rrhs = dyn_cast<AffineConstantExpr>(rhs->getRHS())) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700445 if (rrhs->getValue() == -1) {
446 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
447 os << " - ";
448 printAffineExprInternal(rhs->getLHS(), BindingStrength::Weak);
449
450 if (enclosingTightness == BindingStrength::Strong)
451 os << ')';
452 return;
453 }
454
455 if (rrhs->getValue() < -1) {
456 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700457 os << " - ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700458 printAffineExprInternal(rhs->getLHS(), BindingStrength::Strong);
Uday Bondhugula970f5b82018-08-01 22:02:00 -0700459 os << " * " << -rrhs->getValue();
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700460 if (enclosingTightness == BindingStrength::Strong)
461 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700462 return;
463 }
464 }
465 }
466 }
467
468 // Pretty print addition to a negative number as a subtraction.
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700469 if (auto *rhs = dyn_cast<AffineConstantExpr>(binOp->getRHS())) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700470 if (rhs->getValue() < 0) {
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700471 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
472 os << " - " << -rhs->getValue() << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700473 return;
474 }
475 }
476
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700477 printAffineExprInternal(binOp->getLHS(), BindingStrength::Weak);
Chris Lattner4fd59b02018-07-20 09:35:47 -0700478 os << " + ";
Chris Lattner7d3b77c2018-07-31 16:21:36 -0700479 printAffineExprInternal(binOp->getRHS(), BindingStrength::Weak);
480
481 if (enclosingTightness == BindingStrength::Strong)
482 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700483}
484
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700485void ModulePrinter::printAffineMap(const AffineMap *map) {
Chris Lattner4fd59b02018-07-20 09:35:47 -0700486 // Dimension identifiers.
487 os << '(';
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700488 for (int i = 0; i < (int)map->getNumDims() - 1; ++i)
489 os << 'd' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700490 if (map->getNumDims() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700491 os << 'd' << map->getNumDims() - 1;
492 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700493
494 // Symbolic identifiers.
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700495 if (map->getNumSymbols() != 0) {
496 os << '[';
497 for (unsigned i = 0; i < map->getNumSymbols() - 1; ++i)
498 os << 's' << i << ", ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700499 if (map->getNumSymbols() >= 1)
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700500 os << 's' << map->getNumSymbols() - 1;
501 os << ']';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700502 }
503
504 // AffineMap should have at least one result.
505 assert(!map->getResults().empty());
506 // Result affine expressions.
507 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700508 interleaveComma(map->getResults(),
509 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700510 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700511
512 if (!map->isBounded()) {
513 return;
514 }
515
516 // Print range sizes for bounded affine maps.
517 os << " size (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700518 interleaveComma(map->getRangeSizes(),
519 [&](AffineExpr *expr) { printAffineExpr(expr); });
Chris Lattnerdc3ba382018-07-29 14:13:03 -0700520 os << ')';
Chris Lattner4fd59b02018-07-20 09:35:47 -0700521}
522
523//===----------------------------------------------------------------------===//
Chris Lattner4c95a502018-06-23 16:03:42 -0700524// Function printing
525//===----------------------------------------------------------------------===//
526
Chris Lattner4fd59b02018-07-20 09:35:47 -0700527void ModulePrinter::printFunctionSignature(const Function *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700528 auto type = fn->getType();
529
530 os << "@" << fn->getName() << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700531 interleaveComma(type->getInputs(),
532 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700533 os << ')';
534
535 switch (type->getResults().size()) {
MLIR Team54b55a22018-07-18 10:16:05 -0700536 case 0:
537 break;
Chris Lattner4c95a502018-06-23 16:03:42 -0700538 case 1:
MLIR Team4718bc92018-07-17 16:56:54 -0700539 os << " -> ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700540 printType(type->getResults()[0]);
Chris Lattner4c95a502018-06-23 16:03:42 -0700541 break;
542 default:
543 os << " -> (";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700544 interleaveComma(type->getResults(),
545 [&](Type *eltType) { printType(eltType); });
Chris Lattner4c95a502018-06-23 16:03:42 -0700546 os << ')';
547 break;
548 }
549}
550
Chris Lattner4fd59b02018-07-20 09:35:47 -0700551void ModulePrinter::print(const ExtFunction *fn) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700552 os << "extfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700553 printFunctionSignature(fn);
MLIR Team54b55a22018-07-18 10:16:05 -0700554 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700555}
556
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700557namespace {
558
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700559// FunctionPrinter contains common functionality for printing
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700560// CFG and ML functions.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700561class FunctionPrinter : public ModulePrinter, private OpAsmPrinter {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700562public:
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700563 FunctionPrinter(const ModulePrinter &other) : ModulePrinter(other) {}
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700564
565 void printOperation(const Operation *op);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700566 void printDefaultOp(const Operation *op);
567
568 // Implement OpAsmPrinter.
569 raw_ostream &getStream() const { return os; }
570 void printType(const Type *type) { ModulePrinter::printType(type); }
571 void printAttribute(const Attribute *attr) {
572 ModulePrinter::printAttribute(attr);
573 }
574 void printAffineMap(const AffineMap *map) {
Chris Lattner3164ae62018-07-28 09:36:25 -0700575 return ModulePrinter::printAffineMapReference(map);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700576 }
577 void printAffineExpr(const AffineExpr *expr) {
578 return ModulePrinter::printAffineExpr(expr);
579 }
580
581 void printOperand(const SSAValue *value) { printValueID(value); }
Chris Lattner85cf26d2018-08-02 16:54:36 -0700582 void printOptionalAttrDict(ArrayRef<NamedAttribute> attrs,
583 ArrayRef<const char *> elidedAttrs = {}) override;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700584
Chris Lattnerd4964212018-08-01 10:43:18 -0700585 enum { nameSentinel = ~0U };
586
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700587protected:
Chris Lattnerf8cce872018-07-20 09:28:54 -0700588 void numberValueID(const SSAValue *value) {
589 assert(!valueIDs.count(value) && "Value numbered multiple times");
Chris Lattnerd4964212018-08-01 10:43:18 -0700590
591 SmallString<32> specialNameBuffer;
592 llvm::raw_svector_ostream specialName(specialNameBuffer);
593
594 // Give constant integers special names.
595 if (auto *op = value->getDefiningOperation()) {
596 if (auto intOp = op->getAs<ConstantIntOp>()) {
Chris Lattner384da8c2018-08-02 17:16:58 -0700597 // i1 constants get special names.
598 if (intOp->getType()->isInteger(1)) {
599 specialName << (intOp->getValue() ? "true" : "false");
600 } else {
601 specialName << 'c' << intOp->getValue();
602 if (!intOp->getType()->isAffineInt())
603 specialName << '_' << *intOp->getType();
604 }
Chris Lattnerd4964212018-08-01 10:43:18 -0700605 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700606 }
Chris Lattnerd4964212018-08-01 10:43:18 -0700607
608 if (specialNameBuffer.empty()) {
609 switch (value->getKind()) {
610 case SSAValueKind::BBArgument:
611 // If this is an argument to the function, give it an 'arg' name.
612 if (auto *bb = cast<BBArgument>(value)->getOwner())
613 if (auto *fn = bb->getFunction())
614 if (&fn->front() == bb) {
615 specialName << "arg" << nextArgumentID++;
616 break;
617 }
618 // Otherwise number it normally.
619 LLVM_FALLTHROUGH;
620 case SSAValueKind::InstResult:
621 case SSAValueKind::StmtResult:
622 // This is an uninteresting result, give it a boring number and be
623 // done with it.
624 valueIDs[value] = nextValueID++;
625 return;
626 case SSAValueKind::FnArgument:
627 specialName << "arg" << nextArgumentID++;
628 break;
629 case SSAValueKind::ForStmt:
630 specialName << 'i' << nextLoopID++;
631 break;
632 }
633 }
634
635 // Ok, this value had an interesting name. Remember it with a sentinel.
636 valueIDs[value] = nameSentinel;
637
638 // Remember that we've used this name, checking to see if we had a conflict.
639 auto insertRes = usedNames.insert(specialName.str());
640 if (insertRes.second) {
641 // If this is the first use of the name, then we're successful!
642 valueNames[value] = insertRes.first->first();
643 return;
644 }
645
646 // Otherwise, we had a conflict - probe until we find a unique name. This
647 // is guaranteed to terminate (and usually in a single iteration) because it
648 // generates new names by incrementing nextConflictID.
649 while (1) {
650 std::string probeName =
651 specialName.str().str() + "_" + llvm::utostr(nextConflictID++);
652 insertRes = usedNames.insert(probeName);
653 if (insertRes.second) {
654 // If this is the first use of the name, then we're successful!
655 valueNames[value] = insertRes.first->first();
656 return;
657 }
658 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700659 }
660
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700661 void printValueID(const SSAValue *value, bool printResultNo = true) const {
Chris Lattner6119d382018-07-20 18:41:34 -0700662 int resultNo = -1;
663 auto lookupValue = value;
664
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700665 // If this is a reference to the result of a multi-result instruction or
666 // statement, print out the # identifier and make sure to map our lookup
667 // to the first result of the instruction.
Chris Lattner6119d382018-07-20 18:41:34 -0700668 if (auto *result = dyn_cast<InstResult>(value)) {
669 if (result->getOwner()->getNumResults() != 1) {
670 resultNo = result->getResultNumber();
671 lookupValue = result->getOwner()->getResult(0);
672 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700673 } else if (auto *result = dyn_cast<StmtResult>(value)) {
674 if (result->getOwner()->getNumResults() != 1) {
675 resultNo = result->getResultNumber();
676 lookupValue = result->getOwner()->getResult(0);
677 }
Chris Lattner6119d382018-07-20 18:41:34 -0700678 }
679
680 auto it = valueIDs.find(lookupValue);
681 if (it == valueIDs.end()) {
Chris Lattnerf8cce872018-07-20 09:28:54 -0700682 os << "<<INVALID SSA VALUE>>";
Chris Lattner6119d382018-07-20 18:41:34 -0700683 return;
684 }
685
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700686 os << '%';
Chris Lattnerd4964212018-08-01 10:43:18 -0700687 if (it->second != nameSentinel) {
688 os << it->second;
689 } else {
690 auto nameIt = valueNames.find(lookupValue);
691 assert(nameIt != valueNames.end() && "Didn't have a name entry?");
692 os << nameIt->second;
693 }
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700694
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700695 if (resultNo != -1 && printResultNo)
Chris Lattner6119d382018-07-20 18:41:34 -0700696 os << '#' << resultNo;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700697 }
698
699private:
Chris Lattnerd4964212018-08-01 10:43:18 -0700700 /// This is the value ID for each SSA value in the current function. If this
701 /// returns ~0, then the valueID has an entry in valueNames.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700702 DenseMap<const SSAValue *, unsigned> valueIDs;
Chris Lattnerd4964212018-08-01 10:43:18 -0700703 DenseMap<const SSAValue *, StringRef> valueNames;
704
705 /// This keeps track of all of the non-numeric names that are in flight,
706 /// allowing us to check for duplicates.
707 llvm::StringSet<> usedNames;
708
709 /// This is the next value ID to assign in numbering.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700710 unsigned nextValueID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700711 /// This is the ID to assign to the next induction variable.
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -0700712 unsigned nextLoopID = 0;
Chris Lattnerd4964212018-08-01 10:43:18 -0700713 /// This is the next ID to assign to an MLFunction argument.
714 unsigned nextArgumentID = 0;
715
716 /// This is the next ID to assign when a name conflict is detected.
717 unsigned nextConflictID = 0;
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700718};
James Molloy87d81022018-07-23 11:44:40 -0700719} // end anonymous namespace
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700720
Chris Lattner85cf26d2018-08-02 16:54:36 -0700721void FunctionPrinter::printOptionalAttrDict(
722 ArrayRef<NamedAttribute> attrs, ArrayRef<const char *> elidedAttrs) {
723 // If there are no attributes, then there is nothing to be done.
724 if (attrs.empty())
725 return;
726
727 // Filter out any attributes that shouldn't be included.
728 SmallVector<NamedAttribute, 8> filteredAttrs;
729 for (auto attr : attrs) {
730 auto attrName = attr.first.str();
731 // Never print attributes that start with a colon. These are internal
732 // attributes that represent location or other internal metadata.
733 if (attrName.startswith(":"))
734 continue;
735
736 // If the caller has requested that this attribute be ignored, then drop it.
737 bool ignore = false;
738 for (const char *elide : elidedAttrs)
739 ignore |= attrName == StringRef(elide);
740
741 // Otherwise add it to our filteredAttrs list.
742 if (!ignore)
743 filteredAttrs.push_back(attr);
744 }
745
746 // If there are no attributes left to print after filtering, then we're done.
747 if (filteredAttrs.empty())
748 return;
749
750 // Otherwise, print them all out in braces.
751 os << " {";
752 interleaveComma(filteredAttrs, [&](NamedAttribute attr) {
753 os << attr.first << ": ";
754 printAttribute(attr.second);
755 });
756 os << '}';
757}
758
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700759void FunctionPrinter::printOperation(const Operation *op) {
Chris Lattnerac591f12018-07-22 21:02:26 -0700760 if (op->getNumResults()) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -0700761 printValueID(op->getResult(0), /*printResultNo=*/false);
Chris Lattnerac591f12018-07-22 21:02:26 -0700762 os << " = ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700763 }
764
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700765 // Check to see if this is a known operation. If so, use the registered
766 // custom printer hook.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700767 if (auto opInfo = state.operationSet->lookup(op->getName().str())) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700768 opInfo->printAssembly(op, this);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700769 return;
770 }
771
Chris Lattnerf8cce872018-07-20 09:28:54 -0700772 // Otherwise use the standard verbose printing approach.
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700773 printDefaultOp(op);
774}
Chris Lattnerf8cce872018-07-20 09:28:54 -0700775
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700776void FunctionPrinter::printDefaultOp(const Operation *op) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700777 // TODO: escape name if necessary.
Chris Lattnerf8cce872018-07-20 09:28:54 -0700778 os << "\"" << op->getName().str() << "\"(";
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700779
Chris Lattnerac591f12018-07-22 21:02:26 -0700780 interleaveComma(op->getOperands(),
781 [&](const SSAValue *value) { printValueID(value); });
Chris Lattner7f9cc272018-07-19 08:35:28 -0700782
Chris Lattnerf8cce872018-07-20 09:28:54 -0700783 os << ')';
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700784 auto attrs = op->getAttrs();
Chris Lattner85cf26d2018-08-02 16:54:36 -0700785 printOptionalAttrDict(attrs);
Chris Lattner3b2ef762018-07-18 15:31:25 -0700786
Chris Lattnerac591f12018-07-22 21:02:26 -0700787 // Print the type signature of the operation.
788 os << " : (";
789 interleaveComma(op->getOperands(),
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700790 [&](const SSAValue *value) { printType(value->getType()); });
Chris Lattnerac591f12018-07-22 21:02:26 -0700791 os << ") -> ";
Chris Lattnerf8cce872018-07-20 09:28:54 -0700792
Chris Lattnerac591f12018-07-22 21:02:26 -0700793 if (op->getNumResults() == 1) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700794 printType(op->getResult(0)->getType());
Chris Lattnerac591f12018-07-22 21:02:26 -0700795 } else {
796 os << '(';
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700797 interleaveComma(op->getResults(), [&](const SSAValue *result) {
798 printType(result->getType());
799 });
Chris Lattnerac591f12018-07-22 21:02:26 -0700800 os << ')';
Chris Lattnerf8cce872018-07-20 09:28:54 -0700801 }
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700802}
803
Chris Lattner4c95a502018-06-23 16:03:42 -0700804//===----------------------------------------------------------------------===//
805// CFG Function printing
806//===----------------------------------------------------------------------===//
807
808namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700809class CFGFunctionPrinter : public FunctionPrinter {
Chris Lattner4c95a502018-06-23 16:03:42 -0700810public:
Chris Lattner4fd59b02018-07-20 09:35:47 -0700811 CFGFunctionPrinter(const CFGFunction *function, const ModulePrinter &other);
Chris Lattner4c95a502018-06-23 16:03:42 -0700812
813 const CFGFunction *getFunction() const { return function; }
814
815 void print();
816 void print(const BasicBlock *block);
Chris Lattnered65a732018-06-28 20:45:33 -0700817
818 void print(const Instruction *inst);
819 void print(const OperationInst *inst);
820 void print(const ReturnInst *inst);
821 void print(const BranchInst *inst);
James Molloy4f788372018-07-24 15:01:27 -0700822 void print(const CondBranchInst *inst);
Chris Lattner4c95a502018-06-23 16:03:42 -0700823
824 unsigned getBBID(const BasicBlock *block) {
825 auto it = basicBlockIDs.find(block);
826 assert(it != basicBlockIDs.end() && "Block not in this function?");
827 return it->second;
828 }
829
830private:
831 const CFGFunction *function;
MLIR Team54b55a22018-07-18 10:16:05 -0700832 DenseMap<const BasicBlock *, unsigned> basicBlockIDs;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700833
Chris Lattner4fd59b02018-07-20 09:35:47 -0700834 void numberValuesInBlock(const BasicBlock *block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700835};
James Molloy87d81022018-07-23 11:44:40 -0700836} // end anonymous namespace
Chris Lattner4c95a502018-06-23 16:03:42 -0700837
Chris Lattner4fd59b02018-07-20 09:35:47 -0700838CFGFunctionPrinter::CFGFunctionPrinter(const CFGFunction *function,
839 const ModulePrinter &other)
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700840 : FunctionPrinter(other), function(function) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700841 // Each basic block gets a unique ID per function.
842 unsigned blockID = 0;
Chris Lattnerf8cce872018-07-20 09:28:54 -0700843 for (auto &block : *function) {
844 basicBlockIDs[&block] = blockID++;
Chris Lattner4fd59b02018-07-20 09:35:47 -0700845 numberValuesInBlock(&block);
Chris Lattnerf8cce872018-07-20 09:28:54 -0700846 }
847}
848
849/// Number all of the SSA values in the specified basic block.
Chris Lattner4fd59b02018-07-20 09:35:47 -0700850void CFGFunctionPrinter::numberValuesInBlock(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700851 for (auto *arg : block->getArguments()) {
852 numberValueID(arg);
853 }
Chris Lattnerf8cce872018-07-20 09:28:54 -0700854 for (auto &op : *block) {
855 // We number instruction that have results, and we only number the first
856 // result.
857 if (op.getNumResults() != 0)
858 numberValueID(op.getResult(0));
859 }
860
861 // Terminators do not define values.
Chris Lattner4c95a502018-06-23 16:03:42 -0700862}
863
Chris Lattner4fd59b02018-07-20 09:35:47 -0700864void CFGFunctionPrinter::print() {
Chris Lattner4c95a502018-06-23 16:03:42 -0700865 os << "cfgfunc ";
Chris Lattner4fd59b02018-07-20 09:35:47 -0700866 printFunctionSignature(getFunction());
Chris Lattner4c95a502018-06-23 16:03:42 -0700867 os << " {\n";
868
James Molloy87d81022018-07-23 11:44:40 -0700869 for (auto &block : *function)
870 print(&block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700871 os << "}\n\n";
872}
873
Chris Lattner4fd59b02018-07-20 09:35:47 -0700874void CFGFunctionPrinter::print(const BasicBlock *block) {
James Molloy61a656c2018-07-22 15:45:24 -0700875 os << "bb" << getBBID(block);
Chris Lattner4c95a502018-06-23 16:03:42 -0700876
James Molloy61a656c2018-07-22 15:45:24 -0700877 if (!block->args_empty()) {
878 os << '(';
879 interleaveComma(block->getArguments(), [&](const BBArgument *arg) {
880 printValueID(arg);
881 os << ": ";
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700882 printType(arg->getType());
James Molloy61a656c2018-07-22 15:45:24 -0700883 });
884 os << ')';
885 }
Chris Lattner25ce3062018-07-27 11:10:12 -0700886 os << ':';
887
888 // Print out some context information about the predecessors of this block.
889 if (!block->getFunction()) {
890 os << "\t// block is not in a function!";
891 } else if (block->hasNoPredecessors()) {
892 // Don't print "no predecessors" for the entry block.
893 if (block != &block->getFunction()->front())
894 os << "\t// no predecessors";
895 } else if (auto *pred = block->getSinglePredecessor()) {
896 os << "\t// pred: bb" << getBBID(pred);
897 } else {
898 // We want to print the predecessors in increasing numeric order, not in
899 // whatever order the use-list is in, so gather and sort them.
900 SmallVector<unsigned, 4> predIDs;
901 for (auto *pred : block->getPredecessors())
902 predIDs.push_back(getBBID(pred));
903 llvm::array_pod_sort(predIDs.begin(), predIDs.end());
904
905 os << "\t// " << predIDs.size() << " preds: ";
906
907 interleaveComma(predIDs, [&](unsigned predID) { os << "bb" << predID; });
908 }
909 os << '\n';
James Molloy61a656c2018-07-22 15:45:24 -0700910
Jacques Pienaarb020c542018-07-15 00:06:54 -0700911 for (auto &inst : block->getOperations()) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700912 os << " ";
Chris Lattner3a467cc2018-07-01 20:28:00 -0700913 print(&inst);
James Molloy61a656c2018-07-22 15:45:24 -0700914 os << '\n';
Jacques Pienaarb020c542018-07-15 00:06:54 -0700915 }
Chris Lattner4c95a502018-06-23 16:03:42 -0700916
917 print(block->getTerminator());
James Molloy61a656c2018-07-22 15:45:24 -0700918 os << '\n';
Chris Lattner4c95a502018-06-23 16:03:42 -0700919}
920
Chris Lattner4fd59b02018-07-20 09:35:47 -0700921void CFGFunctionPrinter::print(const Instruction *inst) {
Chris Lattner4c95a502018-06-23 16:03:42 -0700922 switch (inst->getKind()) {
Chris Lattnered65a732018-06-28 20:45:33 -0700923 case Instruction::Kind::Operation:
924 return print(cast<OperationInst>(inst));
Chris Lattnerf6d80a02018-06-24 11:18:29 -0700925 case TerminatorInst::Kind::Branch:
Chris Lattnered65a732018-06-28 20:45:33 -0700926 return print(cast<BranchInst>(inst));
James Molloy4f788372018-07-24 15:01:27 -0700927 case TerminatorInst::Kind::CondBranch:
928 return print(cast<CondBranchInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700929 case TerminatorInst::Kind::Return:
Chris Lattnered65a732018-06-28 20:45:33 -0700930 return print(cast<ReturnInst>(inst));
Chris Lattner4c95a502018-06-23 16:03:42 -0700931 }
932}
933
Chris Lattner4fd59b02018-07-20 09:35:47 -0700934void CFGFunctionPrinter::print(const OperationInst *inst) {
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -0700935 printOperation(inst);
Chris Lattner3b2ef762018-07-18 15:31:25 -0700936}
Chris Lattner1604e472018-07-23 08:42:19 -0700937
Chris Lattner4fd59b02018-07-20 09:35:47 -0700938void CFGFunctionPrinter::print(const BranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700939 os << "br bb" << getBBID(inst->getDest());
Chris Lattner1604e472018-07-23 08:42:19 -0700940
941 if (inst->getNumOperands() != 0) {
942 os << '(';
943 // TODO: Use getOperands() when we have it.
944 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
945 printValueID(operand.get());
946 });
947 os << ") : ";
948 interleaveComma(inst->getInstOperands(), [&](const InstOperand &operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700949 printType(operand.get()->getType());
Chris Lattner1604e472018-07-23 08:42:19 -0700950 });
951 }
Chris Lattnered65a732018-06-28 20:45:33 -0700952}
Chris Lattner1604e472018-07-23 08:42:19 -0700953
James Molloy4f788372018-07-24 15:01:27 -0700954void CFGFunctionPrinter::print(const CondBranchInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700955 os << "cond_br ";
James Molloy4f788372018-07-24 15:01:27 -0700956 printValueID(inst->getCondition());
957
958 os << ", bb" << getBBID(inst->getTrueDest());
959 if (inst->getNumTrueOperands() != 0) {
960 os << '(';
961 interleaveComma(inst->getTrueOperands(),
962 [&](const CFGValue *operand) { printValueID(operand); });
963 os << " : ";
964 interleaveComma(inst->getTrueOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700965 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700966 });
967 os << ")";
968 }
969
970 os << ", bb" << getBBID(inst->getFalseDest());
971 if (inst->getNumFalseOperands() != 0) {
972 os << '(';
973 interleaveComma(inst->getFalseOperands(),
974 [&](const CFGValue *operand) { printValueID(operand); });
975 os << " : ";
976 interleaveComma(inst->getFalseOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700977 printType(operand->getType());
James Molloy4f788372018-07-24 15:01:27 -0700978 });
979 os << ")";
980 }
981}
982
Chris Lattner40746442018-07-21 14:32:09 -0700983void CFGFunctionPrinter::print(const ReturnInst *inst) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -0700984 os << "return";
Chris Lattner40746442018-07-21 14:32:09 -0700985
James Molloy6bf60c22018-08-02 08:28:20 -0700986 if (inst->getNumOperands() == 0)
987 return;
Chris Lattner40746442018-07-21 14:32:09 -0700988
James Molloy6bf60c22018-08-02 08:28:20 -0700989 os << ' ';
James Molloy4f788372018-07-24 15:01:27 -0700990 interleaveComma(inst->getOperands(),
991 [&](const CFGValue *operand) { printValueID(operand); });
992 os << " : ";
Chris Lattnerac591f12018-07-22 21:02:26 -0700993 interleaveComma(inst->getOperands(), [&](const CFGValue *operand) {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -0700994 printType(operand->getType());
Chris Lattner40746442018-07-21 14:32:09 -0700995 });
996}
MLIR Team54b55a22018-07-18 10:16:05 -0700997
Chris Lattner4fd59b02018-07-20 09:35:47 -0700998void ModulePrinter::print(const CFGFunction *fn) {
999 CFGFunctionPrinter(fn, *this).print();
Chris Lattnered65a732018-06-28 20:45:33 -07001000}
1001
Chris Lattner4c95a502018-06-23 16:03:42 -07001002//===----------------------------------------------------------------------===//
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001003// ML Function printing
Chris Lattner4c95a502018-06-23 16:03:42 -07001004//===----------------------------------------------------------------------===//
1005
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001006namespace {
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001007class MLFunctionPrinter : public FunctionPrinter {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001008public:
Chris Lattner4fd59b02018-07-20 09:35:47 -07001009 MLFunctionPrinter(const MLFunction *function, const ModulePrinter &other);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001010
1011 const MLFunction *getFunction() const { return function; }
1012
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001013 // Prints ML function
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001014 void print();
1015
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001016 // Methods to print ML function statements
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001017 void print(const Statement *stmt);
Tatiana Shpeismanfa412f72018-07-09 17:42:46 -07001018 void print(const OperationStmt *stmt);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001019 void print(const ForStmt *stmt);
1020 void print(const IfStmt *stmt);
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001021 void print(const StmtBlock *block);
1022
1023 // Number of spaces used for indenting nested statements
1024 const static unsigned indentWidth = 2;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001025
1026private:
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001027 void numberValues();
1028
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001029 const MLFunction *function;
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001030 int numSpaces;
1031};
James Molloy87d81022018-07-23 11:44:40 -07001032} // end anonymous namespace
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001033
Chris Lattner4fd59b02018-07-20 09:35:47 -07001034MLFunctionPrinter::MLFunctionPrinter(const MLFunction *function,
1035 const ModulePrinter &other)
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001036 : FunctionPrinter(other), function(function), numSpaces(0) {
1037 numberValues();
1038}
1039
1040/// Number all of the SSA values in this ML function.
1041void MLFunctionPrinter::numberValues() {
1042 // Visits all operation statements and numbers the first result.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001043 struct NumberValuesPass : public StmtWalker<NumberValuesPass> {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001044 NumberValuesPass(MLFunctionPrinter *printer) : printer(printer) {}
1045 void visitOperationStmt(OperationStmt *stmt) {
1046 if (stmt->getNumResults() != 0)
1047 printer->numberValueID(stmt->getResult(0));
1048 }
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001049 void visitForStmt(ForStmt *stmt) { printer->numberValueID(stmt); }
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001050 MLFunctionPrinter *printer;
1051 };
1052
1053 NumberValuesPass pass(this);
1054 // TODO: it'd be cleaner to have constant visitor istead of using const_cast.
Uday Bondhugula081d9e72018-07-27 10:58:14 -07001055 pass.walk(const_cast<MLFunction *>(function));
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001056}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001057
Chris Lattner4fd59b02018-07-20 09:35:47 -07001058void MLFunctionPrinter::print() {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001059 os << "mlfunc ";
1060 // FIXME: should print argument names rather than just signature
Chris Lattner4fd59b02018-07-20 09:35:47 -07001061 printFunctionSignature(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001062 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001063 print(function);
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001064 os << " return\n";
1065 os << "}\n\n";
1066}
1067
Chris Lattner4fd59b02018-07-20 09:35:47 -07001068void MLFunctionPrinter::print(const StmtBlock *block) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001069 numSpaces += indentWidth;
Jacques Pienaarb020c542018-07-15 00:06:54 -07001070 for (auto &stmt : block->getStatements()) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001071 print(&stmt);
Jacques Pienaarb020c542018-07-15 00:06:54 -07001072 os << "\n";
1073 }
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001074 numSpaces -= indentWidth;
1075}
1076
Chris Lattner4fd59b02018-07-20 09:35:47 -07001077void MLFunctionPrinter::print(const Statement *stmt) {
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001078 switch (stmt->getKind()) {
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001079 case Statement::Kind::Operation:
1080 return print(cast<OperationStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001081 case Statement::Kind::For:
1082 return print(cast<ForStmt>(stmt));
1083 case Statement::Kind::If:
1084 return print(cast<IfStmt>(stmt));
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001085 }
1086}
1087
Chris Lattner4fd59b02018-07-20 09:35:47 -07001088void MLFunctionPrinter::print(const OperationStmt *stmt) {
Tatiana Shpeisman60bf7be2018-07-26 18:09:20 -07001089 os.indent(numSpaces);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001090 printOperation(stmt);
1091}
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001092
Chris Lattner4fd59b02018-07-20 09:35:47 -07001093void MLFunctionPrinter::print(const ForStmt *stmt) {
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001094 os.indent(numSpaces) << "for ";
Tatiana Shpeismanc9c4b342018-07-31 07:40:14 -07001095 printOperand(stmt);
Tatiana Shpeisman3838db72018-07-30 15:18:10 -07001096 os << " = " << *stmt->getLowerBound();
Tatiana Shpeisman1da50c42018-07-19 09:52:39 -07001097 os << " to " << *stmt->getUpperBound();
1098 if (stmt->getStep()->getValue() != 1)
1099 os << " step " << *stmt->getStep();
1100
1101 os << " {\n";
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001102 print(static_cast<const StmtBlock *>(stmt));
Tatiana Shpeisman565b9642018-07-16 11:47:09 -07001103 os.indent(numSpaces) << "}";
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001104}
1105
Chris Lattner4fd59b02018-07-20 09:35:47 -07001106void MLFunctionPrinter::print(const IfStmt *stmt) {
Tatiana Shpeisman1bcfe982018-07-13 13:03:13 -07001107 os.indent(numSpaces) << "if () {\n";
1108 print(stmt->getThenClause());
1109 os.indent(numSpaces) << "}";
1110 if (stmt->hasElseClause()) {
1111 os << " else {\n";
1112 print(stmt->getElseClause());
1113 os.indent(numSpaces) << "}";
1114 }
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001115}
1116
Chris Lattner4fd59b02018-07-20 09:35:47 -07001117void ModulePrinter::print(const MLFunction *fn) {
1118 MLFunctionPrinter(fn, *this).print();
MLIR Team4718bc92018-07-17 16:56:54 -07001119}
1120
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001121//===----------------------------------------------------------------------===//
1122// print and dump methods
1123//===----------------------------------------------------------------------===//
Chris Lattnered65a732018-06-28 20:45:33 -07001124
MLIR Teamb61885d2018-07-18 16:29:21 -07001125void Attribute::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001126 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001127 ModulePrinter(os, state).printAttribute(this);
MLIR Teamb61885d2018-07-18 16:29:21 -07001128}
1129
James Molloy87d81022018-07-23 11:44:40 -07001130void Attribute::dump() const { print(llvm::errs()); }
MLIR Teamb61885d2018-07-18 16:29:21 -07001131
MLIR Team4718bc92018-07-17 16:56:54 -07001132void Type::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001133 ModuleState state(getContext());
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001134 ModulePrinter(os, state).printType(this);
MLIR Team4718bc92018-07-17 16:56:54 -07001135}
1136
MLIR Team54b55a22018-07-18 10:16:05 -07001137void Type::dump() const { print(llvm::errs()); }
MLIR Team4718bc92018-07-17 16:56:54 -07001138
MLIR Team718c82f2018-07-16 09:45:22 -07001139void AffineMap::dump() const {
1140 print(llvm::errs());
1141 llvm::errs() << "\n";
1142}
Uday Bondhugula3934d4d2018-07-09 09:00:25 -07001143
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001144void AffineExpr::dump() const {
1145 print(llvm::errs());
1146 llvm::errs() << "\n";
1147}
1148
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001149void AffineExpr::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001150 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001151 ModulePrinter(os, state).printAffineExpr(this);
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001152}
1153
1154void AffineMap::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001155 ModuleState state(/*no context is known*/ nullptr);
Chris Lattnerdd0c2ca2018-07-24 16:07:22 -07001156 ModulePrinter(os, state).printAffineMap(this);
Chris Lattner4fd59b02018-07-20 09:35:47 -07001157}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001158
Chris Lattner384da8c2018-08-02 17:16:58 -07001159void SSAValue::print(raw_ostream &os) const {
1160 switch (getKind()) {
1161 case SSAValueKind::BBArgument:
1162 // TODO: Improve this.
1163 os << "<bb argument>\n";
1164 return;
1165 case SSAValueKind::InstResult:
1166 return getDefiningInst()->print(os);
1167 case SSAValueKind::FnArgument:
1168 // TODO: Improve this.
1169 os << "<function argument>\n";
1170 return;
1171 case SSAValueKind::StmtResult:
1172 return getDefiningStmt()->print(os);
1173 case SSAValueKind::ForStmt:
1174 return cast<ForStmt>(this)->print(os);
1175 }
1176}
1177
1178void SSAValue::dump() const { print(llvm::errs()); }
1179
Chris Lattner4fd59b02018-07-20 09:35:47 -07001180void Instruction::print(raw_ostream &os) const {
1181 ModuleState state(getFunction()->getContext());
1182 ModulePrinter modulePrinter(os, state);
1183 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
1184}
Uday Bondhugula015cbb12018-07-03 20:16:08 -07001185
Chris Lattner4fd59b02018-07-20 09:35:47 -07001186void Instruction::dump() const {
1187 print(llvm::errs());
1188 llvm::errs() << "\n";
Uday Bondhugulafaf37dd2018-06-29 18:09:29 -07001189}
1190
Chris Lattner4c95a502018-06-23 16:03:42 -07001191void BasicBlock::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001192 ModuleState state(getFunction()->getContext());
1193 ModulePrinter modulePrinter(os, state);
1194 CFGFunctionPrinter(getFunction(), modulePrinter).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001195}
1196
MLIR Team54b55a22018-07-18 10:16:05 -07001197void BasicBlock::dump() const { print(llvm::errs()); }
Chris Lattner4c95a502018-06-23 16:03:42 -07001198
Tatiana Shpeismanbf079c92018-07-03 17:51:28 -07001199void Statement::print(raw_ostream &os) const {
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001200 MLFunction *function = findFunction();
1201 ModuleState state(function->getContext());
Chris Lattner4fd59b02018-07-20 09:35:47 -07001202 ModulePrinter modulePrinter(os, state);
Tatiana Shpeismand880b352018-07-31 23:14:16 -07001203 MLFunctionPrinter(function, modulePrinter).print(this);
Tatiana Shpeismanc96b5872018-06-28 17:02:32 -07001204}
1205
MLIR Team54b55a22018-07-18 10:16:05 -07001206void Statement::dump() const { print(llvm::errs()); }
Jacques Pienaarb020c542018-07-15 00:06:54 -07001207
Chris Lattner4c95a502018-06-23 16:03:42 -07001208void Function::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001209 ModuleState state(getContext());
1210 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001211}
1212
MLIR Team54b55a22018-07-18 10:16:05 -07001213void Function::dump() const { print(llvm::errs()); }
1214
Chris Lattner4c95a502018-06-23 16:03:42 -07001215void Module::print(raw_ostream &os) const {
Chris Lattner4fd59b02018-07-20 09:35:47 -07001216 ModuleState state(getContext());
1217 state.initialize(this);
1218 ModulePrinter(os, state).print(this);
Chris Lattner4c95a502018-06-23 16:03:42 -07001219}
1220
MLIR Team54b55a22018-07-18 10:16:05 -07001221void Module::dump() const { print(llvm::errs()); }