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