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