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