1 //===- IRPrinting.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PassDetail.h"
10 #include "mlir/IR/BuiltinOps.h"
11 #include "mlir/Pass/PassManager.h"
12 #include "llvm/Support/Format.h"
13 #include "llvm/Support/FormatVariadic.h"
14 #include "llvm/Support/SHA1.h"
15 
16 using namespace mlir;
17 using namespace mlir::detail;
18 
19 namespace {
20 //===----------------------------------------------------------------------===//
21 // OperationFingerPrint
22 //===----------------------------------------------------------------------===//
23 
24 /// A unique fingerprint for a specific operation, and all of it's internal
25 /// operations.
26 class OperationFingerPrint {
27 public:
28   OperationFingerPrint(Operation *topOp) {
29     llvm::SHA1 hasher;
30 
31     // Hash each of the operations based upon their mutable bits:
32     topOp->walk([&](Operation *op) {
33       //   - Operation pointer
34       addDataToHash(hasher, op);
35       //   - Attributes
36       addDataToHash(hasher, op->getMutableAttrDict());
37       //   - Blocks in Regions
38       for (Region &region : op->getRegions()) {
39         for (Block &block : region) {
40           addDataToHash(hasher, &block);
41           for (BlockArgument arg : block.getArguments())
42             addDataToHash(hasher, arg);
43         }
44       }
45       //   - Location
46       addDataToHash(hasher, op->getLoc().getAsOpaquePointer());
47       //   - Operands
48       for (Value operand : op->getOperands())
49         addDataToHash(hasher, operand);
50       //   - Successors
51       for (unsigned i = 0, e = op->getNumSuccessors(); i != e; ++i)
52         addDataToHash(hasher, op->getSuccessor(i));
53     });
54     hash = hasher.result();
55   }
56 
57   bool operator==(const OperationFingerPrint &other) const {
58     return hash == other.hash;
59   }
60   bool operator!=(const OperationFingerPrint &other) const {
61     return !(*this == other);
62   }
63 
64 private:
65   template <typename T> void addDataToHash(llvm::SHA1 &hasher, const T &data) {
66     hasher.update(
67         ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(&data), sizeof(T)));
68   }
69 
70   SmallString<20> hash;
71 };
72 
73 //===----------------------------------------------------------------------===//
74 // IRPrinter
75 //===----------------------------------------------------------------------===//
76 
77 class IRPrinterInstrumentation : public PassInstrumentation {
78 public:
79   IRPrinterInstrumentation(std::unique_ptr<PassManager::IRPrinterConfig> config)
80       : config(std::move(config)) {}
81 
82 private:
83   /// Instrumentation hooks.
84   void runBeforePass(Pass *pass, Operation *op) override;
85   void runAfterPass(Pass *pass, Operation *op) override;
86   void runAfterPassFailed(Pass *pass, Operation *op) override;
87 
88   /// Configuration to use.
89   std::unique_ptr<PassManager::IRPrinterConfig> config;
90 
91   /// The following is a set of fingerprints for operations that are currently
92   /// being operated on in a pass. This field is only used when the
93   /// configuration asked for change detection.
94   DenseMap<Pass *, OperationFingerPrint> beforePassFingerPrints;
95 };
96 } // end anonymous namespace
97 
98 static void printIR(Operation *op, bool printModuleScope, raw_ostream &out,
99                     OpPrintingFlags flags) {
100   // Check to see if we are printing the top-level module.
101   auto module = dyn_cast<ModuleOp>(op);
102   if (module && !op->getBlock())
103     return module.print(out << "\n", flags);
104 
105   // Otherwise, check to see if we are not printing at module scope.
106   if (!printModuleScope)
107     return op->print(out << "\n", flags.useLocalScope());
108 
109   // Otherwise, we are printing at module scope.
110   out << " ('" << op->getName() << "' operation";
111   if (auto symbolName =
112           op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName()))
113     out << ": @" << symbolName.getValue();
114   out << ")\n";
115 
116   // Find the top-level module operation.
117   auto *topLevelOp = op;
118   while (auto *parentOp = topLevelOp->getParentOp())
119     topLevelOp = parentOp;
120 
121   // Check to see if the top-level operation is actually a module in the case of
122   // invalid-ir.
123   if (auto module = dyn_cast<ModuleOp>(topLevelOp))
124     module.print(out, flags);
125   else
126     topLevelOp->print(out, flags);
127 }
128 
129 /// Instrumentation hooks.
130 void IRPrinterInstrumentation::runBeforePass(Pass *pass, Operation *op) {
131   if (isa<OpToOpPassAdaptor>(pass))
132     return;
133   // If the config asked to detect changes, record the current fingerprint.
134   if (config->shouldPrintAfterOnlyOnChange())
135     beforePassFingerPrints.try_emplace(pass, op);
136 
137   config->printBeforeIfEnabled(pass, op, [&](raw_ostream &out) {
138     out << formatv("// *** IR Dump Before {0} ***", pass->getName());
139     printIR(op, config->shouldPrintAtModuleScope(), out,
140             config->getOpPrintingFlags());
141     out << "\n\n";
142   });
143 }
144 
145 void IRPrinterInstrumentation::runAfterPass(Pass *pass, Operation *op) {
146   if (isa<OpToOpPassAdaptor>(pass))
147     return;
148   // If the config asked to detect changes, compare the current fingerprint with
149   // the previous.
150   if (config->shouldPrintAfterOnlyOnChange()) {
151     auto fingerPrintIt = beforePassFingerPrints.find(pass);
152     assert(fingerPrintIt != beforePassFingerPrints.end() &&
153            "expected valid fingerprint");
154     // If the fingerprints are the same, we don't print the IR.
155     if (fingerPrintIt->second == OperationFingerPrint(op)) {
156       beforePassFingerPrints.erase(fingerPrintIt);
157       return;
158     }
159     beforePassFingerPrints.erase(fingerPrintIt);
160   }
161 
162   config->printAfterIfEnabled(pass, op, [&](raw_ostream &out) {
163     out << formatv("// *** IR Dump After {0} ***", pass->getName());
164     printIR(op, config->shouldPrintAtModuleScope(), out,
165             config->getOpPrintingFlags());
166     out << "\n\n";
167   });
168 }
169 
170 void IRPrinterInstrumentation::runAfterPassFailed(Pass *pass, Operation *op) {
171   if (isa<OpToOpPassAdaptor>(pass))
172     return;
173   if (config->shouldPrintAfterOnlyOnChange())
174     beforePassFingerPrints.erase(pass);
175 
176   config->printAfterIfEnabled(pass, op, [&](raw_ostream &out) {
177     out << formatv("// *** IR Dump After {0} Failed ***", pass->getName());
178     printIR(op, config->shouldPrintAtModuleScope(), out,
179             OpPrintingFlags().printGenericOpForm());
180     out << "\n\n";
181   });
182 }
183 
184 //===----------------------------------------------------------------------===//
185 // IRPrinterConfig
186 //===----------------------------------------------------------------------===//
187 
188 /// Initialize the configuration.
189 PassManager::IRPrinterConfig::IRPrinterConfig(bool printModuleScope,
190                                               bool printAfterOnlyOnChange,
191                                               OpPrintingFlags opPrintingFlags)
192     : printModuleScope(printModuleScope),
193       printAfterOnlyOnChange(printAfterOnlyOnChange),
194       opPrintingFlags(opPrintingFlags) {}
195 PassManager::IRPrinterConfig::~IRPrinterConfig() {}
196 
197 /// A hook that may be overridden by a derived config that checks if the IR
198 /// of 'operation' should be dumped *before* the pass 'pass' has been
199 /// executed. If the IR should be dumped, 'printCallback' should be invoked
200 /// with the stream to dump into.
201 void PassManager::IRPrinterConfig::printBeforeIfEnabled(
202     Pass *pass, Operation *operation, PrintCallbackFn printCallback) {
203   // By default, never print.
204 }
205 
206 /// A hook that may be overridden by a derived config that checks if the IR
207 /// of 'operation' should be dumped *after* the pass 'pass' has been
208 /// executed. If the IR should be dumped, 'printCallback' should be invoked
209 /// with the stream to dump into.
210 void PassManager::IRPrinterConfig::printAfterIfEnabled(
211     Pass *pass, Operation *operation, PrintCallbackFn printCallback) {
212   // By default, never print.
213 }
214 
215 //===----------------------------------------------------------------------===//
216 // PassManager
217 //===----------------------------------------------------------------------===//
218 
219 namespace {
220 /// Simple wrapper config that allows for the simpler interface defined above.
221 struct BasicIRPrinterConfig : public PassManager::IRPrinterConfig {
222   BasicIRPrinterConfig(
223       std::function<bool(Pass *, Operation *)> shouldPrintBeforePass,
224       std::function<bool(Pass *, Operation *)> shouldPrintAfterPass,
225       bool printModuleScope, bool printAfterOnlyOnChange,
226       OpPrintingFlags opPrintingFlags, raw_ostream &out)
227       : IRPrinterConfig(printModuleScope, printAfterOnlyOnChange,
228                         opPrintingFlags),
229         shouldPrintBeforePass(shouldPrintBeforePass),
230         shouldPrintAfterPass(shouldPrintAfterPass), out(out) {
231     assert((shouldPrintBeforePass || shouldPrintAfterPass) &&
232            "expected at least one valid filter function");
233   }
234 
235   void printBeforeIfEnabled(Pass *pass, Operation *operation,
236                             PrintCallbackFn printCallback) final {
237     if (shouldPrintBeforePass && shouldPrintBeforePass(pass, operation))
238       printCallback(out);
239   }
240 
241   void printAfterIfEnabled(Pass *pass, Operation *operation,
242                            PrintCallbackFn printCallback) final {
243     if (shouldPrintAfterPass && shouldPrintAfterPass(pass, operation))
244       printCallback(out);
245   }
246 
247   /// Filter functions for before and after pass execution.
248   std::function<bool(Pass *, Operation *)> shouldPrintBeforePass;
249   std::function<bool(Pass *, Operation *)> shouldPrintAfterPass;
250 
251   /// The stream to output to.
252   raw_ostream &out;
253 };
254 } // end anonymous namespace
255 
256 /// Add an instrumentation to print the IR before and after pass execution,
257 /// using the provided configuration.
258 void PassManager::enableIRPrinting(std::unique_ptr<IRPrinterConfig> config) {
259   if (config->shouldPrintAtModuleScope() &&
260       getContext()->isMultithreadingEnabled())
261     llvm::report_fatal_error("IR printing can't be setup on a pass-manager "
262                              "without disabling multi-threading first.");
263   addInstrumentation(
264       std::make_unique<IRPrinterInstrumentation>(std::move(config)));
265 }
266 
267 /// Add an instrumentation to print the IR before and after pass execution.
268 void PassManager::enableIRPrinting(
269     std::function<bool(Pass *, Operation *)> shouldPrintBeforePass,
270     std::function<bool(Pass *, Operation *)> shouldPrintAfterPass,
271     bool printModuleScope, bool printAfterOnlyOnChange, raw_ostream &out,
272     OpPrintingFlags opPrintingFlags) {
273   enableIRPrinting(std::make_unique<BasicIRPrinterConfig>(
274       std::move(shouldPrintBeforePass), std::move(shouldPrintAfterPass),
275       printModuleScope, printAfterOnlyOnChange, opPrintingFlags, out));
276 }
277