xref: /llvm-project-15.0.7/mlir/lib/Pass/Pass.cpp (revision 7518006d)
1 //===- Pass.cpp - Pass infrastructure implementation ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements common pass infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Pass/Pass.h"
14 #include "PassDetail.h"
15 #include "mlir/IR/Diagnostics.h"
16 #include "mlir/IR/Dialect.h"
17 #include "mlir/IR/Module.h"
18 #include "mlir/IR/Verifier.h"
19 #include "mlir/Support/FileUtilities.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/Parallel.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 
30 using namespace mlir;
31 using namespace mlir::detail;
32 
33 //===----------------------------------------------------------------------===//
34 // Pass
35 //===----------------------------------------------------------------------===//
36 
37 /// Out of line virtual method to ensure vtables and metadata are emitted to a
38 /// single .o file.
39 void Pass::anchor() {}
40 
41 /// Attempt to initialize the options of this pass from the given string.
42 LogicalResult Pass::initializeOptions(StringRef options) {
43   return passOptions.parseFromString(options);
44 }
45 
46 /// Copy the option values from 'other', which is another instance of this
47 /// pass.
48 void Pass::copyOptionValuesFrom(const Pass *other) {
49   passOptions.copyOptionValuesFrom(other->passOptions);
50 }
51 
52 /// Prints out the pass in the textual representation of pipelines. If this is
53 /// an adaptor pass, print with the op_name(sub_pass,...) format.
54 void Pass::printAsTextualPipeline(raw_ostream &os) {
55   // Special case for adaptors to use the 'op_name(sub_passes)' format.
56   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(this)) {
57     llvm::interleaveComma(adaptor->getPassManagers(), os,
58                           [&](OpPassManager &pm) {
59                             os << pm.getOpName() << "(";
60                             pm.printAsTextualPipeline(os);
61                             os << ")";
62                           });
63     return;
64   }
65   // Otherwise, print the pass argument followed by its options. If the pass
66   // doesn't have an argument, print the name of the pass to give some indicator
67   // of what pass was run.
68   StringRef argument = getArgument();
69   if (!argument.empty())
70     os << argument;
71   else
72     os << "unknown<" << getName() << ">";
73   passOptions.print(os);
74 }
75 
76 /// Forwarding function to execute this pass.
77 LogicalResult Pass::run(Operation *op, AnalysisManager am) {
78   passState.emplace(op, am);
79 
80   // Instrument before the pass has run.
81   auto pi = am.getPassInstrumentor();
82   if (pi)
83     pi->runBeforePass(this, op);
84 
85   // Invoke the virtual runOnOperation method.
86   runOnOperation();
87 
88   // Invalidate any non preserved analyses.
89   am.invalidate(passState->preservedAnalyses);
90 
91   // Instrument after the pass has run.
92   bool passFailed = passState->irAndPassFailed.getInt();
93   if (pi) {
94     if (passFailed)
95       pi->runAfterPassFailed(this, op);
96     else
97       pi->runAfterPass(this, op);
98   }
99 
100   // Return if the pass signaled a failure.
101   return failure(passFailed);
102 }
103 
104 //===----------------------------------------------------------------------===//
105 // Verifier Passes
106 //===----------------------------------------------------------------------===//
107 
108 void VerifierPass::runOnOperation() {
109   if (failed(verify(getOperation())))
110     signalPassFailure();
111   markAllAnalysesPreserved();
112 }
113 
114 //===----------------------------------------------------------------------===//
115 // OpPassManagerImpl
116 //===----------------------------------------------------------------------===//
117 
118 namespace mlir {
119 namespace detail {
120 struct OpPassManagerImpl {
121   OpPassManagerImpl(OperationName name, bool verifyPasses)
122       : name(name), verifyPasses(verifyPasses) {}
123 
124   /// Merge the passes of this pass manager into the one provided.
125   void mergeInto(OpPassManagerImpl &rhs);
126 
127   /// Nest a new operation pass manager for the given operation kind under this
128   /// pass manager.
129   OpPassManager &nest(const OperationName &nestedName);
130   OpPassManager &nest(StringRef nestedName) {
131     return nest(OperationName(nestedName, getContext()));
132   }
133 
134   /// Add the given pass to this pass manager. If this pass has a concrete
135   /// operation type, it must be the same type as this pass manager.
136   void addPass(std::unique_ptr<Pass> pass);
137 
138   /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
139   /// recursively through the pipeline graph.
140   void coalesceAdjacentAdaptorPasses();
141 
142   /// Split all of AdaptorPasses such that each adaptor only contains one leaf
143   /// pass.
144   void splitAdaptorPasses();
145 
146   /// Return an instance of the context.
147   MLIRContext *getContext() const {
148     return name.getAbstractOperation()->dialect.getContext();
149   }
150 
151   /// The name of the operation that passes of this pass manager operate on.
152   OperationName name;
153 
154   /// Flag that specifies if the IR should be verified after each pass has run.
155   bool verifyPasses : 1;
156 
157   /// The set of passes to run as part of this pass manager.
158   std::vector<std::unique_ptr<Pass>> passes;
159 };
160 } // end namespace detail
161 } // end namespace mlir
162 
163 void OpPassManagerImpl::mergeInto(OpPassManagerImpl &rhs) {
164   assert(name == rhs.name && "merging unrelated pass managers");
165   for (auto &pass : passes)
166     rhs.passes.push_back(std::move(pass));
167   passes.clear();
168 }
169 
170 OpPassManager &OpPassManagerImpl::nest(const OperationName &nestedName) {
171   OpPassManager nested(nestedName, verifyPasses);
172   auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
173   addPass(std::unique_ptr<Pass>(adaptor));
174   return adaptor->getPassManagers().front();
175 }
176 
177 void OpPassManagerImpl::addPass(std::unique_ptr<Pass> pass) {
178   // If this pass runs on a different operation than this pass manager, then
179   // implicitly nest a pass manager for this operation.
180   auto passOpName = pass->getOpName();
181   if (passOpName && passOpName != name.getStringRef())
182     return nest(*passOpName).addPass(std::move(pass));
183 
184   passes.emplace_back(std::move(pass));
185   if (verifyPasses)
186     passes.emplace_back(std::make_unique<VerifierPass>());
187 }
188 
189 void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() {
190   // Bail out early if there are no adaptor passes.
191   if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) {
192         return isa<OpToOpPassAdaptor>(pass.get());
193       }))
194     return;
195 
196   // Walk the pass list and merge adjacent adaptors.
197   OpToOpPassAdaptor *lastAdaptor = nullptr;
198   for (auto it = passes.begin(), e = passes.end(); it != e; ++it) {
199     // Check to see if this pass is an adaptor.
200     if (auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(it->get())) {
201       // If it is the first adaptor in a possible chain, remember it and
202       // continue.
203       if (!lastAdaptor) {
204         lastAdaptor = currentAdaptor;
205         continue;
206       }
207 
208       // Otherwise, merge into the existing adaptor and delete the current one.
209       currentAdaptor->mergeInto(*lastAdaptor);
210       it->reset();
211 
212       // If the verifier is enabled, then next pass is a verifier run so
213       // drop it. Verifier passes are inserted after every pass, so this one
214       // would be a duplicate.
215       if (verifyPasses) {
216         assert(std::next(it) != e && isa<VerifierPass>(*std::next(it)));
217         (++it)->reset();
218       }
219     } else if (lastAdaptor && !isa<VerifierPass>(*it)) {
220       // If this pass is not an adaptor and not a verifier pass, then coalesce
221       // and forget any existing adaptor.
222       for (auto &pm : lastAdaptor->getPassManagers())
223         pm.getImpl().coalesceAdjacentAdaptorPasses();
224       lastAdaptor = nullptr;
225     }
226   }
227 
228   // If there was an adaptor at the end of the manager, coalesce it as well.
229   if (lastAdaptor) {
230     for (auto &pm : lastAdaptor->getPassManagers())
231       pm.getImpl().coalesceAdjacentAdaptorPasses();
232   }
233 
234   // Now that the adaptors have been merged, erase the empty slot corresponding
235   // to the merged adaptors that were nulled-out in the loop above.
236   llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
237 }
238 
239 void OpPassManagerImpl::splitAdaptorPasses() {
240   std::vector<std::unique_ptr<Pass>> oldPasses;
241   std::swap(passes, oldPasses);
242 
243   for (std::unique_ptr<Pass> &pass : oldPasses) {
244     // If this pass isn't an adaptor, move it directly to the new pass list.
245     auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(pass.get());
246     if (!currentAdaptor) {
247       passes.push_back(std::move(pass));
248       continue;
249     }
250 
251     // Otherwise, split the adaptors of each manager within the adaptor.
252     for (OpPassManager &adaptorPM : currentAdaptor->getPassManagers()) {
253       adaptorPM.getImpl().splitAdaptorPasses();
254 
255       // Add all non-verifier passes to this pass manager.
256       for (std::unique_ptr<Pass> &nestedPass : adaptorPM.getImpl().passes) {
257         if (!isa<VerifierPass>(nestedPass.get()))
258           nest(adaptorPM.getOpName()).addPass(std::move(nestedPass));
259       }
260     }
261   }
262 }
263 
264 //===----------------------------------------------------------------------===//
265 // OpPassManager
266 //===----------------------------------------------------------------------===//
267 
268 OpPassManager::OpPassManager(OperationName name, bool verifyPasses)
269     : impl(new OpPassManagerImpl(name, verifyPasses)) {
270   assert(name.getAbstractOperation() &&
271          "OpPassManager can only operate on registered operations");
272   assert(name.getAbstractOperation()->hasProperty(
273              OperationProperty::IsolatedFromAbove) &&
274          "OpPassManager only supports operating on operations marked as "
275          "'IsolatedFromAbove'");
276 }
277 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
278 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
279 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
280   impl.reset(new OpPassManagerImpl(rhs.impl->name, rhs.impl->verifyPasses));
281   for (auto &pass : rhs.impl->passes)
282     impl->passes.emplace_back(pass->clone());
283   return *this;
284 }
285 
286 OpPassManager::~OpPassManager() {}
287 
288 OpPassManager::pass_iterator OpPassManager::begin() {
289   return impl->passes.begin();
290 }
291 OpPassManager::pass_iterator OpPassManager::end() { return impl->passes.end(); }
292 
293 OpPassManager::const_pass_iterator OpPassManager::begin() const {
294   return impl->passes.begin();
295 }
296 OpPassManager::const_pass_iterator OpPassManager::end() const {
297   return impl->passes.end();
298 }
299 
300 /// Run all of the passes in this manager over the current operation.
301 LogicalResult OpPassManager::run(Operation *op, AnalysisManager am) {
302   // Run each of the held passes.
303   for (auto &pass : impl->passes)
304     if (failed(pass->run(op, am)))
305       return failure();
306   return success();
307 }
308 
309 /// Nest a new operation pass manager for the given operation kind under this
310 /// pass manager.
311 OpPassManager &OpPassManager::nest(const OperationName &nestedName) {
312   return impl->nest(nestedName);
313 }
314 OpPassManager &OpPassManager::nest(StringRef nestedName) {
315   return impl->nest(nestedName);
316 }
317 
318 /// Add the given pass to this pass manager. If this pass has a concrete
319 /// operation type, it must be the same type as this pass manager.
320 void OpPassManager::addPass(std::unique_ptr<Pass> pass) {
321   impl->addPass(std::move(pass));
322 }
323 
324 /// Returns the number of passes held by this manager.
325 size_t OpPassManager::size() const { return impl->passes.size(); }
326 
327 /// Returns the internal implementation instance.
328 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
329 
330 /// Return an instance of the context.
331 MLIRContext *OpPassManager::getContext() const { return impl->getContext(); }
332 
333 /// Return the operation name that this pass manager operates on.
334 const OperationName &OpPassManager::getOpName() const { return impl->name; }
335 
336 /// Prints out the given passes as the textual representation of a pipeline.
337 static void printAsTextualPipeline(ArrayRef<std::unique_ptr<Pass>> passes,
338                                    raw_ostream &os) {
339   // Filter out passes that are not part of the public pipeline.
340   auto filteredPasses =
341       llvm::make_filter_range(passes, [](const std::unique_ptr<Pass> &pass) {
342         return !isa<VerifierPass>(pass);
343       });
344   llvm::interleaveComma(filteredPasses, os,
345                         [&](const std::unique_ptr<Pass> &pass) {
346                           pass->printAsTextualPipeline(os);
347                         });
348 }
349 
350 /// Prints out the passes of the pass manager as the textual representation
351 /// of pipelines.
352 void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
353   ::printAsTextualPipeline(impl->passes, os);
354 }
355 
356 static void registerDialectsForPipeline(const OpPassManager &pm,
357                                         DialectRegistry &dialects) {
358   for (const Pass &pass : pm.getPasses())
359     pass.getDependentDialects(dialects);
360 }
361 
362 void OpPassManager::getDependentDialects(DialectRegistry &dialects) const {
363   registerDialectsForPipeline(*this, dialects);
364 }
365 
366 //===----------------------------------------------------------------------===//
367 // OpToOpPassAdaptor
368 //===----------------------------------------------------------------------===//
369 
370 /// Utility to run the given operation and analysis manager on a provided op
371 /// pass manager.
372 static LogicalResult runPipeline(OpPassManager &pm, Operation *op,
373                                  AnalysisManager am) {
374   // Run the pipeline over the provided operation.
375   auto result = pm.run(op, am);
376 
377   // Clear out any computed operation analyses. These analyses won't be used
378   // any more in this pipeline, and this helps reduce the current working set
379   // of memory. If preserving these analyses becomes important in the future
380   // we can re-evaluate this.
381   am.clear();
382   return result;
383 }
384 
385 /// Find an operation pass manager that can operate on an operation of the given
386 /// type, or nullptr if one does not exist.
387 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
388                                          const OperationName &name) {
389   auto it = llvm::find_if(
390       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
391   return it == mgrs.end() ? nullptr : &*it;
392 }
393 
394 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) {
395   mgrs.emplace_back(std::move(mgr));
396 }
397 
398 void OpToOpPassAdaptor::getDependentDialects(DialectRegistry &dialects) const {
399   for (auto &pm : mgrs)
400     pm.getDependentDialects(dialects);
401 }
402 
403 /// Merge the current pass adaptor into given 'rhs'.
404 void OpToOpPassAdaptor::mergeInto(OpToOpPassAdaptor &rhs) {
405   for (auto &pm : mgrs) {
406     // If an existing pass manager exists, then merge the given pass manager
407     // into it.
408     if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
409       pm.getImpl().mergeInto(existingPM->getImpl());
410     } else {
411       // Otherwise, add the given pass manager to the list.
412       rhs.mgrs.emplace_back(std::move(pm));
413     }
414   }
415   mgrs.clear();
416 
417   // After coalescing, sort the pass managers within rhs by name.
418   llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
419                        [](const OpPassManager *lhs, const OpPassManager *rhs) {
420                          return lhs->getOpName().getStringRef().compare(
421                              rhs->getOpName().getStringRef());
422                        });
423 }
424 
425 /// Returns the adaptor pass name.
426 std::string OpToOpPassAdaptor::getAdaptorName() {
427   std::string name = "Pipeline Collection : [";
428   llvm::raw_string_ostream os(name);
429   llvm::interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
430     os << '\'' << pm.getOpName() << '\'';
431   });
432   os << ']';
433   return os.str();
434 }
435 
436 /// Run the held pipeline over all nested operations.
437 void OpToOpPassAdaptor::runOnOperation() {
438   if (getContext().isMultithreadingEnabled())
439     runOnOperationAsyncImpl();
440   else
441     runOnOperationImpl();
442 }
443 
444 /// Run this pass adaptor synchronously.
445 void OpToOpPassAdaptor::runOnOperationImpl() {
446   auto am = getAnalysisManager();
447   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
448                                                         this};
449   auto *instrumentor = am.getPassInstrumentor();
450   for (auto &region : getOperation()->getRegions()) {
451     for (auto &block : region) {
452       for (auto &op : block) {
453         auto *mgr = findPassManagerFor(mgrs, op.getName());
454         if (!mgr)
455           continue;
456 
457         // Run the held pipeline over the current operation.
458         if (instrumentor)
459           instrumentor->runBeforePipeline(mgr->getOpName(), parentInfo);
460         auto result = runPipeline(*mgr, &op, am.slice(&op));
461         if (instrumentor)
462           instrumentor->runAfterPipeline(mgr->getOpName(), parentInfo);
463 
464         if (failed(result))
465           return signalPassFailure();
466       }
467     }
468   }
469 }
470 
471 /// Utility functor that checks if the two ranges of pass managers have a size
472 /// mismatch.
473 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
474                             ArrayRef<OpPassManager> rhs) {
475   return lhs.size() != rhs.size() ||
476          llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
477                       [&](size_t i) { return lhs[i].size() != rhs[i].size(); });
478 }
479 
480 /// Run this pass adaptor synchronously.
481 void OpToOpPassAdaptor::runOnOperationAsyncImpl() {
482   AnalysisManager am = getAnalysisManager();
483 
484   // Create the async executors if they haven't been created, or if the main
485   // pipeline has changed.
486   if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
487     asyncExecutors.assign(llvm::hardware_concurrency().compute_thread_count(),
488                           mgrs);
489 
490   // Run a prepass over the module to collect the operations to execute over.
491   // This ensures that an analysis manager exists for each operation, as well as
492   // providing a queue of operations to execute over.
493   std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
494   for (auto &region : getOperation()->getRegions()) {
495     for (auto &block : region) {
496       for (auto &op : block) {
497         // Add this operation iff the name matches the any of the pass managers.
498         if (findPassManagerFor(mgrs, op.getName()))
499           opAMPairs.emplace_back(&op, am.slice(&op));
500       }
501     }
502   }
503 
504   // A parallel diagnostic handler that provides deterministic diagnostic
505   // ordering.
506   ParallelDiagnosticHandler diagHandler(&getContext());
507 
508   // An index for the current operation/analysis manager pair.
509   std::atomic<unsigned> opIt(0);
510 
511   // Get the current thread for this adaptor.
512   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
513                                                         this};
514   auto *instrumentor = am.getPassInstrumentor();
515 
516   // An atomic failure variable for the async executors.
517   std::atomic<bool> passFailed(false);
518   llvm::parallelForEach(
519       asyncExecutors.begin(),
520       std::next(asyncExecutors.begin(),
521                 std::min(asyncExecutors.size(), opAMPairs.size())),
522       [&](MutableArrayRef<OpPassManager> pms) {
523         for (auto e = opAMPairs.size(); !passFailed && opIt < e;) {
524           // Get the next available operation index.
525           unsigned nextID = opIt++;
526           if (nextID >= e)
527             break;
528 
529           // Set the order id for this thread in the diagnostic handler.
530           diagHandler.setOrderIDForThread(nextID);
531 
532           // Get the pass manager for this operation and execute it.
533           auto &it = opAMPairs[nextID];
534           auto *pm = findPassManagerFor(pms, it.first->getName());
535           assert(pm && "expected valid pass manager for operation");
536 
537           if (instrumentor)
538             instrumentor->runBeforePipeline(pm->getOpName(), parentInfo);
539           auto pipelineResult = runPipeline(*pm, it.first, it.second);
540           if (instrumentor)
541             instrumentor->runAfterPipeline(pm->getOpName(), parentInfo);
542 
543           // Drop this thread from being tracked by the diagnostic handler.
544           // After this task has finished, the thread may be used outside of
545           // this pass manager context meaning that we don't want to track
546           // diagnostics from it anymore.
547           diagHandler.eraseOrderIDForThread();
548 
549           // Handle a failed pipeline result.
550           if (failed(pipelineResult)) {
551             passFailed = true;
552             break;
553           }
554         }
555       });
556 
557   // Signal a failure if any of the executors failed.
558   if (passFailed)
559     signalPassFailure();
560 }
561 
562 //===----------------------------------------------------------------------===//
563 // PassCrashReproducer
564 //===----------------------------------------------------------------------===//
565 
566 namespace {
567 /// This class contains all of the context for generating a recovery reproducer.
568 /// Each recovery context is registered globally to allow for generating
569 /// reproducers when a signal is raised, such as a segfault.
570 struct RecoveryReproducerContext {
571   RecoveryReproducerContext(MutableArrayRef<std::unique_ptr<Pass>> passes,
572                             ModuleOp module, StringRef filename,
573                             bool disableThreads, bool verifyPasses);
574   ~RecoveryReproducerContext();
575 
576   /// Generate a reproducer with the current context.
577   LogicalResult generate(std::string &error);
578 
579 private:
580   /// This function is invoked in the event of a crash.
581   static void crashHandler(void *);
582 
583   /// Register a signal handler to run in the event of a crash.
584   static void registerSignalHandler();
585 
586   /// The textual description of the currently executing pipeline.
587   std::string pipeline;
588 
589   /// The MLIR module representing the IR before the crash.
590   OwningModuleRef module;
591 
592   /// The filename to use when generating the reproducer.
593   StringRef filename;
594 
595   /// Various pass manager and context flags.
596   bool disableThreads;
597   bool verifyPasses;
598 
599   /// The current set of active reproducer contexts. This is used in the event
600   /// of a crash. This is not thread_local as the pass manager may produce any
601   /// number of child threads. This uses a set to allow for multiple MLIR pass
602   /// managers to be running at the same time.
603   static llvm::ManagedStatic<llvm::sys::SmartMutex<true>> reproducerMutex;
604   static llvm::ManagedStatic<
605       llvm::SmallSetVector<RecoveryReproducerContext *, 1>>
606       reproducerSet;
607 };
608 } // end anonymous namespace
609 
610 llvm::ManagedStatic<llvm::sys::SmartMutex<true>>
611     RecoveryReproducerContext::reproducerMutex;
612 llvm::ManagedStatic<llvm::SmallSetVector<RecoveryReproducerContext *, 1>>
613     RecoveryReproducerContext::reproducerSet;
614 
615 RecoveryReproducerContext::RecoveryReproducerContext(
616     MutableArrayRef<std::unique_ptr<Pass>> passes, ModuleOp module,
617     StringRef filename, bool disableThreads, bool verifyPasses)
618     : module(module.clone()), filename(filename),
619       disableThreads(disableThreads), verifyPasses(verifyPasses) {
620   // Grab the textual pipeline being executed..
621   {
622     llvm::raw_string_ostream pipelineOS(pipeline);
623     ::printAsTextualPipeline(passes, pipelineOS);
624   }
625 
626   // Make sure that the handler is registered, and update the current context.
627   llvm::sys::SmartScopedLock<true> producerLock(*reproducerMutex);
628   registerSignalHandler();
629   reproducerSet->insert(this);
630 }
631 
632 RecoveryReproducerContext::~RecoveryReproducerContext() {
633   llvm::sys::SmartScopedLock<true> producerLock(*reproducerMutex);
634   reproducerSet->remove(this);
635 }
636 
637 LogicalResult RecoveryReproducerContext::generate(std::string &error) {
638   std::unique_ptr<llvm::ToolOutputFile> outputFile =
639       mlir::openOutputFile(filename, &error);
640   if (!outputFile)
641     return failure();
642   auto &outputOS = outputFile->os();
643 
644   // Output the current pass manager configuration.
645   outputOS << "// configuration: -pass-pipeline='" << pipeline << "'";
646   if (disableThreads)
647     outputOS << " -mlir-disable-threading";
648 
649   // TODO: Should this also be configured with a pass manager flag?
650   outputOS << "\n// note: verifyPasses=" << (verifyPasses ? "true" : "false")
651            << "\n";
652 
653   // Output the .mlir module.
654   module->print(outputOS);
655   outputFile->keep();
656   return success();
657 }
658 
659 void RecoveryReproducerContext::crashHandler(void *) {
660   // Walk the current stack of contexts and generate a reproducer for each one.
661   // We can't know for certain which one was the cause, so we need to generate
662   // a reproducer for all of them.
663   std::string ignored;
664   for (RecoveryReproducerContext *context : *reproducerSet)
665     context->generate(ignored);
666 }
667 
668 void RecoveryReproducerContext::registerSignalHandler() {
669   // Ensure that the handler is only registered once.
670   static bool registered =
671       (llvm::sys::AddSignalHandler(crashHandler, nullptr), false);
672   (void)registered;
673 }
674 
675 /// Run the pass manager with crash recover enabled.
676 LogicalResult PassManager::runWithCrashRecovery(ModuleOp module,
677                                                 AnalysisManager am) {
678   // If this isn't a local producer, run all of the passes in recovery mode.
679   if (!localReproducer)
680     return runWithCrashRecovery(impl->passes, module, am);
681 
682   // Split the passes within adaptors to ensure that each pass can be run in
683   // isolation.
684   impl->splitAdaptorPasses();
685 
686   // If this is a local producer, run each of the passes individually. If the
687   // verifier is enabled, each pass will have a verifier after. This is included
688   // in the recovery run.
689   unsigned stride = impl->verifyPasses ? 2 : 1;
690   MutableArrayRef<std::unique_ptr<Pass>> passes = impl->passes;
691   for (unsigned i = 0, e = passes.size(); i != e; i += stride) {
692     if (failed(runWithCrashRecovery(passes.slice(i, stride), module, am)))
693       return failure();
694   }
695   return success();
696 }
697 
698 /// Run the given passes with crash recover enabled.
699 LogicalResult
700 PassManager::runWithCrashRecovery(MutableArrayRef<std::unique_ptr<Pass>> passes,
701                                   ModuleOp module, AnalysisManager am) {
702   RecoveryReproducerContext context(passes, module, *crashReproducerFileName,
703                                     !getContext()->isMultithreadingEnabled(),
704                                     impl->verifyPasses);
705 
706   // Safely invoke the passes within a recovery context.
707   llvm::CrashRecoveryContext::Enable();
708   LogicalResult passManagerResult = failure();
709   llvm::CrashRecoveryContext recoveryContext;
710   recoveryContext.RunSafelyOnThread([&] {
711     for (std::unique_ptr<Pass> &pass : passes)
712       if (failed(pass->run(module, am)))
713         return;
714     passManagerResult = success();
715   });
716   llvm::CrashRecoveryContext::Disable();
717   if (succeeded(passManagerResult))
718     return success();
719 
720   std::string error;
721   if (failed(context.generate(error)))
722     return module.emitError("<MLIR-PassManager-Crash-Reproducer>: ") << error;
723   return module.emitError()
724          << "A failure has been detected while processing the MLIR module, a "
725             "reproducer has been generated in '"
726          << *crashReproducerFileName << "'";
727 }
728 
729 //===----------------------------------------------------------------------===//
730 // PassManager
731 //===----------------------------------------------------------------------===//
732 
733 PassManager::PassManager(MLIRContext *ctx, bool verifyPasses)
734     : OpPassManager(OperationName(ModuleOp::getOperationName(), ctx),
735                     verifyPasses),
736       passTiming(false), localReproducer(false) {}
737 
738 PassManager::~PassManager() {}
739 
740 /// Run the passes within this manager on the provided module.
741 LogicalResult PassManager::run(ModuleOp module) {
742   // Before running, make sure to coalesce any adjacent pass adaptors in the
743   // pipeline.
744   getImpl().coalesceAdjacentAdaptorPasses();
745 
746   // Register all dialects for the current pipeline.
747   DialectRegistry dependentDialects;
748   getDependentDialects(dependentDialects);
749   dependentDialects.loadAll(module.getContext());
750 
751   // Construct an analysis manager for the pipeline.
752   ModuleAnalysisManager am(module, instrumentor.get());
753 
754   // Notify the context that we start running a pipeline for book keeping.
755   module.getContext()->enterMultiThreadedExecution();
756 
757   // If reproducer generation is enabled, run the pass manager with crash
758   // handling enabled.
759   LogicalResult result = crashReproducerFileName
760                              ? runWithCrashRecovery(module, am)
761                              : OpPassManager::run(module, am);
762 
763   // Notify the context that the run is done.
764   module.getContext()->exitMultiThreadedExecution();
765 
766   // Dump all of the pass statistics if necessary.
767   if (passStatisticsMode)
768     dumpStatistics();
769   return result;
770 }
771 
772 /// Enable support for the pass manager to generate a reproducer on the event
773 /// of a crash or a pass failure. `outputFile` is a .mlir filename used to write
774 /// the generated reproducer. If `genLocalReproducer` is true, the pass manager
775 /// will attempt to generate a local reproducer that contains the smallest
776 /// pipeline.
777 void PassManager::enableCrashReproducerGeneration(StringRef outputFile,
778                                                   bool genLocalReproducer) {
779   crashReproducerFileName = std::string(outputFile);
780   localReproducer = genLocalReproducer;
781 }
782 
783 /// Add the provided instrumentation to the pass manager.
784 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
785   if (!instrumentor)
786     instrumentor = std::make_unique<PassInstrumentor>();
787 
788   instrumentor->addInstrumentation(std::move(pi));
789 }
790 
791 //===----------------------------------------------------------------------===//
792 // AnalysisManager
793 //===----------------------------------------------------------------------===//
794 
795 /// Returns a pass instrumentation object for the current operation.
796 PassInstrumentor *AnalysisManager::getPassInstrumentor() const {
797   ParentPointerT curParent = parent;
798   while (auto *parentAM = curParent.dyn_cast<const AnalysisManager *>())
799     curParent = parentAM->parent;
800   return curParent.get<const ModuleAnalysisManager *>()->getPassInstrumentor();
801 }
802 
803 /// Get an analysis manager for the given child operation.
804 AnalysisManager AnalysisManager::slice(Operation *op) {
805   assert(op->getParentOp() == impl->getOperation() &&
806          "'op' has a different parent operation");
807   auto it = impl->childAnalyses.find(op);
808   if (it == impl->childAnalyses.end())
809     it = impl->childAnalyses
810              .try_emplace(op, std::make_unique<NestedAnalysisMap>(op))
811              .first;
812   return {this, it->second.get()};
813 }
814 
815 /// Invalidate any non preserved analyses.
816 void detail::NestedAnalysisMap::invalidate(
817     const detail::PreservedAnalyses &pa) {
818   // If all analyses were preserved, then there is nothing to do here.
819   if (pa.isAll())
820     return;
821 
822   // Invalidate the analyses for the current operation directly.
823   analyses.invalidate(pa);
824 
825   // If no analyses were preserved, then just simply clear out the child
826   // analysis results.
827   if (pa.isNone()) {
828     childAnalyses.clear();
829     return;
830   }
831 
832   // Otherwise, invalidate each child analysis map.
833   SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
834   while (!mapsToInvalidate.empty()) {
835     auto *map = mapsToInvalidate.pop_back_val();
836     for (auto &analysisPair : map->childAnalyses) {
837       analysisPair.second->invalidate(pa);
838       if (!analysisPair.second->childAnalyses.empty())
839         mapsToInvalidate.push_back(analysisPair.second.get());
840     }
841   }
842 }
843 
844 //===----------------------------------------------------------------------===//
845 // PassInstrumentation
846 //===----------------------------------------------------------------------===//
847 
848 PassInstrumentation::~PassInstrumentation() {}
849 
850 //===----------------------------------------------------------------------===//
851 // PassInstrumentor
852 //===----------------------------------------------------------------------===//
853 
854 namespace mlir {
855 namespace detail {
856 struct PassInstrumentorImpl {
857   /// Mutex to keep instrumentation access thread-safe.
858   llvm::sys::SmartMutex<true> mutex;
859 
860   /// Set of registered instrumentations.
861   std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
862 };
863 } // end namespace detail
864 } // end namespace mlir
865 
866 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
867 PassInstrumentor::~PassInstrumentor() {}
868 
869 /// See PassInstrumentation::runBeforePipeline for details.
870 void PassInstrumentor::runBeforePipeline(
871     const OperationName &name,
872     const PassInstrumentation::PipelineParentInfo &parentInfo) {
873   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
874   for (auto &instr : impl->instrumentations)
875     instr->runBeforePipeline(name, parentInfo);
876 }
877 
878 /// See PassInstrumentation::runAfterPipeline for details.
879 void PassInstrumentor::runAfterPipeline(
880     const OperationName &name,
881     const PassInstrumentation::PipelineParentInfo &parentInfo) {
882   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
883   for (auto &instr : llvm::reverse(impl->instrumentations))
884     instr->runAfterPipeline(name, parentInfo);
885 }
886 
887 /// See PassInstrumentation::runBeforePass for details.
888 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
889   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
890   for (auto &instr : impl->instrumentations)
891     instr->runBeforePass(pass, op);
892 }
893 
894 /// See PassInstrumentation::runAfterPass for details.
895 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
896   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
897   for (auto &instr : llvm::reverse(impl->instrumentations))
898     instr->runAfterPass(pass, op);
899 }
900 
901 /// See PassInstrumentation::runAfterPassFailed for details.
902 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
903   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
904   for (auto &instr : llvm::reverse(impl->instrumentations))
905     instr->runAfterPassFailed(pass, op);
906 }
907 
908 /// See PassInstrumentation::runBeforeAnalysis for details.
909 void PassInstrumentor::runBeforeAnalysis(StringRef name, TypeID id,
910                                          Operation *op) {
911   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
912   for (auto &instr : impl->instrumentations)
913     instr->runBeforeAnalysis(name, id, op);
914 }
915 
916 /// See PassInstrumentation::runAfterAnalysis for details.
917 void PassInstrumentor::runAfterAnalysis(StringRef name, TypeID id,
918                                         Operation *op) {
919   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
920   for (auto &instr : llvm::reverse(impl->instrumentations))
921     instr->runAfterAnalysis(name, id, op);
922 }
923 
924 /// Add the given instrumentation to the collection.
925 void PassInstrumentor::addInstrumentation(
926     std::unique_ptr<PassInstrumentation> pi) {
927   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
928   impl->instrumentations.emplace_back(std::move(pi));
929 }
930