xref: /llvm-project-15.0.7/mlir/lib/Pass/Pass.cpp (revision cbc9d22e)
1 //===- Pass.cpp - Pass infrastructure implementation ----------------------===//
2 //
3 // Part of the MLIR 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/Analysis/Verifier.h"
16 #include "mlir/IR/Diagnostics.h"
17 #include "mlir/IR/Dialect.h"
18 #include "mlir/IR/Module.h"
19 #include "mlir/Support/FileUtilities.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/CrashRecoveryContext.h"
23 #include "llvm/Support/Mutex.h"
24 #include "llvm/Support/Parallel.h"
25 #include "llvm/Support/Threading.h"
26 #include "llvm/Support/ToolOutputFile.h"
27 
28 using namespace mlir;
29 using namespace mlir::detail;
30 
31 //===----------------------------------------------------------------------===//
32 // Pass
33 //===----------------------------------------------------------------------===//
34 
35 /// Out of line virtual method to ensure vtables and metadata are emitted to a
36 /// single .o file.
37 void Pass::anchor() {}
38 
39 /// Attempt to initialize the options of this pass from the given string.
40 LogicalResult Pass::initializeOptions(StringRef options) {
41   return passOptions.parseFromString(options);
42 }
43 
44 /// Copy the option values from 'other', which is another instance of this
45 /// pass.
46 void Pass::copyOptionValuesFrom(const Pass *other) {
47   passOptions.copyOptionValuesFrom(other->passOptions);
48 }
49 
50 /// Prints out the pass in the textual representation of pipelines. If this is
51 /// an adaptor pass, print with the op_name(sub_pass,...) format.
52 void Pass::printAsTextualPipeline(raw_ostream &os) {
53   // Special case for adaptors to use the 'op_name(sub_passes)' format.
54   if (auto *adaptor = getAdaptorPassBase(this)) {
55     interleaveComma(adaptor->getPassManagers(), os, [&](OpPassManager &pm) {
56       os << pm.getOpName() << "(";
57       pm.printAsTextualPipeline(os);
58       os << ")";
59     });
60     return;
61   }
62   // Otherwise, print the pass argument followed by its options.
63   if (const PassInfo *info = lookupPassInfo())
64     os << info->getPassArgument();
65   else
66     os << getName();
67   passOptions.print(os);
68 }
69 
70 /// Forwarding function to execute this pass.
71 LogicalResult Pass::run(Operation *op, AnalysisManager am) {
72   passState.emplace(op, am);
73 
74   // Instrument before the pass has run.
75   auto pi = am.getPassInstrumentor();
76   if (pi)
77     pi->runBeforePass(this, op);
78 
79   // Invoke the virtual runOnOperation method.
80   runOnOperation();
81 
82   // Invalidate any non preserved analyses.
83   am.invalidate(passState->preservedAnalyses);
84 
85   // Instrument after the pass has run.
86   bool passFailed = passState->irAndPassFailed.getInt();
87   if (pi) {
88     if (passFailed)
89       pi->runAfterPassFailed(this, op);
90     else
91       pi->runAfterPass(this, op);
92   }
93 
94   // Return if the pass signaled a failure.
95   return failure(passFailed);
96 }
97 
98 //===----------------------------------------------------------------------===//
99 // Verifier Passes
100 //===----------------------------------------------------------------------===//
101 
102 void VerifierPass::runOnOperation() {
103   if (failed(verify(getOperation())))
104     signalPassFailure();
105   markAllAnalysesPreserved();
106 }
107 
108 //===----------------------------------------------------------------------===//
109 // OpPassManagerImpl
110 //===----------------------------------------------------------------------===//
111 
112 namespace mlir {
113 namespace detail {
114 struct OpPassManagerImpl {
115   OpPassManagerImpl(OperationName name, bool disableThreads, bool verifyPasses)
116       : name(name), disableThreads(disableThreads), verifyPasses(verifyPasses) {
117   }
118 
119   /// Merge the passes of this pass manager into the one provided.
120   void mergeInto(OpPassManagerImpl &rhs) {
121     assert(name == rhs.name && "merging unrelated pass managers");
122     for (auto &pass : passes)
123       rhs.passes.push_back(std::move(pass));
124     passes.clear();
125   }
126 
127   /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
128   /// recursively through the pipeline graph.
129   void coalesceAdjacentAdaptorPasses();
130 
131   /// The name of the operation that passes of this pass manager operate on.
132   OperationName name;
133 
134   /// Flag to disable multi-threading of passes.
135   bool disableThreads : 1;
136 
137   /// Flag that specifies if the IR should be verified after each pass has run.
138   bool verifyPasses : 1;
139 
140   /// The set of passes to run as part of this pass manager.
141   std::vector<std::unique_ptr<Pass>> passes;
142 };
143 } // end namespace detail
144 } // end namespace mlir
145 
146 /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
147 /// recursively through the pipeline graph.
148 void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() {
149   // Bail out early if there are no adaptor passes.
150   if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) {
151         return isAdaptorPass(pass.get());
152       }))
153     return;
154 
155   // Walk the pass list and merge adjacent adaptors.
156   OpToOpPassAdaptorBase *lastAdaptor = nullptr;
157   for (auto it = passes.begin(), e = passes.end(); it != e; ++it) {
158     // Check to see if this pass is an adaptor.
159     if (auto *currentAdaptor = getAdaptorPassBase(it->get())) {
160       // If it is the first adaptor in a possible chain, remember it and
161       // continue.
162       if (!lastAdaptor) {
163         lastAdaptor = currentAdaptor;
164         continue;
165       }
166 
167       // Otherwise, merge into the existing adaptor and delete the current one.
168       currentAdaptor->mergeInto(*lastAdaptor);
169       it->reset();
170 
171       // If the verifier is enabled, then next pass is a verifier run so
172       // drop it. Verifier passes are inserted after every pass, so this one
173       // would be a duplicate.
174       if (verifyPasses) {
175         assert(std::next(it) != e && isa<VerifierPass>(*std::next(it)));
176         (++it)->reset();
177       }
178     } else if (lastAdaptor && !isa<VerifierPass>(*it)) {
179       // If this pass is not an adaptor and not a verifier pass, then coalesce
180       // and forget any existing adaptor.
181       for (auto &pm : lastAdaptor->getPassManagers())
182         pm.getImpl().coalesceAdjacentAdaptorPasses();
183       lastAdaptor = nullptr;
184     }
185   }
186 
187   // If there was an adaptor at the end of the manager, coalesce it as well.
188   if (lastAdaptor) {
189     for (auto &pm : lastAdaptor->getPassManagers())
190       pm.getImpl().coalesceAdjacentAdaptorPasses();
191   }
192 
193   // Now that the adaptors have been merged, erase the empty slot corresponding
194   // to the merged adaptors that were nulled-out in the loop above.
195   llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
196 }
197 
198 //===----------------------------------------------------------------------===//
199 // OpPassManager
200 //===----------------------------------------------------------------------===//
201 
202 OpPassManager::OpPassManager(OperationName name, bool disableThreads,
203                              bool verifyPasses)
204     : impl(new OpPassManagerImpl(name, disableThreads, verifyPasses)) {
205   assert(name.getAbstractOperation() &&
206          "OpPassManager can only operate on registered operations");
207   assert(name.getAbstractOperation()->hasProperty(
208              OperationProperty::IsolatedFromAbove) &&
209          "OpPassManager only supports operating on operations marked as "
210          "'IsolatedFromAbove'");
211 }
212 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
213 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
214 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
215   impl.reset(new OpPassManagerImpl(rhs.impl->name, rhs.impl->disableThreads,
216                                    rhs.impl->verifyPasses));
217   for (auto &pass : rhs.impl->passes)
218     impl->passes.emplace_back(pass->clone());
219   return *this;
220 }
221 
222 OpPassManager::~OpPassManager() {}
223 
224 OpPassManager::pass_iterator OpPassManager::begin() {
225   return impl->passes.begin();
226 }
227 OpPassManager::pass_iterator OpPassManager::end() { return impl->passes.end(); }
228 
229 /// Run all of the passes in this manager over the current operation.
230 LogicalResult OpPassManager::run(Operation *op, AnalysisManager am) {
231   // Run each of the held passes.
232   for (auto &pass : impl->passes)
233     if (failed(pass->run(op, am)))
234       return failure();
235   return success();
236 }
237 
238 /// Nest a new operation pass manager for the given operation kind under this
239 /// pass manager.
240 OpPassManager &OpPassManager::nest(const OperationName &nestedName) {
241   OpPassManager nested(nestedName, impl->disableThreads, impl->verifyPasses);
242 
243   /// Create an adaptor for this pass. If multi-threading is disabled, then
244   /// create a synchronous adaptor.
245   if (impl->disableThreads || !llvm::llvm_is_multithreaded()) {
246     auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
247     addPass(std::unique_ptr<Pass>(adaptor));
248     return adaptor->getPassManagers().front();
249   }
250 
251   auto *adaptor = new OpToOpPassAdaptorParallel(std::move(nested));
252   addPass(std::unique_ptr<Pass>(adaptor));
253   return adaptor->getPassManagers().front();
254 }
255 OpPassManager &OpPassManager::nest(StringRef nestedName) {
256   return nest(OperationName(nestedName, getContext()));
257 }
258 
259 /// Add the given pass to this pass manager. If this pass has a concrete
260 /// operation type, it must be the same type as this pass manager.
261 void OpPassManager::addPass(std::unique_ptr<Pass> pass) {
262   // If this pass runs on a different operation than this pass manager, then
263   // implicitly nest a pass manager for this operation.
264   auto passOpName = pass->getOpName();
265   if (passOpName && passOpName != impl->name.getStringRef())
266     return nest(*passOpName).addPass(std::move(pass));
267 
268   impl->passes.emplace_back(std::move(pass));
269   if (impl->verifyPasses)
270     impl->passes.emplace_back(std::make_unique<VerifierPass>());
271 }
272 
273 /// Returns the number of passes held by this manager.
274 size_t OpPassManager::size() const { return impl->passes.size(); }
275 
276 /// Returns the internal implementation instance.
277 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
278 
279 /// Return an instance of the context.
280 MLIRContext *OpPassManager::getContext() const {
281   return impl->name.getAbstractOperation()->dialect.getContext();
282 }
283 
284 /// Return the operation name that this pass manager operates on.
285 const OperationName &OpPassManager::getOpName() const { return impl->name; }
286 
287 /// Prints out the passes of the pass manager as the textual representation
288 /// of pipelines.
289 void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
290   // Filter out passes that are not part of the public pipeline.
291   auto filteredPasses = llvm::make_filter_range(
292       impl->passes, [](const std::unique_ptr<Pass> &pass) {
293         return !isa<VerifierPass>(pass);
294       });
295   interleaveComma(filteredPasses, os, [&](const std::unique_ptr<Pass> &pass) {
296     pass->printAsTextualPipeline(os);
297   });
298 }
299 
300 //===----------------------------------------------------------------------===//
301 // OpToOpPassAdaptor
302 //===----------------------------------------------------------------------===//
303 
304 /// Utility to run the given operation and analysis manager on a provided op
305 /// pass manager.
306 static LogicalResult runPipeline(OpPassManager &pm, Operation *op,
307                                  AnalysisManager am) {
308   // Run the pipeline over the provided operation.
309   auto result = pm.run(op, am);
310 
311   // Clear out any computed operation analyses. These analyses won't be used
312   // any more in this pipeline, and this helps reduce the current working set
313   // of memory. If preserving these analyses becomes important in the future
314   // we can re-evaluate this.
315   am.clear();
316   return result;
317 }
318 
319 /// Find an operation pass manager that can operate on an operation of the given
320 /// type, or nullptr if one does not exist.
321 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
322                                          const OperationName &name) {
323   auto it = llvm::find_if(
324       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
325   return it == mgrs.end() ? nullptr : &*it;
326 }
327 
328 OpToOpPassAdaptorBase::OpToOpPassAdaptorBase(OpPassManager &&mgr) {
329   mgrs.emplace_back(std::move(mgr));
330 }
331 
332 /// Merge the current pass adaptor into given 'rhs'.
333 void OpToOpPassAdaptorBase::mergeInto(OpToOpPassAdaptorBase &rhs) {
334   for (auto &pm : mgrs) {
335     // If an existing pass manager exists, then merge the given pass manager
336     // into it.
337     if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
338       pm.getImpl().mergeInto(existingPM->getImpl());
339     } else {
340       // Otherwise, add the given pass manager to the list.
341       rhs.mgrs.emplace_back(std::move(pm));
342     }
343   }
344   mgrs.clear();
345 
346   // After coalescing, sort the pass managers within rhs by name.
347   llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
348                        [](const OpPassManager *lhs, const OpPassManager *rhs) {
349                          return lhs->getOpName().getStringRef().compare(
350                              rhs->getOpName().getStringRef());
351                        });
352 }
353 
354 /// Returns the adaptor pass name.
355 std::string OpToOpPassAdaptorBase::getName() {
356   std::string name = "Pipeline Collection : [";
357   llvm::raw_string_ostream os(name);
358   interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
359     os << '\'' << pm.getOpName() << '\'';
360   });
361   os << ']';
362   return os.str();
363 }
364 
365 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr)
366     : OpToOpPassAdaptorBase(std::move(mgr)) {}
367 
368 /// Run the held pipeline over all nested operations.
369 void OpToOpPassAdaptor::runOnOperation() {
370   auto am = getAnalysisManager();
371   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
372                                                         this};
373   auto *instrumentor = am.getPassInstrumentor();
374   for (auto &region : getOperation()->getRegions()) {
375     for (auto &block : region) {
376       for (auto &op : block) {
377         auto *mgr = findPassManagerFor(mgrs, op.getName());
378         if (!mgr)
379           continue;
380 
381         // Run the held pipeline over the current operation.
382         if (instrumentor)
383           instrumentor->runBeforePipeline(mgr->getOpName(), parentInfo);
384         auto result = runPipeline(*mgr, &op, am.slice(&op));
385         if (instrumentor)
386           instrumentor->runAfterPipeline(mgr->getOpName(), parentInfo);
387 
388         if (failed(result))
389           return signalPassFailure();
390       }
391     }
392   }
393 }
394 
395 OpToOpPassAdaptorParallel::OpToOpPassAdaptorParallel(OpPassManager &&mgr)
396     : OpToOpPassAdaptorBase(std::move(mgr)) {}
397 
398 /// Utility functor that checks if the two ranges of pass managers have a size
399 /// mismatch.
400 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
401                             ArrayRef<OpPassManager> rhs) {
402   return lhs.size() != rhs.size() ||
403          llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
404                       [&](size_t i) { return lhs[i].size() != rhs[i].size(); });
405 }
406 
407 // Run the held pipeline asynchronously across the functions within the module.
408 void OpToOpPassAdaptorParallel::runOnOperation() {
409   AnalysisManager am = getAnalysisManager();
410 
411   // Create the async executors if they haven't been created, or if the main
412   // pipeline has changed.
413   if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
414     asyncExecutors.assign(llvm::hardware_concurrency(), mgrs);
415 
416   // Run a prepass over the module to collect the operations to execute over.
417   // This ensures that an analysis manager exists for each operation, as well as
418   // providing a queue of operations to execute over.
419   std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
420   for (auto &region : getOperation()->getRegions()) {
421     for (auto &block : region) {
422       for (auto &op : block) {
423         // Add this operation iff the name matches the any of the pass managers.
424         if (findPassManagerFor(mgrs, op.getName()))
425           opAMPairs.emplace_back(&op, am.slice(&op));
426       }
427     }
428   }
429 
430   // A parallel diagnostic handler that provides deterministic diagnostic
431   // ordering.
432   ParallelDiagnosticHandler diagHandler(&getContext());
433 
434   // An index for the current operation/analysis manager pair.
435   std::atomic<unsigned> opIt(0);
436 
437   // Get the current thread for this adaptor.
438   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
439                                                         this};
440   auto *instrumentor = am.getPassInstrumentor();
441 
442   // An atomic failure variable for the async executors.
443   std::atomic<bool> passFailed(false);
444   llvm::parallel::for_each(
445       llvm::parallel::par, asyncExecutors.begin(),
446       std::next(asyncExecutors.begin(),
447                 std::min(asyncExecutors.size(), opAMPairs.size())),
448       [&](MutableArrayRef<OpPassManager> pms) {
449         for (auto e = opAMPairs.size(); !passFailed && opIt < e;) {
450           // Get the next available operation index.
451           unsigned nextID = opIt++;
452           if (nextID >= e)
453             break;
454 
455           // Set the order id for this thread in the diagnostic handler.
456           diagHandler.setOrderIDForThread(nextID);
457 
458           // Get the pass manager for this operation and execute it.
459           auto &it = opAMPairs[nextID];
460           auto *pm = findPassManagerFor(pms, it.first->getName());
461           assert(pm && "expected valid pass manager for operation");
462 
463           if (instrumentor)
464             instrumentor->runBeforePipeline(pm->getOpName(), parentInfo);
465           auto pipelineResult = runPipeline(*pm, it.first, it.second);
466           if (instrumentor)
467             instrumentor->runAfterPipeline(pm->getOpName(), parentInfo);
468 
469           // Drop this thread from being tracked by the diagnostic handler.
470           // After this task has finished, the thread may be used outside of
471           // this pass manager context meaning that we don't want to track
472           // diagnostics from it anymore.
473           diagHandler.eraseOrderIDForThread();
474 
475           // Handle a failed pipeline result.
476           if (failed(pipelineResult)) {
477             passFailed = true;
478             break;
479           }
480         }
481       });
482 
483   // Signal a failure if any of the executors failed.
484   if (passFailed)
485     signalPassFailure();
486 }
487 
488 /// Utility function to convert the given class to the base adaptor it is an
489 /// adaptor pass, returns nullptr otherwise.
490 OpToOpPassAdaptorBase *mlir::detail::getAdaptorPassBase(Pass *pass) {
491   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
492     return adaptor;
493   if (auto *adaptor = dyn_cast<OpToOpPassAdaptorParallel>(pass))
494     return adaptor;
495   return nullptr;
496 }
497 
498 //===----------------------------------------------------------------------===//
499 // PassCrashReproducer
500 //===----------------------------------------------------------------------===//
501 
502 /// Safely run the pass manager over the given module, creating a reproducible
503 /// on failure or crash.
504 static LogicalResult runWithCrashRecovery(OpPassManager &pm,
505                                           ModuleAnalysisManager &am,
506                                           ModuleOp module,
507                                           StringRef crashReproducerFileName) {
508   /// Enable crash recovery.
509   llvm::CrashRecoveryContext::Enable();
510 
511   // Grab the textual pipeline executing within the pass manager first, just in
512   // case the pass manager becomes compromised.
513   std::string pipeline;
514   {
515     llvm::raw_string_ostream pipelineOS(pipeline);
516     pm.printAsTextualPipeline(pipelineOS);
517   }
518 
519   // Clone the initial module before running it through the pass pipeline.
520   OwningModuleRef reproducerModule = module.clone();
521 
522   // Safely invoke the pass manager within a recovery context.
523   LogicalResult passManagerResult = failure();
524   llvm::CrashRecoveryContext recoveryContext;
525   recoveryContext.RunSafelyOnThread(
526       [&] { passManagerResult = pm.run(module, am); });
527 
528   /// Disable crash recovery.
529   llvm::CrashRecoveryContext::Disable();
530   if (succeeded(passManagerResult))
531     return success();
532 
533   // The conversion failed, so generate a reproducible.
534   std::string error;
535   std::unique_ptr<llvm::ToolOutputFile> outputFile =
536       mlir::openOutputFile(crashReproducerFileName, &error);
537   if (!outputFile)
538     return emitError(UnknownLoc::get(pm.getContext()),
539                      "<MLIR-PassManager-Crash-Reproducer>: ")
540            << error;
541   auto &outputOS = outputFile->os();
542 
543   // Output the current pass manager configuration.
544   outputOS << "// configuration: -pass-pipeline='" << pipeline << "'";
545   if (pm.getImpl().disableThreads)
546     outputOS << " -disable-pass-threading";
547 
548   // TODO(riverriddle) Should this also be configured with a pass manager flag?
549   outputOS << "\n// note: verifyPasses="
550            << (pm.getImpl().verifyPasses ? "true" : "false") << "\n";
551 
552   // Output the .mlir module.
553   reproducerModule->print(outputOS);
554   outputFile->keep();
555 
556   return reproducerModule->emitError()
557          << "A failure has been detected while processing the MLIR module, a "
558             "reproducer has been generated in '"
559          << crashReproducerFileName << "'";
560 }
561 
562 //===----------------------------------------------------------------------===//
563 // PassManager
564 //===----------------------------------------------------------------------===//
565 
566 PassManager::PassManager(MLIRContext *ctx, bool verifyPasses)
567     : OpPassManager(OperationName(ModuleOp::getOperationName(), ctx),
568                     /*disableThreads=*/false, verifyPasses),
569       passTiming(false) {}
570 
571 PassManager::~PassManager() {}
572 
573 /// Run the passes within this manager on the provided module.
574 LogicalResult PassManager::run(ModuleOp module) {
575   // Before running, make sure to coalesce any adjacent pass adaptors in the
576   // pipeline.
577   getImpl().coalesceAdjacentAdaptorPasses();
578 
579   // Construct an analysis manager for the pipeline.
580   ModuleAnalysisManager am(module, instrumentor.get());
581 
582   // If reproducer generation is enabled, run the pass manager with crash
583   // handling enabled.
584   LogicalResult result =
585       crashReproducerFileName
586           ? runWithCrashRecovery(*this, am, module, *crashReproducerFileName)
587           : OpPassManager::run(module, am);
588 
589   // Dump all of the pass statistics if necessary.
590   if (passStatisticsMode)
591     dumpStatistics();
592   return result;
593 }
594 
595 /// Disable support for multi-threading within the pass manager.
596 void PassManager::disableMultithreading(bool disable) {
597   getImpl().disableThreads = disable;
598 }
599 
600 /// Enable support for the pass manager to generate a reproducer on the event
601 /// of a crash or a pass failure. `outputFile` is a .mlir filename used to write
602 /// the generated reproducer.
603 void PassManager::enableCrashReproducerGeneration(StringRef outputFile) {
604   crashReproducerFileName = outputFile;
605 }
606 
607 /// Add the provided instrumentation to the pass manager.
608 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
609   if (!instrumentor)
610     instrumentor = std::make_unique<PassInstrumentor>();
611 
612   instrumentor->addInstrumentation(std::move(pi));
613 }
614 
615 //===----------------------------------------------------------------------===//
616 // AnalysisManager
617 //===----------------------------------------------------------------------===//
618 
619 /// Returns a pass instrumentation object for the current operation.
620 PassInstrumentor *AnalysisManager::getPassInstrumentor() const {
621   ParentPointerT curParent = parent;
622   while (auto *parentAM = curParent.dyn_cast<const AnalysisManager *>())
623     curParent = parentAM->parent;
624   return curParent.get<const ModuleAnalysisManager *>()->getPassInstrumentor();
625 }
626 
627 /// Get an analysis manager for the given child operation.
628 AnalysisManager AnalysisManager::slice(Operation *op) {
629   assert(op->getParentOp() == impl->getOperation() &&
630          "'op' has a different parent operation");
631   auto it = impl->childAnalyses.find(op);
632   if (it == impl->childAnalyses.end())
633     it = impl->childAnalyses
634              .try_emplace(op, std::make_unique<NestedAnalysisMap>(op))
635              .first;
636   return {this, it->second.get()};
637 }
638 
639 /// Invalidate any non preserved analyses.
640 void detail::NestedAnalysisMap::invalidate(
641     const detail::PreservedAnalyses &pa) {
642   // If all analyses were preserved, then there is nothing to do here.
643   if (pa.isAll())
644     return;
645 
646   // Invalidate the analyses for the current operation directly.
647   analyses.invalidate(pa);
648 
649   // If no analyses were preserved, then just simply clear out the child
650   // analysis results.
651   if (pa.isNone()) {
652     childAnalyses.clear();
653     return;
654   }
655 
656   // Otherwise, invalidate each child analysis map.
657   SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
658   while (!mapsToInvalidate.empty()) {
659     auto *map = mapsToInvalidate.pop_back_val();
660     for (auto &analysisPair : map->childAnalyses) {
661       analysisPair.second->invalidate(pa);
662       if (!analysisPair.second->childAnalyses.empty())
663         mapsToInvalidate.push_back(analysisPair.second.get());
664     }
665   }
666 }
667 
668 //===----------------------------------------------------------------------===//
669 // PassInstrumentation
670 //===----------------------------------------------------------------------===//
671 
672 PassInstrumentation::~PassInstrumentation() {}
673 
674 //===----------------------------------------------------------------------===//
675 // PassInstrumentor
676 //===----------------------------------------------------------------------===//
677 
678 namespace mlir {
679 namespace detail {
680 struct PassInstrumentorImpl {
681   /// Mutex to keep instrumentation access thread-safe.
682   llvm::sys::SmartMutex<true> mutex;
683 
684   /// Set of registered instrumentations.
685   std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
686 };
687 } // end namespace detail
688 } // end namespace mlir
689 
690 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
691 PassInstrumentor::~PassInstrumentor() {}
692 
693 /// See PassInstrumentation::runBeforePipeline for details.
694 void PassInstrumentor::runBeforePipeline(
695     const OperationName &name,
696     const PassInstrumentation::PipelineParentInfo &parentInfo) {
697   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
698   for (auto &instr : impl->instrumentations)
699     instr->runBeforePipeline(name, parentInfo);
700 }
701 
702 /// See PassInstrumentation::runAfterPipeline for details.
703 void PassInstrumentor::runAfterPipeline(
704     const OperationName &name,
705     const PassInstrumentation::PipelineParentInfo &parentInfo) {
706   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
707   for (auto &instr : llvm::reverse(impl->instrumentations))
708     instr->runAfterPipeline(name, parentInfo);
709 }
710 
711 /// See PassInstrumentation::runBeforePass for details.
712 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
713   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
714   for (auto &instr : impl->instrumentations)
715     instr->runBeforePass(pass, op);
716 }
717 
718 /// See PassInstrumentation::runAfterPass for details.
719 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
720   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
721   for (auto &instr : llvm::reverse(impl->instrumentations))
722     instr->runAfterPass(pass, op);
723 }
724 
725 /// See PassInstrumentation::runAfterPassFailed for details.
726 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
727   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
728   for (auto &instr : llvm::reverse(impl->instrumentations))
729     instr->runAfterPassFailed(pass, op);
730 }
731 
732 /// See PassInstrumentation::runBeforeAnalysis for details.
733 void PassInstrumentor::runBeforeAnalysis(StringRef name, AnalysisID *id,
734                                          Operation *op) {
735   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
736   for (auto &instr : impl->instrumentations)
737     instr->runBeforeAnalysis(name, id, op);
738 }
739 
740 /// See PassInstrumentation::runAfterAnalysis for details.
741 void PassInstrumentor::runAfterAnalysis(StringRef name, AnalysisID *id,
742                                         Operation *op) {
743   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
744   for (auto &instr : llvm::reverse(impl->instrumentations))
745     instr->runAfterAnalysis(name, id, op);
746 }
747 
748 /// Add the given instrumentation to the collection.
749 void PassInstrumentor::addInstrumentation(
750     std::unique_ptr<PassInstrumentation> pi) {
751   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
752   impl->instrumentations.emplace_back(std::move(pi));
753 }
754 
755 constexpr AnalysisID mlir::detail::PreservedAnalyses::allAnalysesID;
756