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