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