xref: /llvm-project-15.0.7/mlir/lib/Pass/Pass.cpp (revision 5aa5eba1)
1 //===- Pass.cpp - Pass infrastructure implementation ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements common pass infrastructure.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Pass/Pass.h"
14 #include "PassDetail.h"
15 #include "mlir/IR/Diagnostics.h"
16 #include "mlir/IR/Dialect.h"
17 #include "mlir/IR/Verifier.h"
18 #include "mlir/Support/FileUtilities.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/Parallel.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 
30 using namespace mlir;
31 using namespace mlir::detail;
32 
33 //===----------------------------------------------------------------------===//
34 // Pass
35 //===----------------------------------------------------------------------===//
36 
37 /// Out of line virtual method to ensure vtables and metadata are emitted to a
38 /// single .o file.
39 void Pass::anchor() {}
40 
41 /// Attempt to initialize the options of this pass from the given string.
42 LogicalResult Pass::initializeOptions(StringRef options) {
43   return passOptions.parseFromString(options);
44 }
45 
46 /// Copy the option values from 'other', which is another instance of this
47 /// pass.
48 void Pass::copyOptionValuesFrom(const Pass *other) {
49   passOptions.copyOptionValuesFrom(other->passOptions);
50 }
51 
52 /// Prints out the pass in the textual representation of pipelines. If this is
53 /// an adaptor pass, print with the op_name(sub_pass,...) format.
54 void Pass::printAsTextualPipeline(raw_ostream &os) {
55   // Special case for adaptors to use the 'op_name(sub_passes)' format.
56   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(this)) {
57     llvm::interleaveComma(adaptor->getPassManagers(), os,
58                           [&](OpPassManager &pm) {
59                             os << pm.getOpName() << "(";
60                             pm.printAsTextualPipeline(os);
61                             os << ")";
62                           });
63     return;
64   }
65   // Otherwise, print the pass argument followed by its options. If the pass
66   // doesn't have an argument, print the name of the pass to give some indicator
67   // of what pass was run.
68   StringRef argument = getArgument();
69   if (!argument.empty())
70     os << argument;
71   else
72     os << "unknown<" << getName() << ">";
73   passOptions.print(os);
74 }
75 
76 //===----------------------------------------------------------------------===//
77 // OpPassManagerImpl
78 //===----------------------------------------------------------------------===//
79 
80 namespace mlir {
81 namespace detail {
82 struct OpPassManagerImpl {
83   OpPassManagerImpl(Identifier identifier, OpPassManager::Nesting nesting)
84       : name(identifier.str()), identifier(identifier),
85         initializationGeneration(0), nesting(nesting) {}
86   OpPassManagerImpl(StringRef name, OpPassManager::Nesting nesting)
87       : name(name), initializationGeneration(0), nesting(nesting) {}
88 
89   /// Merge the passes of this pass manager into the one provided.
90   void mergeInto(OpPassManagerImpl &rhs);
91 
92   /// Nest a new operation pass manager for the given operation kind under this
93   /// pass manager.
94   OpPassManager &nest(Identifier nestedName);
95   OpPassManager &nest(StringRef nestedName);
96 
97   /// Add the given pass to this pass manager. If this pass has a concrete
98   /// operation type, it must be the same type as this pass manager.
99   void addPass(std::unique_ptr<Pass> pass);
100 
101   /// Coalesce adjacent AdaptorPasses into one large adaptor. This runs
102   /// recursively through the pipeline graph.
103   void coalesceAdjacentAdaptorPasses();
104 
105   /// Return the operation name of this pass manager as an identifier.
106   Identifier getOpName(MLIRContext &context) {
107     if (!identifier)
108       identifier = Identifier::get(name, &context);
109     return *identifier;
110   }
111 
112   /// The name of the operation that passes of this pass manager operate on.
113   std::string name;
114 
115   /// The cached identifier (internalized in the context) for the name of the
116   /// operation that passes of this pass manager operate on.
117   Optional<Identifier> identifier;
118 
119   /// The set of passes to run as part of this pass manager.
120   std::vector<std::unique_ptr<Pass>> passes;
121 
122   /// The current initialization generation of this pass manager. This is used
123   /// to indicate when a pass manager should be reinitialized.
124   unsigned initializationGeneration;
125 
126   /// Control the implicit nesting of passes that mismatch the name set for this
127   /// OpPassManager.
128   OpPassManager::Nesting nesting;
129 };
130 } // end namespace detail
131 } // end namespace mlir
132 
133 void OpPassManagerImpl::mergeInto(OpPassManagerImpl &rhs) {
134   assert(name == rhs.name && "merging unrelated pass managers");
135   for (auto &pass : passes)
136     rhs.passes.push_back(std::move(pass));
137   passes.clear();
138 }
139 
140 OpPassManager &OpPassManagerImpl::nest(Identifier nestedName) {
141   OpPassManager nested(nestedName, nesting);
142   auto *adaptor = new OpToOpPassAdaptor(std::move(nested));
143   addPass(std::unique_ptr<Pass>(adaptor));
144   return adaptor->getPassManagers().front();
145 }
146 
147 OpPassManager &OpPassManagerImpl::nest(StringRef 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 void OpPassManagerImpl::addPass(std::unique_ptr<Pass> pass) {
155   // If this pass runs on a different operation than this pass manager, then
156   // implicitly nest a pass manager for this operation if enabled.
157   auto passOpName = pass->getOpName();
158   if (passOpName && passOpName->str() != name) {
159     if (nesting == OpPassManager::Nesting::Implicit)
160       return nest(*passOpName).addPass(std::move(pass));
161     llvm::report_fatal_error(llvm::Twine("Can't add pass '") + pass->getName() +
162                              "' restricted to '" + *passOpName +
163                              "' on a PassManager intended to run on '" + name +
164                              "', did you intend to nest?");
165   }
166 
167   passes.emplace_back(std::move(pass));
168 }
169 
170 void OpPassManagerImpl::coalesceAdjacentAdaptorPasses() {
171   // Bail out early if there are no adaptor passes.
172   if (llvm::none_of(passes, [](std::unique_ptr<Pass> &pass) {
173         return isa<OpToOpPassAdaptor>(pass.get());
174       }))
175     return;
176 
177   // Walk the pass list and merge adjacent adaptors.
178   OpToOpPassAdaptor *lastAdaptor = nullptr;
179   for (auto it = passes.begin(), e = passes.end(); it != e; ++it) {
180     // Check to see if this pass is an adaptor.
181     if (auto *currentAdaptor = dyn_cast<OpToOpPassAdaptor>(it->get())) {
182       // If it is the first adaptor in a possible chain, remember it and
183       // continue.
184       if (!lastAdaptor) {
185         lastAdaptor = currentAdaptor;
186         continue;
187       }
188 
189       // Otherwise, merge into the existing adaptor and delete the current one.
190       currentAdaptor->mergeInto(*lastAdaptor);
191       it->reset();
192     } else if (lastAdaptor) {
193       // If this pass is not an adaptor, then coalesce and forget any existing
194       // adaptor.
195       for (auto &pm : lastAdaptor->getPassManagers())
196         pm.getImpl().coalesceAdjacentAdaptorPasses();
197       lastAdaptor = nullptr;
198     }
199   }
200 
201   // If there was an adaptor at the end of the manager, coalesce it as well.
202   if (lastAdaptor) {
203     for (auto &pm : lastAdaptor->getPassManagers())
204       pm.getImpl().coalesceAdjacentAdaptorPasses();
205   }
206 
207   // Now that the adaptors have been merged, erase the empty slot corresponding
208   // to the merged adaptors that were nulled-out in the loop above.
209   llvm::erase_if(passes, std::logical_not<std::unique_ptr<Pass>>());
210 }
211 
212 //===----------------------------------------------------------------------===//
213 // OpPassManager
214 //===----------------------------------------------------------------------===//
215 
216 OpPassManager::OpPassManager(Identifier name, Nesting nesting)
217     : impl(new OpPassManagerImpl(name, nesting)) {}
218 OpPassManager::OpPassManager(StringRef name, Nesting nesting)
219     : impl(new OpPassManagerImpl(name, nesting)) {}
220 OpPassManager::OpPassManager(OpPassManager &&rhs) : impl(std::move(rhs.impl)) {}
221 OpPassManager::OpPassManager(const OpPassManager &rhs) { *this = rhs; }
222 OpPassManager &OpPassManager::operator=(const OpPassManager &rhs) {
223   impl.reset(new OpPassManagerImpl(rhs.impl->name, rhs.impl->nesting));
224   impl->initializationGeneration = rhs.impl->initializationGeneration;
225   for (auto &pass : rhs.impl->passes) {
226     auto newPass = pass->clone();
227     newPass->threadingSibling = pass.get();
228     impl->passes.push_back(std::move(newPass));
229   }
230   return *this;
231 }
232 
233 OpPassManager::~OpPassManager() {}
234 
235 OpPassManager::pass_iterator OpPassManager::begin() {
236   return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
237 }
238 OpPassManager::pass_iterator OpPassManager::end() {
239   return MutableArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
240 }
241 
242 OpPassManager::const_pass_iterator OpPassManager::begin() const {
243   return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.begin();
244 }
245 OpPassManager::const_pass_iterator OpPassManager::end() const {
246   return ArrayRef<std::unique_ptr<Pass>>{impl->passes}.end();
247 }
248 
249 /// Nest a new operation pass manager for the given operation kind under this
250 /// pass manager.
251 OpPassManager &OpPassManager::nest(Identifier nestedName) {
252   return impl->nest(nestedName);
253 }
254 OpPassManager &OpPassManager::nest(StringRef nestedName) {
255   return impl->nest(nestedName);
256 }
257 
258 /// Add the given pass to this pass manager. If this pass has a concrete
259 /// operation type, it must be the same type as this pass manager.
260 void OpPassManager::addPass(std::unique_ptr<Pass> pass) {
261   impl->addPass(std::move(pass));
262 }
263 
264 /// Returns the number of passes held by this manager.
265 size_t OpPassManager::size() const { return impl->passes.size(); }
266 
267 /// Returns the internal implementation instance.
268 OpPassManagerImpl &OpPassManager::getImpl() { return *impl; }
269 
270 /// Return the operation name that this pass manager operates on.
271 StringRef OpPassManager::getOpName() const { return impl->name; }
272 
273 /// Return the operation name that this pass manager operates on.
274 Identifier OpPassManager::getOpName(MLIRContext &context) const {
275   return impl->getOpName(context);
276 }
277 
278 /// Prints out the given passes as the textual representation of a pipeline.
279 static void printAsTextualPipeline(ArrayRef<std::unique_ptr<Pass>> passes,
280                                    raw_ostream &os) {
281   llvm::interleaveComma(passes, os, [&](const std::unique_ptr<Pass> &pass) {
282     pass->printAsTextualPipeline(os);
283   });
284 }
285 
286 /// Prints out the passes of the pass manager as the textual representation
287 /// of pipelines.
288 void OpPassManager::printAsTextualPipeline(raw_ostream &os) {
289   ::printAsTextualPipeline(impl->passes, os);
290 }
291 
292 void OpPassManager::dump() {
293   llvm::errs() << "Pass Manager with " << impl->passes.size() << " passes: ";
294   ::printAsTextualPipeline(impl->passes, llvm::errs());
295   llvm::errs() << "\n";
296 }
297 
298 static void registerDialectsForPipeline(const OpPassManager &pm,
299                                         DialectRegistry &dialects) {
300   for (const Pass &pass : pm.getPasses())
301     pass.getDependentDialects(dialects);
302 }
303 
304 void OpPassManager::getDependentDialects(DialectRegistry &dialects) const {
305   registerDialectsForPipeline(*this, dialects);
306 }
307 
308 void OpPassManager::setNesting(Nesting nesting) { impl->nesting = nesting; }
309 
310 OpPassManager::Nesting OpPassManager::getNesting() { return impl->nesting; }
311 
312 LogicalResult OpPassManager::initialize(MLIRContext *context,
313                                         unsigned newInitGeneration) {
314   if (impl->initializationGeneration == newInitGeneration)
315     return success();
316   impl->initializationGeneration = newInitGeneration;
317   for (Pass &pass : getPasses()) {
318     // If this pass isn't an adaptor, directly initialize it.
319     auto *adaptor = dyn_cast<OpToOpPassAdaptor>(&pass);
320     if (!adaptor) {
321       if (failed(pass.initialize(context)))
322         return failure();
323       continue;
324     }
325 
326     // Otherwise, initialize each of the adaptors pass managers.
327     for (OpPassManager &adaptorPM : adaptor->getPassManagers())
328       if (failed(adaptorPM.initialize(context, newInitGeneration)))
329         return failure();
330   }
331   return success();
332 }
333 
334 //===----------------------------------------------------------------------===//
335 // OpToOpPassAdaptor
336 //===----------------------------------------------------------------------===//
337 
338 LogicalResult OpToOpPassAdaptor::run(Pass *pass, Operation *op,
339                                      AnalysisManager am, bool verifyPasses,
340                                      unsigned parentInitGeneration) {
341   if (!op->isRegistered())
342     return op->emitOpError()
343            << "trying to schedule a pass on an unregistered operation";
344   if (!op->hasTrait<OpTrait::IsIsolatedFromAbove>())
345     return op->emitOpError() << "trying to schedule a pass on an operation not "
346                                 "marked as 'IsolatedFromAbove'";
347 
348   // Initialize the pass state with a callback for the pass to dynamically
349   // execute a pipeline on the currently visited operation.
350   PassInstrumentor *pi = am.getPassInstrumentor();
351   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
352                                                         pass};
353   auto dynamic_pipeline_callback = [&](OpPassManager &pipeline,
354                                        Operation *root) -> LogicalResult {
355     if (!op->isAncestor(root))
356       return root->emitOpError()
357              << "Trying to schedule a dynamic pipeline on an "
358                 "operation that isn't "
359                 "nested under the current operation the pass is processing";
360     assert(pipeline.getOpName() == root->getName().getStringRef());
361 
362     // Before running, make sure to coalesce any adjacent pass adaptors in the
363     // pipeline.
364     pipeline.getImpl().coalesceAdjacentAdaptorPasses();
365 
366     // Initialize the user provided pipeline and execute the pipeline.
367     if (failed(pipeline.initialize(root->getContext(), parentInitGeneration)))
368       return failure();
369     AnalysisManager nestedAm = root == op ? am : am.nest(root);
370     return OpToOpPassAdaptor::runPipeline(pipeline.getPasses(), root, nestedAm,
371                                           verifyPasses, parentInitGeneration,
372                                           pi, &parentInfo);
373   };
374   pass->passState.emplace(op, am, dynamic_pipeline_callback);
375 
376   // Instrument before the pass has run.
377   if (pi)
378     pi->runBeforePass(pass, op);
379 
380   // Invoke the virtual runOnOperation method.
381   if (auto *adaptor = dyn_cast<OpToOpPassAdaptor>(pass))
382     adaptor->runOnOperation(verifyPasses);
383   else
384     pass->runOnOperation();
385   bool passFailed = pass->passState->irAndPassFailed.getInt();
386 
387   // Invalidate any non preserved analyses.
388   am.invalidate(pass->passState->preservedAnalyses);
389 
390   // Run the verifier if this pass didn't fail already.
391   if (!passFailed && verifyPasses)
392     passFailed = failed(verify(op));
393 
394   // Instrument after the pass has run.
395   if (pi) {
396     if (passFailed)
397       pi->runAfterPassFailed(pass, op);
398     else
399       pi->runAfterPass(pass, op);
400   }
401 
402   // Return if the pass signaled a failure.
403   return failure(passFailed);
404 }
405 
406 /// Run the given operation and analysis manager on a provided op pass manager.
407 LogicalResult OpToOpPassAdaptor::runPipeline(
408     iterator_range<OpPassManager::pass_iterator> passes, Operation *op,
409     AnalysisManager am, bool verifyPasses, unsigned parentInitGeneration,
410     PassInstrumentor *instrumentor,
411     const PassInstrumentation::PipelineParentInfo *parentInfo) {
412   assert((!instrumentor || parentInfo) &&
413          "expected parent info if instrumentor is provided");
414   auto scope_exit = llvm::make_scope_exit([&] {
415     // Clear out any computed operation analyses. These analyses won't be used
416     // any more in this pipeline, and this helps reduce the current working set
417     // of memory. If preserving these analyses becomes important in the future
418     // we can re-evaluate this.
419     am.clear();
420   });
421 
422   // Run the pipeline over the provided operation.
423   if (instrumentor)
424     instrumentor->runBeforePipeline(op->getName().getIdentifier(), *parentInfo);
425   for (Pass &pass : passes)
426     if (failed(run(&pass, op, am, verifyPasses, parentInitGeneration)))
427       return failure();
428   if (instrumentor)
429     instrumentor->runAfterPipeline(op->getName().getIdentifier(), *parentInfo);
430   return success();
431 }
432 
433 /// Find an operation pass manager that can operate on an operation of the given
434 /// type, or nullptr if one does not exist.
435 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
436                                          StringRef name) {
437   auto it = llvm::find_if(
438       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName() == name; });
439   return it == mgrs.end() ? nullptr : &*it;
440 }
441 
442 /// Find an operation pass manager that can operate on an operation of the given
443 /// type, or nullptr if one does not exist.
444 static OpPassManager *findPassManagerFor(MutableArrayRef<OpPassManager> mgrs,
445                                          Identifier name,
446                                          MLIRContext &context) {
447   auto it = llvm::find_if(
448       mgrs, [&](OpPassManager &mgr) { return mgr.getOpName(context) == name; });
449   return it == mgrs.end() ? nullptr : &*it;
450 }
451 
452 OpToOpPassAdaptor::OpToOpPassAdaptor(OpPassManager &&mgr) {
453   mgrs.emplace_back(std::move(mgr));
454 }
455 
456 void OpToOpPassAdaptor::getDependentDialects(DialectRegistry &dialects) const {
457   for (auto &pm : mgrs)
458     pm.getDependentDialects(dialects);
459 }
460 
461 /// Merge the current pass adaptor into given 'rhs'.
462 void OpToOpPassAdaptor::mergeInto(OpToOpPassAdaptor &rhs) {
463   for (auto &pm : mgrs) {
464     // If an existing pass manager exists, then merge the given pass manager
465     // into it.
466     if (auto *existingPM = findPassManagerFor(rhs.mgrs, pm.getOpName())) {
467       pm.getImpl().mergeInto(existingPM->getImpl());
468     } else {
469       // Otherwise, add the given pass manager to the list.
470       rhs.mgrs.emplace_back(std::move(pm));
471     }
472   }
473   mgrs.clear();
474 
475   // After coalescing, sort the pass managers within rhs by name.
476   llvm::array_pod_sort(rhs.mgrs.begin(), rhs.mgrs.end(),
477                        [](const OpPassManager *lhs, const OpPassManager *rhs) {
478                          return lhs->getOpName().compare(rhs->getOpName());
479                        });
480 }
481 
482 /// Returns the adaptor pass name.
483 std::string OpToOpPassAdaptor::getAdaptorName() {
484   std::string name = "Pipeline Collection : [";
485   llvm::raw_string_ostream os(name);
486   llvm::interleaveComma(getPassManagers(), os, [&](OpPassManager &pm) {
487     os << '\'' << pm.getOpName() << '\'';
488   });
489   os << ']';
490   return os.str();
491 }
492 
493 void OpToOpPassAdaptor::runOnOperation() {
494   llvm_unreachable(
495       "Unexpected call to Pass::runOnOperation() on OpToOpPassAdaptor");
496 }
497 
498 /// Run the held pipeline over all nested operations.
499 void OpToOpPassAdaptor::runOnOperation(bool verifyPasses) {
500   if (getContext().isMultithreadingEnabled())
501     runOnOperationAsyncImpl(verifyPasses);
502   else
503     runOnOperationImpl(verifyPasses);
504 }
505 
506 /// Run this pass adaptor synchronously.
507 void OpToOpPassAdaptor::runOnOperationImpl(bool verifyPasses) {
508   auto am = getAnalysisManager();
509   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
510                                                         this};
511   auto *instrumentor = am.getPassInstrumentor();
512   for (auto &region : getOperation()->getRegions()) {
513     for (auto &block : region) {
514       for (auto &op : block) {
515         auto *mgr = findPassManagerFor(mgrs, op.getName().getIdentifier(),
516                                        *op.getContext());
517         if (!mgr)
518           continue;
519 
520         // Run the held pipeline over the current operation.
521         unsigned initGeneration = mgr->impl->initializationGeneration;
522         if (failed(runPipeline(mgr->getPasses(), &op, am.nest(&op),
523                                verifyPasses, initGeneration, instrumentor,
524                                &parentInfo)))
525           return signalPassFailure();
526       }
527     }
528   }
529 }
530 
531 /// Utility functor that checks if the two ranges of pass managers have a size
532 /// mismatch.
533 static bool hasSizeMismatch(ArrayRef<OpPassManager> lhs,
534                             ArrayRef<OpPassManager> rhs) {
535   return lhs.size() != rhs.size() ||
536          llvm::any_of(llvm::seq<size_t>(0, lhs.size()),
537                       [&](size_t i) { return lhs[i].size() != rhs[i].size(); });
538 }
539 
540 /// Run this pass adaptor synchronously.
541 void OpToOpPassAdaptor::runOnOperationAsyncImpl(bool verifyPasses) {
542   AnalysisManager am = getAnalysisManager();
543 
544   // Create the async executors if they haven't been created, or if the main
545   // pipeline has changed.
546   if (asyncExecutors.empty() || hasSizeMismatch(asyncExecutors.front(), mgrs))
547     asyncExecutors.assign(llvm::hardware_concurrency().compute_thread_count(),
548                           mgrs);
549 
550   // Run a prepass over the operation to collect the nested operations to
551   // execute over. This ensures that an analysis manager exists for each
552   // operation, as well as providing a queue of operations to execute over.
553   std::vector<std::pair<Operation *, AnalysisManager>> opAMPairs;
554   for (auto &region : getOperation()->getRegions()) {
555     for (auto &block : region) {
556       for (auto &op : block) {
557         // Add this operation iff the name matches any of the pass managers.
558         if (findPassManagerFor(mgrs, op.getName().getIdentifier(),
559                                getContext()))
560           opAMPairs.emplace_back(&op, am.nest(&op));
561       }
562     }
563   }
564 
565   // A parallel diagnostic handler that provides deterministic diagnostic
566   // ordering.
567   ParallelDiagnosticHandler diagHandler(&getContext());
568 
569   // An index for the current operation/analysis manager pair.
570   std::atomic<unsigned> opIt(0);
571 
572   // Get the current thread for this adaptor.
573   PassInstrumentation::PipelineParentInfo parentInfo = {llvm::get_threadid(),
574                                                         this};
575   auto *instrumentor = am.getPassInstrumentor();
576 
577   // An atomic failure variable for the async executors.
578   std::atomic<bool> passFailed(false);
579   llvm::parallelForEach(
580       asyncExecutors.begin(),
581       std::next(asyncExecutors.begin(),
582                 std::min(asyncExecutors.size(), opAMPairs.size())),
583       [&](MutableArrayRef<OpPassManager> pms) {
584         for (auto e = opAMPairs.size(); !passFailed && opIt < e;) {
585           // Get the next available operation index.
586           unsigned nextID = opIt++;
587           if (nextID >= e)
588             break;
589 
590           // Set the order id for this thread in the diagnostic handler.
591           diagHandler.setOrderIDForThread(nextID);
592 
593           // Get the pass manager for this operation and execute it.
594           auto &it = opAMPairs[nextID];
595           auto *pm = findPassManagerFor(
596               pms, it.first->getName().getIdentifier(), getContext());
597           assert(pm && "expected valid pass manager for operation");
598 
599           unsigned initGeneration = pm->impl->initializationGeneration;
600           LogicalResult pipelineResult =
601               runPipeline(pm->getPasses(), it.first, it.second, verifyPasses,
602                           initGeneration, instrumentor, &parentInfo);
603 
604           // Drop this thread from being tracked by the diagnostic handler.
605           // After this task has finished, the thread may be used outside of
606           // this pass manager context meaning that we don't want to track
607           // diagnostics from it anymore.
608           diagHandler.eraseOrderIDForThread();
609 
610           // Handle a failed pipeline result.
611           if (failed(pipelineResult)) {
612             passFailed = true;
613             break;
614           }
615         }
616       });
617 
618   // Signal a failure if any of the executors failed.
619   if (passFailed)
620     signalPassFailure();
621 }
622 
623 //===----------------------------------------------------------------------===//
624 // PassManager
625 //===----------------------------------------------------------------------===//
626 
627 PassManager::PassManager(MLIRContext *ctx, Nesting nesting,
628                          StringRef operationName)
629     : OpPassManager(Identifier::get(operationName, ctx), nesting), context(ctx),
630       initializationKey(DenseMapInfo<llvm::hash_code>::getTombstoneKey()),
631       passTiming(false), verifyPasses(true) {}
632 
633 PassManager::~PassManager() {}
634 
635 void PassManager::enableVerifier(bool enabled) { verifyPasses = enabled; }
636 
637 /// Run the passes within this manager on the provided operation.
638 LogicalResult PassManager::run(Operation *op) {
639   MLIRContext *context = getContext();
640   assert(op->getName().getIdentifier() == getOpName(*context) &&
641          "operation has a different name than the PassManager or is from a "
642          "different context");
643 
644   // Before running, make sure to coalesce any adjacent pass adaptors in the
645   // pipeline.
646   getImpl().coalesceAdjacentAdaptorPasses();
647 
648   // Register all dialects for the current pipeline.
649   DialectRegistry dependentDialects;
650   getDependentDialects(dependentDialects);
651   context->appendDialectRegistry(dependentDialects);
652   for (StringRef name : dependentDialects.getDialectNames())
653     context->getOrLoadDialect(name);
654 
655   // Initialize all of the passes within the pass manager with a new generation.
656   llvm::hash_code newInitKey = context->getRegistryHash();
657   if (newInitKey != initializationKey) {
658     if (failed(initialize(context, impl->initializationGeneration + 1)))
659       return failure();
660     initializationKey = newInitKey;
661   }
662 
663   // Construct a top level analysis manager for the pipeline.
664   ModuleAnalysisManager am(op, instrumentor.get());
665 
666   // Notify the context that we start running a pipeline for book keeping.
667   context->enterMultiThreadedExecution();
668 
669   // If reproducer generation is enabled, run the pass manager with crash
670   // handling enabled.
671   LogicalResult result =
672       crashReproGenerator ? runWithCrashRecovery(op, am) : runPasses(op, am);
673 
674   // Notify the context that the run is done.
675   context->exitMultiThreadedExecution();
676 
677   // Dump all of the pass statistics if necessary.
678   if (passStatisticsMode)
679     dumpStatistics();
680   return result;
681 }
682 
683 /// Add the provided instrumentation to the pass manager.
684 void PassManager::addInstrumentation(std::unique_ptr<PassInstrumentation> pi) {
685   if (!instrumentor)
686     instrumentor = std::make_unique<PassInstrumentor>();
687 
688   instrumentor->addInstrumentation(std::move(pi));
689 }
690 
691 LogicalResult PassManager::runPasses(Operation *op, AnalysisManager am) {
692   return OpToOpPassAdaptor::runPipeline(getPasses(), op, am, verifyPasses,
693                                         impl->initializationGeneration);
694 }
695 
696 //===----------------------------------------------------------------------===//
697 // AnalysisManager
698 //===----------------------------------------------------------------------===//
699 
700 /// Get an analysis manager for the given operation, which must be a proper
701 /// descendant of the current operation represented by this analysis manager.
702 AnalysisManager AnalysisManager::nest(Operation *op) {
703   Operation *currentOp = impl->getOperation();
704   assert(currentOp->isProperAncestor(op) &&
705          "expected valid descendant operation");
706 
707   // Check for the base case where the provided operation is immediately nested.
708   if (currentOp == op->getParentOp())
709     return nestImmediate(op);
710 
711   // Otherwise, we need to collect all ancestors up to the current operation.
712   SmallVector<Operation *, 4> opAncestors;
713   do {
714     opAncestors.push_back(op);
715     op = op->getParentOp();
716   } while (op != currentOp);
717 
718   AnalysisManager result = *this;
719   for (Operation *op : llvm::reverse(opAncestors))
720     result = result.nestImmediate(op);
721   return result;
722 }
723 
724 /// Get an analysis manager for the given immediately nested child operation.
725 AnalysisManager AnalysisManager::nestImmediate(Operation *op) {
726   assert(impl->getOperation() == op->getParentOp() &&
727          "expected immediate child operation");
728 
729   auto it = impl->childAnalyses.find(op);
730   if (it == impl->childAnalyses.end())
731     it = impl->childAnalyses
732              .try_emplace(op, std::make_unique<NestedAnalysisMap>(op, impl))
733              .first;
734   return {it->second.get()};
735 }
736 
737 /// Invalidate any non preserved analyses.
738 void detail::NestedAnalysisMap::invalidate(
739     const detail::PreservedAnalyses &pa) {
740   // If all analyses were preserved, then there is nothing to do here.
741   if (pa.isAll())
742     return;
743 
744   // Invalidate the analyses for the current operation directly.
745   analyses.invalidate(pa);
746 
747   // If no analyses were preserved, then just simply clear out the child
748   // analysis results.
749   if (pa.isNone()) {
750     childAnalyses.clear();
751     return;
752   }
753 
754   // Otherwise, invalidate each child analysis map.
755   SmallVector<NestedAnalysisMap *, 8> mapsToInvalidate(1, this);
756   while (!mapsToInvalidate.empty()) {
757     auto *map = mapsToInvalidate.pop_back_val();
758     for (auto &analysisPair : map->childAnalyses) {
759       analysisPair.second->invalidate(pa);
760       if (!analysisPair.second->childAnalyses.empty())
761         mapsToInvalidate.push_back(analysisPair.second.get());
762     }
763   }
764 }
765 
766 //===----------------------------------------------------------------------===//
767 // PassInstrumentation
768 //===----------------------------------------------------------------------===//
769 
770 PassInstrumentation::~PassInstrumentation() {}
771 
772 //===----------------------------------------------------------------------===//
773 // PassInstrumentor
774 //===----------------------------------------------------------------------===//
775 
776 namespace mlir {
777 namespace detail {
778 struct PassInstrumentorImpl {
779   /// Mutex to keep instrumentation access thread-safe.
780   llvm::sys::SmartMutex<true> mutex;
781 
782   /// Set of registered instrumentations.
783   std::vector<std::unique_ptr<PassInstrumentation>> instrumentations;
784 };
785 } // end namespace detail
786 } // end namespace mlir
787 
788 PassInstrumentor::PassInstrumentor() : impl(new PassInstrumentorImpl()) {}
789 PassInstrumentor::~PassInstrumentor() {}
790 
791 /// See PassInstrumentation::runBeforePipeline for details.
792 void PassInstrumentor::runBeforePipeline(
793     Identifier name,
794     const PassInstrumentation::PipelineParentInfo &parentInfo) {
795   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
796   for (auto &instr : impl->instrumentations)
797     instr->runBeforePipeline(name, parentInfo);
798 }
799 
800 /// See PassInstrumentation::runAfterPipeline for details.
801 void PassInstrumentor::runAfterPipeline(
802     Identifier name,
803     const PassInstrumentation::PipelineParentInfo &parentInfo) {
804   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
805   for (auto &instr : llvm::reverse(impl->instrumentations))
806     instr->runAfterPipeline(name, parentInfo);
807 }
808 
809 /// See PassInstrumentation::runBeforePass for details.
810 void PassInstrumentor::runBeforePass(Pass *pass, Operation *op) {
811   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
812   for (auto &instr : impl->instrumentations)
813     instr->runBeforePass(pass, op);
814 }
815 
816 /// See PassInstrumentation::runAfterPass for details.
817 void PassInstrumentor::runAfterPass(Pass *pass, Operation *op) {
818   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
819   for (auto &instr : llvm::reverse(impl->instrumentations))
820     instr->runAfterPass(pass, op);
821 }
822 
823 /// See PassInstrumentation::runAfterPassFailed for details.
824 void PassInstrumentor::runAfterPassFailed(Pass *pass, Operation *op) {
825   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
826   for (auto &instr : llvm::reverse(impl->instrumentations))
827     instr->runAfterPassFailed(pass, op);
828 }
829 
830 /// See PassInstrumentation::runBeforeAnalysis for details.
831 void PassInstrumentor::runBeforeAnalysis(StringRef name, TypeID id,
832                                          Operation *op) {
833   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
834   for (auto &instr : impl->instrumentations)
835     instr->runBeforeAnalysis(name, id, op);
836 }
837 
838 /// See PassInstrumentation::runAfterAnalysis for details.
839 void PassInstrumentor::runAfterAnalysis(StringRef name, TypeID id,
840                                         Operation *op) {
841   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
842   for (auto &instr : llvm::reverse(impl->instrumentations))
843     instr->runAfterAnalysis(name, id, op);
844 }
845 
846 /// Add the given instrumentation to the collection.
847 void PassInstrumentor::addInstrumentation(
848     std::unique_ptr<PassInstrumentation> pi) {
849   llvm::sys::SmartScopedLock<true> instrumentationLock(impl->mutex);
850   impl->instrumentations.emplace_back(std::move(pi));
851 }
852