xref: /llvm-project-15.0.7/mlir/lib/Pass/Pass.cpp (revision 5ac257da)
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/Threading.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/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(OperationName opName, OpPassManager::Nesting nesting)
84       : name(opName.getStringRef()), opName(opName),
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(StringAttr 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   /// Clear the list of passes in this pass manager, other options are
102   /// preserved.
103   void clear();
104 
105   /// Finalize the pass list in preparation for execution. This includes
106   /// coalescing adjacent pass managers when possible, verifying scheduled
107   /// passes, etc.
108   LogicalResult finalizePassList(MLIRContext *ctx);
109 
110   /// Return the operation name of this pass manager.
111   OperationName getOpName(MLIRContext &context) {
112     if (!opName)
113       opName = OperationName(name, &context);
114     return *opName;
115   }
116 
117   /// The name of the operation that passes of this pass manager operate on.
118   std::string name;
119 
120   /// The cached OperationName (internalized in the context) for the name of the
121   /// operation that passes of this pass manager operate on.
122   Optional<OperationName> opName;
123 
124   /// The set of passes to run as part of this pass manager.
125   std::vector<std::unique_ptr<Pass>> passes;
126 
127   /// The current initialization generation of this pass manager. This is used
128   /// to indicate when a pass manager should be reinitialized.
129   unsigned initializationGeneration;
130 
131   /// Control the implicit nesting of passes that mismatch the name set for this
132   /// OpPassManager.
133   OpPassManager::Nesting nesting;
134 };
135 } // namespace detail
136 } // namespace mlir
137 
138 void OpPassManagerImpl::mergeInto(OpPassManagerImpl &rhs) {
139   assert(name == rhs.name && "merging unrelated pass managers");
140   for (auto &pass : passes)
141     rhs.passes.push_back(std::move(pass));
142   passes.clear();
143 }
144 
145 OpPassManager &OpPassManagerImpl::nest(StringAttr 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 OpPassManager &OpPassManagerImpl::nest(StringRef nestedName) {
153   OpPassManager nested(nestedName, nesting);
154   auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
155   addPass(std::unique_ptr<Pass>(adaptor));
156   return adaptor->getPassManagers().front();
157 }
158 
159 void OpPassManagerImpl::addPass(std::unique_ptr<Pass> pass) {
160   // If this pass runs on a different operation than this pass manager, then
161   // implicitly nest a pass manager for this operation if enabled.
162   auto passOpName = pass->getOpName();
163   if (passOpName && passOpName->str() != name) {
164     if (nesting == OpPassManager::Nesting::Implicit)
165       return nest(*passOpName).addPass(std::move(pass));
166     llvm::report_fatal_error(llvm::Twine("Can't add pass '") + pass->getName() +
167                              "' restricted to '" + *passOpName +
168                              "' on a PassManager intended to run on '" + name +
169                              "', did you intend to nest?");
170   }
171 
172   passes.emplace_back(std::move(pass));
173 }
174 
175 void OpPassManagerImpl::clear() { passes.clear(); }
176 
177 LogicalResult OpPassManagerImpl::finalizePassList(MLIRContext *ctx) {
178   // Walk the pass list and merge adjacent adaptors.
179   OpToOpPassAdaptor *lastAdaptor = nullptr;
180   for (auto &pass : passes) {
181     // Check to see if this pass is an adaptor.
182     if (auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(pass.get())) {
183       // If it is the first adaptor in a possible chain, remember it and
184       // continue.
185       if (!lastAdaptor) {
186         lastAdaptor = currentAdaptor;
187         continue;
188       }
189 
190       // Otherwise, merge into the existing adaptor and delete the current one.
191       currentAdaptor->mergeInto(*lastAdaptor);
192       pass.reset();
193     } else if (lastAdaptor) {
194       // If this pass is not an adaptor, then finalize and forget any existing
195       // adaptor.
196       for (auto &pm : lastAdaptor->getPassManagers())
197         if (failed(pm.getImpl().finalizePassList(ctx)))
198           return failure();
199       lastAdaptor = nullptr;
200     }
201   }
202 
203   // If there was an adaptor at the end of the manager, finalize it as well.
204   if (lastAdaptor) {
205     for (auto &pm : lastAdaptor->getPassManagers())
206       if (failed(pm.getImpl().finalizePassList(ctx)))
207         return failure();
208   }
209 
210   // Now that the adaptors have been merged, erase any empty slots corresponding
211   // to the merged adaptors that were nulled-out in the loop above.
212   Optional<RegisteredOperationName> opName =
213       getOpName(*ctx).getRegisteredInfo();
214   llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
215 
216   // Verify that all of the passes are valid for the operation.
217   for (std::unique_ptr<Pass> &pass : passes) {
218     if (opName && !pass->canScheduleOn(*opName)) {
219       return emitError(UnknownLoc::get(ctx))
220              << "unable to schedule pass '" << pass->getName()
221              << "' on a PassManager intended to run on '" << name << "'!";
222     }
223   }
224   return success();
225 }
226 
227 //===----------------------------------------------------------------------===//
228 // OpPassManager
229 //===----------------------------------------------------------------------===//
230 
231 OpPassManager::OpPassManager(StringAttr name, Nesting nesting)
232     : impl(new OpPassManagerImpl(name, nesting)) {}
233 OpPassManager::OpPassManager(StringRef name, Nesting nesting)
234     : impl(new OpPassManagerImpl(name, nesting)) {}
235 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
236 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
237 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
238   impl = std::make_unique<OpPassManagerImpl>(rhs.impl->name, rhs.impl->nesting);
239   impl->initializationGeneration = rhs.impl->initializationGeneration;
240   for (auto &pass : rhs.impl->passes) {
241     auto newPass = pass->clone();
242     newPass->threadingSibling = pass.get();
243     impl->passes.push_back(std::move(newPass));
244   }
245   return *this;
246 }
247 
248 OpPassManager::~OpPassManager() = default;
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(StringAttr 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 void OpPassManager::clear() { impl->clear(); }
280 
281 /// Returns the number of passes held by this manager.
282 size_t OpPassManager::size() const { return impl->passes.size(); }
283 
284 /// Returns the internal implementation instance.
285 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
286 
287 /// Return the operation name that this pass manager operates on.
288 StringRef OpPassManager::getOpName() const { return impl->name; }
289 
290 /// Return the operation name that this pass manager operates on.
291 OperationName OpPassManager::getOpName(MLIRContext &context) const {
292   return impl->getOpName(context);
293 }
294 
295 /// Prints out the given passes as the textual representation of a pipeline.
296 static void printAsTextualPipeline(ArrayRef<std::unique_ptr<Pass>> passes,
297                                    raw_ostream &os) {
298   llvm::interleaveComma(passes, os, [&](const std::unique_ptr<Pass> &pass) {
299     pass->printAsTextualPipeline(os);
300   });
301 }
302 
303 /// Prints out the passes of the pass manager as the textual representation
304 /// of pipelines.
305 void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
306   ::printAsTextualPipeline(impl->passes, os);
307 }
308 
309 void OpPassManager::dump() {
310   llvm::errs() << "Pass Manager with " << impl->passes.size() << " passes: ";
311   ::printAsTextualPipeline(impl->passes, llvm::errs());
312   llvm::errs() << "\n";
313 }
314 
315 static void registerDialectsForPipeline(const OpPassManager &pm,
316                                         DialectRegistry &dialects) {
317   for (const Pass &pass : pm.getPasses())
318     pass.getDependentDialects(dialects);
319 }
320 
321 void OpPassManager::getDependentDialects(DialectRegistry &dialects) const {
322   registerDialectsForPipeline(*this, dialects);
323 }
324 
325 void OpPassManager::setNesting(Nesting nesting) { impl->nesting = nesting; }
326 
327 OpPassManager::Nesting OpPassManager::getNesting() { return impl->nesting; }
328 
329 LogicalResult OpPassManager::initialize(MLIRContext *context,
330                                         unsigned newInitGeneration) {
331   if (impl->initializationGeneration == newInitGeneration)
332     return success();
333   impl->initializationGeneration = newInitGeneration;
334   for (Pass &pass : getPasses()) {
335     // If this pass isn't an adaptor, directly initialize it.
336     auto *adaptor = dyn_cast<OpToOpPassAdaptor>(&pass);
337     if (!adaptor) {
338       if (failed(pass.initialize(context)))
339         return failure();
340       continue;
341     }
342 
343     // Otherwise, initialize each of the adaptors pass managers.
344     for (OpPassManager &adaptorPM : adaptor->getPassManagers())
345       if (failed(adaptorPM.initialize(context, newInitGeneration)))
346         return failure();
347   }
348   return success();
349 }
350 
351 //===----------------------------------------------------------------------===//
352 // OpToOpPassAdaptor
353 //===----------------------------------------------------------------------===//
354 
355 LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
356                                      AnalysisManager am, bool verifyPasses,
357                                      unsigned parentInitGeneration) {
358   if (!op->isRegistered())
359     return op->emitOpError()
360            << "trying to schedule a pass on an unregistered operation";
361   if (!op->hasTrait<OpTrait::IsIsolatedFromAbove>())
362     return op->emitOpError() << "trying to schedule a pass on an operation not "
363                                 "marked as 'IsolatedFromAbove'";
364 
365   // Initialize the pass state with a callback for the pass to dynamically
366   // execute a pipeline on the currently visited operation.
367   PassInstrumentor *pi = am.getPassInstrumentor();
368   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
369                                                         pass};
370   auto dynamicPipelineCallback = [&](OpPassManager &pipeline,
371                                      Operation *root) -> LogicalResult {
372     if (!op->isAncestor(root))
373       return root->emitOpError()
374              << "Trying to schedule a dynamic pipeline on an "
375                 "operation that isn't "
376                 "nested under the current operation the pass is processing";
377     assert(pipeline.getOpName() == root->getName().getStringRef());
378 
379     // Before running, finalize the passes held by the pipeline.
380     if (failed(pipeline.getImpl().finalizePassList(root->getContext())))
381       return failure();
382 
383     // Initialize the user provided pipeline and execute the pipeline.
384     if (failed(pipeline.initialize(root->getContext(), parentInitGeneration)))
385       return failure();
386     AnalysisManager nestedAm = root == op ? am : am.nest(root);
387     return OpToOpPassAdaptor::runPipeline(pipeline.getPasses(), root, nestedAm,
388                                           verifyPasses, parentInitGeneration,
389                                           pi, &parentInfo);
390   };
391   pass->passState.emplace(op, am, dynamicPipelineCallback);
392 
393   // Instrument before the pass has run.
394   if (pi)
395     pi->runBeforePass(pass, op);
396 
397   // Invoke the virtual runOnOperation method.
398   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
399     adaptor->runOnOperation(verifyPasses);
400   else
401     pass->runOnOperation();
402   bool passFailed = pass->passState->irAndPassFailed.getInt();
403 
404   // Invalidate any non preserved analyses.
405   am.invalidate(pass->passState->preservedAnalyses);
406 
407   // When verifyPasses is specified, we run the verifier (unless the pass
408   // failed).
409   if (!passFailed && verifyPasses) {
410     bool runVerifierNow = true;
411     // Reduce compile time by avoiding running the verifier if the pass didn't
412     // change the IR since the last time the verifier was run:
413     //
414     //  1) If the pass said that it preserved all analyses then it can't have
415     //     permuted the IR.
416     //  2) If we just ran an OpToOpPassAdaptor (e.g. to run function passes
417     //     within a module) then each sub-unit will have been verified on the
418     //     subunit (and those passes aren't allowed to modify the parent).
419     //
420     // We run these checks in EXPENSIVE_CHECKS mode out of caution.
421 #ifndef EXPENSIVE_CHECKS
422     runVerifierNow = !isa<OpToOpPassAdaptor>(pass) &&
423                      !pass->passState->preservedAnalyses.isAll();
424 #endif
425     if (runVerifierNow)
426       passFailed = failed(verify(op));
427   }
428 
429   // Instrument after the pass has run.
430   if (pi) {
431     if (passFailed)
432       pi->runAfterPassFailed(pass, op);
433     else
434       pi->runAfterPass(pass, op);
435   }
436 
437   // Return if the pass signaled a failure.
438   return failure(passFailed);
439 }
440 
441 /// Run the given operation and analysis manager on a provided op pass manager.
442 LogicalResult OpToOpPassAdaptor::runPipeline(
443     iterator_range<OpPassManager::pass_iterator> passes, Operation *op,
444     AnalysisManager am, bool verifyPasses, unsigned parentInitGeneration,
445     PassInstrumentor *instrumentor,
446     const PassInstrumentation::PipelineParentInfo *parentInfo) {
447   assert((!instrumentor || parentInfo) &&
448          "expected parent info if instrumentor is provided");
449   auto scopeExit = llvm::make_scope_exit([&] {
450     // Clear out any computed operation analyses. These analyses won't be used
451     // any more in this pipeline, and this helps reduce the current working set
452     // of memory. If preserving these analyses becomes important in the future
453     // we can re-evaluate this.
454     am.clear();
455   });
456 
457   // Run the pipeline over the provided operation.
458   if (instrumentor)
459     instrumentor->runBeforePipeline(op->getName().getIdentifier(), *parentInfo);
460   for (Pass &pass : passes)
461     if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration)))
462       return failure();
463   if (instrumentor)
464     instrumentor->runAfterPipeline(op->getName().getIdentifier(), *parentInfo);
465   return success();
466 }
467 
468 /// Find an operation pass manager that can operate on an operation of the given
469 /// type, or nullptr if one does not exist.
470 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
471                                          StringRef name) {
472   auto *it = llvm::find_if(
473       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
474   return it == mgrs.end() ? nullptr : &*it;
475 }
476 
477 /// Find an operation pass manager that can operate on an operation of the given
478 /// type, or nullptr if one does not exist.
479 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
480                                          OperationName name,
481                                          MLIRContext &context) {
482   auto *it = llvm::find_if(
483       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName(context) == name; });
484   return it == mgrs.end() ? nullptr : &*it;
485 }
486 
487 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) {
488   mgrs.emplace_back(std::move(mgr));
489 }
490 
491 void OpToOpPassAdaptor::getDependentDialects(DialectRegistry &dialects) const {
492   for (auto &pm : mgrs)
493     pm.getDependentDialects(dialects);
494 }
495 
496 /// Merge the current pass adaptor into given 'rhs'.
497 void OpToOpPassAdaptor::mergeInto(OpToOpPassAdaptor &rhs) {
498   for (auto &pm : mgrs) {
499     // If an existing pass manager exists, then merge the given pass manager
500     // into it.
501     if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
502       pm.getImpl().mergeInto(existingPM->getImpl());
503     } else {
504       // Otherwise, add the given pass manager to the list.
505       rhs.mgrs.emplace_back(std::move(pm));
506     }
507   }
508   mgrs.clear();
509 
510   // After coalescing, sort the pass managers within rhs by name.
511   llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
512                        [](const OpPassManager *lhs, const OpPassManager *rhs) {
513                          return lhs->getOpName().compare(rhs->getOpName());
514                        });
515 }
516 
517 /// Returns the adaptor pass name.
518 std::string OpToOpPassAdaptor::getAdaptorName() {
519   std::string name = "Pipeline Collection : [";
520   llvm::raw_string_ostream os(name);
521   llvm::interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
522     os << '\'' << pm.getOpName() << '\'';
523   });
524   os << ']';
525   return os.str();
526 }
527 
528 void OpToOpPassAdaptor::runOnOperation() {
529   llvm_unreachable(
530       "Unexpected call to Pass::runOnOperation() on OpToOpPassAdaptor");
531 }
532 
533 /// Run the held pipeline over all nested operations.
534 void OpToOpPassAdaptor::runOnOperation(bool verifyPasses) {
535   if (getContext().isMultithreadingEnabled())
536     runOnOperationAsyncImpl(verifyPasses);
537   else
538     runOnOperationImpl(verifyPasses);
539 }
540 
541 /// Run this pass adaptor synchronously.
542 void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
543   auto am = getAnalysisManager();
544   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
545                                                         this};
546   auto *instrumentor = am.getPassInstrumentor();
547   for (auto &region : getOperation()->getRegions()) {
548     for (auto &block : region) {
549       for (auto &op : block) {
550         auto *mgr = findPassManagerFor(mgrs, op.getName(), *op.getContext());
551         if (!mgr)
552           continue;
553 
554         // Run the held pipeline over the current operation.
555         unsigned initGeneration = mgr->impl->initializationGeneration;
556         if (failed(runPipeline(mgr->getPasses(), &op, am.nest(&op),
557                                verifyPasses, initGeneration, instrumentor,
558                                &parentInfo)))
559           return signalPassFailure();
560       }
561     }
562   }
563 }
564 
565 /// Utility functor that checks if the two ranges of pass managers have a size
566 /// mismatch.
567 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
568                             ArrayRef<OpPassManager> rhs) {
569   return lhs.size() != rhs.size() ||
570          llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
571                       [&](size_t i) { return lhs[i].size() != rhs[i].size(); });
572 }
573 
574 /// Run this pass adaptor synchronously.
575 void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
576   AnalysisManager am = getAnalysisManager();
577   MLIRContext *context = &getContext();
578 
579   // Create the async executors if they haven't been created, or if the main
580   // pipeline has changed.
581   if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
582     asyncExecutors.assign(context->getThreadPool().getThreadCount(), mgrs);
583 
584   // Run a prepass over the operation to collect the nested operations to
585   // execute over. This ensures that an analysis manager exists for each
586   // operation, as well as providing a queue of operations to execute over.
587   std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
588   for (auto &region : getOperation()->getRegions()) {
589     for (auto &block : region) {
590       for (auto &op : block) {
591         // Add this operation iff the name matches any of the pass managers.
592         if (findPassManagerFor(mgrs, op.getName(), *context))
593           opAMPairs.emplace_back(&op, am.nest(&op));
594       }
595     }
596   }
597 
598   // Get the current thread for this adaptor.
599   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
600                                                         this};
601   auto *instrumentor = am.getPassInstrumentor();
602 
603   // An atomic failure variable for the async executors.
604   std::vector<std::atomic<bool>> activePMs(asyncExecutors.size());
605   std::fill(activePMs.begin(), activePMs.end(), false);
606   auto processFn = [&](auto &opPMPair) {
607     // Find a pass manager for this operation.
608     auto it = llvm::find_if(activePMs, [](std::atomic<bool> &isActive) {
609       bool expectedInactive = false;
610       return isActive.compare_exchange_strong(expectedInactive, true);
611     });
612     unsigned pmIndex = it - activePMs.begin();
613 
614     // Get the pass manager for this operation and execute it.
615     auto *pm = findPassManagerFor(asyncExecutors[pmIndex],
616                                   opPMPair.first->getName(), *context);
617     assert(pm && "expected valid pass manager for operation");
618 
619     unsigned initGeneration = pm->impl->initializationGeneration;
620     LogicalResult pipelineResult =
621         runPipeline(pm->getPasses(), opPMPair.first, opPMPair.second,
622                     verifyPasses, initGeneration, instrumentor, &parentInfo);
623 
624     // Reset the active bit for this pass manager.
625     activePMs[pmIndex].store(false);
626     return pipelineResult;
627   };
628 
629   // Signal a failure if any of the executors failed.
630   if (failed(failableParallelForEach(context, opAMPairs, processFn)))
631     signalPassFailure();
632 }
633 
634 //===----------------------------------------------------------------------===//
635 // PassManager
636 //===----------------------------------------------------------------------===//
637 
638 PassManager::PassManager(MLIRContext *ctx, Nesting nesting,
639                          StringRef operationName)
640     : OpPassManager(StringAttr::get(ctx, operationName), nesting), context(ctx),
641       initializationKey(DenseMapInfo<llvm::hash_code>::getTombstoneKey()),
642       passTiming(false), verifyPasses(true) {}
643 
644 PassManager::~PassManager() = default;
645 
646 void PassManager::enableVerifier(bool enabled) { verifyPasses = enabled; }
647 
648 /// Run the passes within this manager on the provided operation.
649 LogicalResult PassManager::run(Operation *op) {
650   MLIRContext *context = getContext();
651   assert(op->getName() == getOpName(*context) &&
652          "operation has a different name than the PassManager or is from a "
653          "different context");
654 
655   // Register all dialects for the current pipeline.
656   DialectRegistry dependentDialects;
657   getDependentDialects(dependentDialects);
658   context->appendDialectRegistry(dependentDialects);
659   for (StringRef name : dependentDialects.getDialectNames())
660     context->getOrLoadDialect(name);
661 
662   // Before running, make sure to finalize the pipeline pass list.
663   if (failed(getImpl().finalizePassList(context)))
664     return failure();
665 
666   // Initialize all of the passes within the pass manager with a new generation.
667   llvm::hash_code newInitKey = context->getRegistryHash();
668   if (newInitKey != initializationKey) {
669     if (failed(initialize(context, impl->initializationGeneration + 1)))
670       return failure();
671     initializationKey = newInitKey;
672   }
673 
674   // Construct a top level analysis manager for the pipeline.
675   ModuleAnalysisManager am(op, instrumentor.get());
676 
677   // Notify the context that we start running a pipeline for book keeping.
678   context->enterMultiThreadedExecution();
679 
680   // If reproducer generation is enabled, run the pass manager with crash
681   // handling enabled.
682   LogicalResult result =
683       crashReproGenerator ? runWithCrashRecovery(op, am) : runPasses(op, am);
684 
685   // Notify the context that the run is done.
686   context->exitMultiThreadedExecution();
687 
688   // Dump all of the pass statistics if necessary.
689   if (passStatisticsMode)
690     dumpStatistics();
691   return result;
692 }
693 
694 /// Add the provided instrumentation to the pass manager.
695 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
696   if (!instrumentor)
697     instrumentor = std::make_unique<PassInstrumentor>();
698 
699   instrumentor->addInstrumentation(std::move(pi));
700 }
701 
702 LogicalResult PassManager::runPasses(Operation *op, AnalysisManager am) {
703   return OpToOpPassAdaptor::runPipeline(getPasses(), op, am, verifyPasses,
704                                         impl->initializationGeneration);
705 }
706 
707 //===----------------------------------------------------------------------===//
708 // AnalysisManager
709 //===----------------------------------------------------------------------===//
710 
711 /// Get an analysis manager for the given operation, which must be a proper
712 /// descendant of the current operation represented by this analysis manager.
713 AnalysisManager AnalysisManager::nest(Operation *op) {
714   Operation *currentOp = impl->getOperation();
715   assert(currentOp->isProperAncestor(op) &&
716          "expected valid descendant operation");
717 
718   // Check for the base case where the provided operation is immediately nested.
719   if (currentOp == op->getParentOp())
720     return nestImmediate(op);
721 
722   // Otherwise, we need to collect all ancestors up to the current operation.
723   SmallVector<Operation *, 4> opAncestors;
724   do {
725     opAncestors.push_back(op);
726     op = op->getParentOp();
727   } while (op != currentOp);
728 
729   AnalysisManager result = *this;
730   for (Operation *op : llvm::reverse(opAncestors))
731     result = result.nestImmediate(op);
732   return result;
733 }
734 
735 /// Get an analysis manager for the given immediately nested child operation.
736 AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
737   assert(impl->getOperation() == op->getParentOp() &&
738          "expected immediate child operation");
739 
740   auto it = impl->childAnalyses.find(op);
741   if (it == impl->childAnalyses.end())
742     it = impl->childAnalyses
743              .try_emplace(op, std::make_unique<NestedAnalysisMap>(op, impl))
744              .first;
745   return {it->second.get()};
746 }
747 
748 /// Invalidate any non preserved analyses.
749 void detail::NestedAnalysisMap::invalidate(
750     const detail::PreservedAnalyses &pa) {
751   // If all analyses were preserved, then there is nothing to do here.
752   if (pa.isAll())
753     return;
754 
755   // Invalidate the analyses for the current operation directly.
756   analyses.invalidate(pa);
757 
758   // If no analyses were preserved, then just simply clear out the child
759   // analysis results.
760   if (pa.isNone()) {
761     childAnalyses.clear();
762     return;
763   }
764 
765   // Otherwise, invalidate each child analysis map.
766   SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
767   while (!mapsToInvalidate.empty()) {
768     auto *map = mapsToInvalidate.pop_back_val();
769     for (auto &analysisPair : map->childAnalyses) {
770       analysisPair.second->invalidate(pa);
771       if (!analysisPair.second->childAnalyses.empty())
772         mapsToInvalidate.push_back(analysisPair.second.get());
773     }
774   }
775 }
776 
777 //===----------------------------------------------------------------------===//
778 // PassInstrumentation
779 //===----------------------------------------------------------------------===//
780 
781 PassInstrumentation::~PassInstrumentation() = default;
782 
783 //===----------------------------------------------------------------------===//
784 // PassInstrumentor
785 //===----------------------------------------------------------------------===//
786 
787 namespace mlir {
788 namespace detail {
789 struct PassInstrumentorImpl {
790   /// Mutex to keep instrumentation access thread-safe.
791   llvm::sys::SmartMutex<true> mutex;
792 
793   /// Set of registered instrumentations.
794   std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
795 };
796 } // namespace detail
797 } // namespace mlir
798 
799 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
800 PassInstrumentor::~PassInstrumentor() = default;
801 
802 /// See PassInstrumentation::runBeforePipeline for details.
803 void PassInstrumentor::runBeforePipeline(
804     StringAttr name,
805     const PassInstrumentation::PipelineParentInfo &parentInfo) {
806   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
807   for (auto &instr : impl->instrumentations)
808     instr->runBeforePipeline(name, parentInfo);
809 }
810 
811 /// See PassInstrumentation::runAfterPipeline for details.
812 void PassInstrumentor::runAfterPipeline(
813     StringAttr name,
814     const PassInstrumentation::PipelineParentInfo &parentInfo) {
815   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
816   for (auto &instr : llvm::reverse(impl->instrumentations))
817     instr->runAfterPipeline(name, parentInfo);
818 }
819 
820 /// See PassInstrumentation::runBeforePass for details.
821 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
822   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
823   for (auto &instr : impl->instrumentations)
824     instr->runBeforePass(pass, op);
825 }
826 
827 /// See PassInstrumentation::runAfterPass for details.
828 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
829   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
830   for (auto &instr : llvm::reverse(impl->instrumentations))
831     instr->runAfterPass(pass, op);
832 }
833 
834 /// See PassInstrumentation::runAfterPassFailed for details.
835 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
836   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
837   for (auto &instr : llvm::reverse(impl->instrumentations))
838     instr->runAfterPassFailed(pass, op);
839 }
840 
841 /// See PassInstrumentation::runBeforeAnalysis for details.
842 void PassInstrumentor::runBeforeAnalysis(StringRef name, TypeID id,
843                                          Operation *op) {
844   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
845   for (auto &instr : impl->instrumentations)
846     instr->runBeforeAnalysis(name, id, op);
847 }
848 
849 /// See PassInstrumentation::runAfterAnalysis for details.
850 void PassInstrumentor::runAfterAnalysis(StringRef name, TypeID id,
851                                         Operation *op) {
852   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
853   for (auto &instr : llvm::reverse(impl->instrumentations))
854     instr->runAfterAnalysis(name, id, op);
855 }
856 
857 /// Add the given instrumentation to the collection.
858 void PassInstrumentor::addInstrumentation(
859     std::unique_ptr<PassInstrumentation> pi) {
860   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
861   impl->instrumentations.emplace_back(std::move(pi));
862 }
863