1 //===- Standard pass instrumentations handling ----------------*- C++ -*--===//
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 /// \file
9 ///
10 /// This file defines IR-printing pass instrumentation callbacks as well as
11 /// StandardInstrumentations class that manages standard pass instrumentations.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Passes/StandardInstrumentations.h"
16 #include "llvm/ADT/Any.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/CallGraphSCCPass.h"
20 #include "llvm/Analysis/LazyCallGraph.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/PassInstrumentation.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/PrintPasses.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/FormatVariadic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include <unordered_set>
35 #include <vector>
36 
37 using namespace llvm;
38 
39 cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
40     "verify-cfg-preserved", cl::Hidden,
41 #ifdef NDEBUG
42     cl::init(false));
43 #else
44     cl::init(true));
45 #endif
46 
47 // FIXME: Change `-debug-pass-manager` from boolean to enum type. Similar to
48 // `-debug-pass` in legacy PM.
49 static cl::opt<bool>
50     DebugPMVerbose("debug-pass-manager-verbose", cl::Hidden, cl::init(false),
51                    cl::desc("Print all pass management debugging information. "
52                             "`-debug-pass-manager` must also be specified"));
53 
54 // An option that prints out the IR after passes, similar to
55 // -print-after-all except that it only prints the IR after passes that
56 // change the IR.  Those passes that do not make changes to the IR are
57 // reported as not making any changes.  In addition, the initial IR is
58 // also reported.  Other hidden options affect the output from this
59 // option.  -filter-passes will limit the output to the named passes
60 // that actually change the IR and other passes are reported as filtered out.
61 // The specified passes will either be reported as making no changes (with
62 // no IR reported) or the changed IR will be reported.  Also, the
63 // -filter-print-funcs and -print-module-scope options will do similar
64 // filtering based on function name, reporting changed IRs as functions(or
65 // modules if -print-module-scope is specified) for a particular function
66 // or indicating that the IR has been filtered out.  The extra options
67 // can be combined, allowing only changed IRs for certain passes on certain
68 // functions to be reported in different formats, with the rest being
69 // reported as filtered out.  The -print-before-changed option will print
70 // the IR as it was before each pass that changed it.  The optional
71 // value of quiet will only report when the IR changes, suppressing
72 // all other messages, including the initial IR.  The values "diff" and
73 // "diff-quiet" will present the changes in a form similar to a patch, in
74 // either verbose or quiet mode, respectively.  The lines that are removed
75 // and added are prefixed with '-' and '+', respectively.  The
76 // -filter-print-funcs and -filter-passes can be used to filter the output.
77 // This reporter relies on the linux diff utility to do comparisons and
78 // insert the prefixes.  For systems that do not have the necessary
79 // facilities, the error message will be shown in place of the expected output.
80 //
81 enum class ChangePrinter {
82   NoChangePrinter,
83   PrintChangedVerbose,
84   PrintChangedQuiet,
85   PrintChangedDiffVerbose,
86   PrintChangedDiffQuiet,
87   PrintChangedColourDiffVerbose,
88   PrintChangedColourDiffQuiet
89 };
90 static cl::opt<ChangePrinter> PrintChanged(
91     "print-changed", cl::desc("Print changed IRs"), cl::Hidden,
92     cl::ValueOptional, cl::init(ChangePrinter::NoChangePrinter),
93     cl::values(
94         clEnumValN(ChangePrinter::PrintChangedQuiet, "quiet",
95                    "Run in quiet mode"),
96         clEnumValN(ChangePrinter::PrintChangedDiffVerbose, "diff",
97                    "Display patch-like changes"),
98         clEnumValN(ChangePrinter::PrintChangedDiffQuiet, "diff-quiet",
99                    "Display patch-like changes in quiet mode"),
100         clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose, "cdiff",
101                    "Display patch-like changes with color"),
102         clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet, "cdiff-quiet",
103                    "Display patch-like changes in quiet mode with color"),
104         // Sentinel value for unspecified option.
105         clEnumValN(ChangePrinter::PrintChangedVerbose, "", "")));
106 
107 // An option that supports the -print-changed option.  See
108 // the description for -print-changed for an explanation of the use
109 // of this option.  Note that this option has no effect without -print-changed.
110 static cl::list<std::string>
111     PrintPassesList("filter-passes", cl::value_desc("pass names"),
112                     cl::desc("Only consider IR changes for passes whose names "
113                              "match for the print-changed option"),
114                     cl::CommaSeparated, cl::Hidden);
115 // An option that supports the -print-changed option.  See
116 // the description for -print-changed for an explanation of the use
117 // of this option.  Note that this option has no effect without -print-changed.
118 static cl::opt<bool>
119     PrintChangedBefore("print-before-changed",
120                        cl::desc("Print before passes that change them"),
121                        cl::init(false), cl::Hidden);
122 
123 // An option for specifying the diff used by print-changed=[diff | diff-quiet]
124 static cl::opt<std::string>
125     DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"),
126                cl::desc("system diff used by change reporters"));
127 
128 namespace {
129 
130 // Perform a system based diff between \p Before and \p After, using
131 // \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat
132 // to control the formatting of the output.  Return an error message
133 // for any failures instead of the diff.
134 std::string doSystemDiff(StringRef Before, StringRef After,
135                          StringRef OldLineFormat, StringRef NewLineFormat,
136                          StringRef UnchangedLineFormat) {
137   StringRef SR[2]{Before, After};
138   // Store the 2 bodies into temporary files and call diff on them
139   // to get the body of the node.
140   const unsigned NumFiles = 3;
141   std::string FileName[NumFiles];
142   int FD[NumFiles]{-1, -1, -1};
143   for (unsigned I = 0; I < NumFiles; ++I) {
144     if (FD[I] == -1) {
145       SmallVector<char, 200> SV;
146       std::error_code EC =
147           sys::fs::createTemporaryFile("tmpdiff", "txt", FD[I], SV);
148       if (EC)
149         return "Unable to create temporary file.";
150       FileName[I] = Twine(SV).str();
151     }
152     // The third file is used as the result of the diff.
153     if (I == NumFiles - 1)
154       break;
155 
156     std::error_code EC = sys::fs::openFileForWrite(FileName[I], FD[I]);
157     if (EC)
158       return "Unable to open temporary file for writing.";
159 
160     raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true);
161     if (FD[I] == -1)
162       return "Error opening file for writing.";
163     OutStream << SR[I];
164   }
165 
166   static ErrorOr<std::string> DiffExe = sys::findProgramByName(DiffBinary);
167   if (!DiffExe)
168     return "Unable to find diff executable.";
169 
170   SmallString<128> OLF = formatv("--old-line-format={0}", OldLineFormat);
171   SmallString<128> NLF = formatv("--new-line-format={0}", NewLineFormat);
172   SmallString<128> ULF =
173       formatv("--unchanged-line-format={0}", UnchangedLineFormat);
174 
175   StringRef Args[] = {"-w", "-d", OLF, NLF, ULF, FileName[0], FileName[1]};
176   Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None};
177   int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects);
178   if (Result < 0)
179     return "Error executing system diff.";
180   std::string Diff;
181   auto B = MemoryBuffer::getFile(FileName[2]);
182   if (B && *B)
183     Diff = (*B)->getBuffer().str();
184   else
185     return "Unable to read result.";
186 
187   // Clean up.
188   for (unsigned I = 0; I < NumFiles; ++I) {
189     std::error_code EC = sys::fs::remove(FileName[I]);
190     if (EC)
191       return "Unable to remove temporary file.";
192   }
193   return Diff;
194 }
195 
196 /// Extracting Module out of \p IR unit. Also fills a textual description
197 /// of \p IR for use in header when printing.
198 Optional<std::pair<const Module *, std::string>>
199 unwrapModule(Any IR, bool Force = false) {
200   if (any_isa<const Module *>(IR))
201     return std::make_pair(any_cast<const Module *>(IR), std::string());
202 
203   if (any_isa<const Function *>(IR)) {
204     const Function *F = any_cast<const Function *>(IR);
205     if (!Force && !isFunctionInPrintList(F->getName()))
206       return None;
207 
208     const Module *M = F->getParent();
209     return std::make_pair(M, formatv(" (function: {0})", F->getName()).str());
210   }
211 
212   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
213     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
214     for (const LazyCallGraph::Node &N : *C) {
215       const Function &F = N.getFunction();
216       if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
217         const Module *M = F.getParent();
218         return std::make_pair(M, formatv(" (scc: {0})", C->getName()).str());
219       }
220     }
221     assert(!Force && "Expected to have made a pair when forced.");
222     return None;
223   }
224 
225   if (any_isa<const Loop *>(IR)) {
226     const Loop *L = any_cast<const Loop *>(IR);
227     const Function *F = L->getHeader()->getParent();
228     if (!Force && !isFunctionInPrintList(F->getName()))
229       return None;
230     const Module *M = F->getParent();
231     std::string LoopName;
232     raw_string_ostream ss(LoopName);
233     L->getHeader()->printAsOperand(ss, false);
234     return std::make_pair(M, formatv(" (loop: {0})", ss.str()).str());
235   }
236 
237   llvm_unreachable("Unknown IR unit");
238 }
239 
240 void printIR(raw_ostream &OS, const Function *F, StringRef Banner,
241              StringRef Extra = StringRef(), bool Brief = false) {
242   if (Brief) {
243     OS << F->getName() << '\n';
244     return;
245   }
246 
247   if (!isFunctionInPrintList(F->getName()))
248     return;
249   OS << Banner << Extra << "\n" << static_cast<const Value &>(*F);
250 }
251 
252 void printIR(raw_ostream &OS, const Module *M, StringRef Banner,
253              StringRef Extra = StringRef(), bool Brief = false,
254              bool ShouldPreserveUseListOrder = false) {
255   if (Brief) {
256     OS << M->getName() << '\n';
257     return;
258   }
259 
260   if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
261     OS << Banner << Extra << "\n";
262     M->print(OS, nullptr, ShouldPreserveUseListOrder);
263   } else {
264     for (const auto &F : M->functions()) {
265       printIR(OS, &F, Banner, Extra);
266     }
267   }
268 }
269 
270 void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C, StringRef Banner,
271              StringRef Extra = StringRef(), bool Brief = false) {
272   if (Brief) {
273     OS << *C << '\n';
274     return;
275   }
276 
277   bool BannerPrinted = false;
278   for (const LazyCallGraph::Node &N : *C) {
279     const Function &F = N.getFunction();
280     if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
281       if (!BannerPrinted) {
282         OS << Banner << Extra << "\n";
283         BannerPrinted = true;
284       }
285       F.print(OS);
286     }
287   }
288 }
289 
290 void printIR(raw_ostream &OS, const Loop *L, StringRef Banner,
291              bool Brief = false) {
292   if (Brief) {
293     OS << *L;
294     return;
295   }
296 
297   const Function *F = L->getHeader()->getParent();
298   if (!isFunctionInPrintList(F->getName()))
299     return;
300   printLoop(const_cast<Loop &>(*L), OS, std::string(Banner));
301 }
302 
303 /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
304 /// llvm::Any and does actual print job.
305 void unwrapAndPrint(raw_ostream &OS, Any IR, StringRef Banner,
306                     bool ForceModule = false, bool Brief = false,
307                     bool ShouldPreserveUseListOrder = false) {
308   if (ForceModule) {
309     if (auto UnwrappedModule = unwrapModule(IR))
310       printIR(OS, UnwrappedModule->first, Banner, UnwrappedModule->second,
311               Brief, ShouldPreserveUseListOrder);
312     return;
313   }
314 
315   if (any_isa<const Module *>(IR)) {
316     const Module *M = any_cast<const Module *>(IR);
317     assert(M && "module should be valid for printing");
318     printIR(OS, M, Banner, "", Brief, ShouldPreserveUseListOrder);
319     return;
320   }
321 
322   if (any_isa<const Function *>(IR)) {
323     const Function *F = any_cast<const Function *>(IR);
324     assert(F && "function should be valid for printing");
325     printIR(OS, F, Banner, "", Brief);
326     return;
327   }
328 
329   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
330     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
331     assert(C && "scc should be valid for printing");
332     std::string Extra = std::string(formatv(" (scc: {0})", C->getName()));
333     printIR(OS, C, Banner, Extra, Brief);
334     return;
335   }
336 
337   if (any_isa<const Loop *>(IR)) {
338     const Loop *L = any_cast<const Loop *>(IR);
339     assert(L && "Loop should be valid for printing");
340     printIR(OS, L, Banner, Brief);
341     return;
342   }
343   llvm_unreachable("Unknown wrapped IR type");
344 }
345 
346 // Return true when this is a pass for which changes should be ignored
347 bool isIgnored(StringRef PassID) {
348   return isSpecialPass(PassID,
349                        {"PassManager", "PassAdaptor", "AnalysisManagerProxy"});
350 }
351 
352 } // namespace
353 
354 template <typename IRUnitT>
355 ChangeReporter<IRUnitT>::~ChangeReporter<IRUnitT>() {
356   assert(BeforeStack.empty() && "Problem with Change Printer stack.");
357 }
358 
359 template <typename IRUnitT>
360 bool ChangeReporter<IRUnitT>::isInterestingFunction(const Function &F) {
361   return isFunctionInPrintList(F.getName());
362 }
363 
364 template <typename IRUnitT>
365 bool ChangeReporter<IRUnitT>::isInterestingPass(StringRef PassID) {
366   if (isIgnored(PassID))
367     return false;
368 
369   static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
370                                                         PrintPassesList.end());
371   return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
372 }
373 
374 // Return true when this is a pass on IR for which printing
375 // of changes is desired.
376 template <typename IRUnitT>
377 bool ChangeReporter<IRUnitT>::isInteresting(Any IR, StringRef PassID) {
378   if (!isInterestingPass(PassID))
379     return false;
380   if (any_isa<const Function *>(IR))
381     return isInterestingFunction(*any_cast<const Function *>(IR));
382   return true;
383 }
384 
385 template <typename IRUnitT>
386 void ChangeReporter<IRUnitT>::saveIRBeforePass(Any IR, StringRef PassID) {
387   // Always need to place something on the stack because invalidated passes
388   // are not given the IR so it cannot be determined whether the pass was for
389   // something that was filtered out.
390   BeforeStack.emplace_back();
391 
392   if (!isInteresting(IR, PassID))
393     return;
394   // Is this the initial IR?
395   if (InitialIR) {
396     InitialIR = false;
397     if (VerboseMode)
398       handleInitialIR(IR);
399   }
400 
401   // Save the IR representation on the stack.
402   IRUnitT &Data = BeforeStack.back();
403   generateIRRepresentation(IR, PassID, Data);
404 }
405 
406 template <typename IRUnitT>
407 void ChangeReporter<IRUnitT>::handleIRAfterPass(Any IR, StringRef PassID) {
408   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
409   std::string Name;
410 
411   // unwrapModule has inconsistent handling of names for function IRs.
412   if (any_isa<const Function *>(IR)) {
413     const Function *F = any_cast<const Function *>(IR);
414     Name = formatv(" (function: {0})", F->getName()).str();
415   } else {
416     if (auto UM = unwrapModule(IR))
417       Name = UM->second;
418   }
419   if (Name == "")
420     Name = " (module)";
421 
422   if (isIgnored(PassID)) {
423     if (VerboseMode)
424       handleIgnored(PassID, Name);
425   } else if (!isInteresting(IR, PassID)) {
426     if (VerboseMode)
427       handleFiltered(PassID, Name);
428   } else {
429     // Get the before rep from the stack
430     IRUnitT &Before = BeforeStack.back();
431     // Create the after rep
432     IRUnitT After;
433     generateIRRepresentation(IR, PassID, After);
434 
435     // Was there a change in IR?
436     if (same(Before, After)) {
437       if (VerboseMode)
438         omitAfter(PassID, Name);
439     } else
440       handleAfter(PassID, Name, Before, After, IR);
441   }
442   BeforeStack.pop_back();
443 }
444 
445 template <typename IRUnitT>
446 void ChangeReporter<IRUnitT>::handleInvalidatedPass(StringRef PassID) {
447   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
448 
449   // Always flag it as invalidated as we cannot determine when
450   // a pass for a filtered function is invalidated since we do not
451   // get the IR in the call.  Also, the output is just alternate
452   // forms of the banner anyway.
453   if (VerboseMode)
454     handleInvalidated(PassID);
455   BeforeStack.pop_back();
456 }
457 
458 template <typename IRUnitT>
459 void ChangeReporter<IRUnitT>::registerRequiredCallbacks(
460     PassInstrumentationCallbacks &PIC) {
461   PIC.registerBeforeNonSkippedPassCallback(
462       [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
463 
464   PIC.registerAfterPassCallback(
465       [this](StringRef P, Any IR, const PreservedAnalyses &) {
466         handleIRAfterPass(IR, P);
467       });
468   PIC.registerAfterPassInvalidatedCallback(
469       [this](StringRef P, const PreservedAnalyses &) {
470         handleInvalidatedPass(P);
471       });
472 }
473 
474 ChangedBlockData::ChangedBlockData(const BasicBlock &B)
475     : Label(B.getName().str()) {
476   raw_string_ostream SS(Body);
477   B.print(SS, nullptr, true, true);
478 }
479 
480 template <typename IRUnitT>
481 TextChangeReporter<IRUnitT>::TextChangeReporter(bool Verbose)
482     : ChangeReporter<IRUnitT>(Verbose), Out(dbgs()) {}
483 
484 template <typename IRUnitT>
485 void TextChangeReporter<IRUnitT>::handleInitialIR(Any IR) {
486   // Always print the module.
487   // Unwrap and print directly to avoid filtering problems in general routines.
488   auto UnwrappedModule = unwrapModule(IR, /*Force=*/true);
489   assert(UnwrappedModule && "Expected module to be unwrapped when forced.");
490   Out << "*** IR Dump At Start: ***" << UnwrappedModule->second << "\n";
491   UnwrappedModule->first->print(Out, nullptr,
492                                 /*ShouldPreserveUseListOrder=*/true);
493 }
494 
495 template <typename IRUnitT>
496 void TextChangeReporter<IRUnitT>::omitAfter(StringRef PassID,
497                                             std::string &Name) {
498   Out << formatv("*** IR Dump After {0}{1} omitted because no change ***\n",
499                  PassID, Name);
500 }
501 
502 template <typename IRUnitT>
503 void TextChangeReporter<IRUnitT>::handleInvalidated(StringRef PassID) {
504   Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
505 }
506 
507 template <typename IRUnitT>
508 void TextChangeReporter<IRUnitT>::handleFiltered(StringRef PassID,
509                                                  std::string &Name) {
510   SmallString<20> Banner =
511       formatv("*** IR Dump After {0}{1} filtered out ***\n", PassID, Name);
512   Out << Banner;
513 }
514 
515 template <typename IRUnitT>
516 void TextChangeReporter<IRUnitT>::handleIgnored(StringRef PassID,
517                                                 std::string &Name) {
518   Out << formatv("*** IR Pass {0}{1} ignored ***\n", PassID, Name);
519 }
520 
521 IRChangedPrinter::~IRChangedPrinter() {}
522 
523 void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
524   if (PrintChanged == ChangePrinter::PrintChangedVerbose ||
525       PrintChanged == ChangePrinter::PrintChangedQuiet)
526     TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
527 }
528 
529 void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
530                                                 std::string &Output) {
531   raw_string_ostream OS(Output);
532   // use the after banner for all cases so it will match
533   SmallString<20> Banner = formatv("*** IR Dump After {0} ***", PassID);
534   unwrapAndPrint(OS, IR, Banner, forcePrintModuleIR(),
535                  /*Brief=*/false, /*ShouldPreserveUseListOrder=*/true);
536 
537   OS.str();
538 }
539 
540 void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
541                                    const std::string &Before,
542                                    const std::string &After, Any) {
543   assert(After.find("*** IR Dump") == 0 && "Unexpected banner format.");
544   StringRef AfterRef = After;
545   StringRef Banner =
546       AfterRef.take_until([](char C) -> bool { return C == '\n'; });
547 
548   // Report the IR before the changes when requested.
549   if (PrintChangedBefore) {
550     Out << "*** IR Dump Before" << Banner.substr(17);
551     // LazyCallGraph::SCC already has "(scc:..." in banner so only add
552     // in the name if it isn't already there.
553     if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
554       Out << Name;
555 
556     StringRef BeforeRef = Before;
557     Out << BeforeRef.substr(Banner.size());
558   }
559 
560   Out << Banner;
561 
562   // LazyCallGraph::SCC already has "(scc:..." in banner so only add
563   // in the name if it isn't already there.
564   if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
565     Out << Name;
566 
567   Out << After.substr(Banner.size());
568 }
569 
570 bool IRChangedPrinter::same(const std::string &S1, const std::string &S2) {
571   return S1 == S2;
572 }
573 
574 template <typename IRData>
575 void OrderedChangedData<IRData>::report(
576     const OrderedChangedData &Before, const OrderedChangedData &After,
577     function_ref<void(const IRData *, const IRData *)> HandlePair) {
578   const auto &BFD = Before.getData();
579   const auto &AFD = After.getData();
580   std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
581   std::vector<std::string>::const_iterator BE = Before.getOrder().end();
582   std::vector<std::string>::const_iterator AI = After.getOrder().begin();
583   std::vector<std::string>::const_iterator AE = After.getOrder().end();
584 
585   auto handlePotentiallyRemovedIRData = [&](std::string S) {
586     // The order in LLVM may have changed so check if still exists.
587     if (!AFD.count(S)) {
588       // This has been removed.
589       HandlePair(&BFD.find(*BI)->getValue(), nullptr);
590     }
591   };
592   auto handleNewIRData = [&](std::vector<const IRData *> &Q) {
593     // Print out any queued up new sections
594     for (const IRData *NBI : Q)
595       HandlePair(nullptr, NBI);
596     Q.clear();
597   };
598 
599   // Print out the IRData in the after order, with before ones interspersed
600   // appropriately (ie, somewhere near where they were in the before list).
601   // Start at the beginning of both lists.  Loop through the
602   // after list.  If an element is common, then advance in the before list
603   // reporting the removed ones until the common one is reached.  Report any
604   // queued up new ones and then report the common one.  If an element is not
605   // common, then enqueue it for reporting.  When the after list is exhausted,
606   // loop through the before list, reporting any removed ones.  Finally,
607   // report the rest of the enqueued new ones.
608   std::vector<const IRData *> NewIRDataQueue;
609   while (AI != AE) {
610     if (!BFD.count(*AI)) {
611       // This section is new so place it in the queue.  This will cause it
612       // to be reported after deleted sections.
613       NewIRDataQueue.emplace_back(&AFD.find(*AI)->getValue());
614       ++AI;
615       continue;
616     }
617     // This section is in both; advance and print out any before-only
618     // until we get to it.
619     while (*BI != *AI) {
620       handlePotentiallyRemovedIRData(*BI);
621       ++BI;
622     }
623     // Report any new sections that were queued up and waiting.
624     handleNewIRData(NewIRDataQueue);
625 
626     const IRData &AData = AFD.find(*AI)->getValue();
627     const IRData &BData = BFD.find(*AI)->getValue();
628     HandlePair(&BData, &AData);
629     ++BI;
630     ++AI;
631   }
632 
633   // Check any remaining before sections to see if they have been removed
634   while (BI != BE) {
635     handlePotentiallyRemovedIRData(*BI);
636     ++BI;
637   }
638 
639   handleNewIRData(NewIRDataQueue);
640 }
641 
642 void ChangedIRComparer::compare(Any IR, StringRef Prefix, StringRef PassID,
643                                 StringRef Name) {
644   if (!getModuleForComparison(IR)) {
645     // Not a module so just handle the single function.
646     assert(Before.getData().size() == 1 && "Expected only one function.");
647     assert(After.getData().size() == 1 && "Expected only one function.");
648     handleFunctionCompare(Name, Prefix, PassID, false,
649                           Before.getData().begin()->getValue(),
650                           After.getData().begin()->getValue());
651     return;
652   }
653 
654   ChangedIRData::report(
655       Before, After, [&](const ChangedFuncData *B, const ChangedFuncData *A) {
656         ChangedFuncData Missing;
657         if (!B)
658           B = &Missing;
659         else if (!A)
660           A = &Missing;
661         assert(B != &Missing && A != &Missing &&
662                "Both functions cannot be missing.");
663         handleFunctionCompare(Name, Prefix, PassID, true, *B, *A);
664       });
665 }
666 
667 void ChangedIRComparer::analyzeIR(Any IR, ChangedIRData &Data) {
668   if (const Module *M = getModuleForComparison(IR)) {
669     // Create data for each existing/interesting function in the module.
670     for (const Function &F : *M)
671       generateFunctionData(Data, F);
672     return;
673   }
674 
675   const Function *F = nullptr;
676   if (any_isa<const Function *>(IR))
677     F = any_cast<const Function *>(IR);
678   else {
679     assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
680     const Loop *L = any_cast<const Loop *>(IR);
681     F = L->getHeader()->getParent();
682   }
683   assert(F && "Unknown IR unit.");
684   generateFunctionData(Data, *F);
685 }
686 
687 const Module *ChangedIRComparer::getModuleForComparison(Any IR) {
688   if (any_isa<const Module *>(IR))
689     return any_cast<const Module *>(IR);
690   if (any_isa<const LazyCallGraph::SCC *>(IR))
691     return any_cast<const LazyCallGraph::SCC *>(IR)
692         ->begin()
693         ->getFunction()
694         .getParent();
695   return nullptr;
696 }
697 
698 bool ChangedIRComparer::generateFunctionData(ChangedIRData &Data,
699                                              const Function &F) {
700   if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
701     ChangedFuncData CFD;
702     for (const auto &B : F) {
703       CFD.getOrder().emplace_back(B.getName());
704       CFD.getData().insert({B.getName(), B});
705     }
706     Data.getOrder().emplace_back(F.getName());
707     Data.getData().insert({F.getName(), CFD});
708     return true;
709   }
710   return false;
711 }
712 
713 PrintIRInstrumentation::~PrintIRInstrumentation() {
714   assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
715 }
716 
717 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
718   assert(StoreModuleDesc);
719   const Module *M = nullptr;
720   std::string Extra;
721   if (auto UnwrappedModule = unwrapModule(IR))
722     std::tie(M, Extra) = UnwrappedModule.getValue();
723   ModuleDescStack.emplace_back(M, Extra, PassID);
724 }
725 
726 PrintIRInstrumentation::PrintModuleDesc
727 PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
728   assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
729   PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
730   assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
731   return ModuleDesc;
732 }
733 
734 void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
735   if (isIgnored(PassID))
736     return;
737 
738   // Saving Module for AfterPassInvalidated operations.
739   // Note: here we rely on a fact that we do not change modules while
740   // traversing the pipeline, so the latest captured module is good
741   // for all print operations that has not happen yet.
742   if (StoreModuleDesc && shouldPrintAfterPass(PassID))
743     pushModuleDesc(PassID, IR);
744 
745   if (!shouldPrintBeforePass(PassID))
746     return;
747 
748   SmallString<20> Banner = formatv("*** IR Dump Before {0} ***", PassID);
749   unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
750 }
751 
752 void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
753   if (isIgnored(PassID))
754     return;
755 
756   if (!shouldPrintAfterPass(PassID))
757     return;
758 
759   if (StoreModuleDesc)
760     popModuleDesc(PassID);
761 
762   SmallString<20> Banner = formatv("*** IR Dump After {0} ***", PassID);
763   unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
764 }
765 
766 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
767   StringRef PassName = PIC->getPassNameForClassName(PassID);
768   if (!StoreModuleDesc || !shouldPrintAfterPass(PassName))
769     return;
770 
771   if (isIgnored(PassID))
772     return;
773 
774   const Module *M;
775   std::string Extra;
776   StringRef StoredPassID;
777   std::tie(M, Extra, StoredPassID) = popModuleDesc(PassID);
778   // Additional filtering (e.g. -filter-print-func) can lead to module
779   // printing being skipped.
780   if (!M)
781     return;
782 
783   SmallString<20> Banner =
784       formatv("*** IR Dump After {0} *** invalidated: ", PassID);
785   printIR(dbgs(), M, Banner, Extra);
786 }
787 
788 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
789   if (shouldPrintBeforeAll())
790     return true;
791 
792   StringRef PassName = PIC->getPassNameForClassName(PassID);
793   return llvm::is_contained(printBeforePasses(), PassName);
794 }
795 
796 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
797   if (shouldPrintAfterAll())
798     return true;
799 
800   StringRef PassName = PIC->getPassNameForClassName(PassID);
801   return llvm::is_contained(printAfterPasses(), PassName);
802 }
803 
804 void PrintIRInstrumentation::registerCallbacks(
805     PassInstrumentationCallbacks &PIC) {
806   this->PIC = &PIC;
807 
808   // BeforePass callback is not just for printing, it also saves a Module
809   // for later use in AfterPassInvalidated.
810   StoreModuleDesc = forcePrintModuleIR() && shouldPrintAfterSomePass();
811   if (shouldPrintBeforeSomePass() || StoreModuleDesc)
812     PIC.registerBeforeNonSkippedPassCallback(
813         [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
814 
815   if (shouldPrintAfterSomePass()) {
816     PIC.registerAfterPassCallback(
817         [this](StringRef P, Any IR, const PreservedAnalyses &) {
818           this->printAfterPass(P, IR);
819         });
820     PIC.registerAfterPassInvalidatedCallback(
821         [this](StringRef P, const PreservedAnalyses &) {
822           this->printAfterPassInvalidated(P);
823         });
824   }
825 }
826 
827 void OptNoneInstrumentation::registerCallbacks(
828     PassInstrumentationCallbacks &PIC) {
829   PIC.registerShouldRunOptionalPassCallback(
830       [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
831 }
832 
833 bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
834   const Function *F = nullptr;
835   if (any_isa<const Function *>(IR)) {
836     F = any_cast<const Function *>(IR);
837   } else if (any_isa<const Loop *>(IR)) {
838     F = any_cast<const Loop *>(IR)->getHeader()->getParent();
839   }
840   bool ShouldRun = !(F && F->hasOptNone());
841   if (!ShouldRun && DebugLogging) {
842     errs() << "Skipping pass " << PassID << " on " << F->getName()
843            << " due to optnone attribute\n";
844   }
845   return ShouldRun;
846 }
847 
848 static std::string getBisectDescription(Any IR) {
849   if (any_isa<const Module *>(IR)) {
850     const Module *M = any_cast<const Module *>(IR);
851     assert(M && "module should be valid for printing");
852     return "module (" + M->getName().str() + ")";
853   }
854 
855   if (any_isa<const Function *>(IR)) {
856     const Function *F = any_cast<const Function *>(IR);
857     assert(F && "function should be valid for printing");
858     return "function (" + F->getName().str() + ")";
859   }
860 
861   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
862     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
863     assert(C && "scc should be valid for printing");
864     return "SCC " + C->getName();
865   }
866 
867   if (any_isa<const Loop *>(IR)) {
868     return "loop";
869   }
870 
871   llvm_unreachable("Unknown wrapped IR type");
872 }
873 
874 void OptBisectInstrumentation::registerCallbacks(
875     PassInstrumentationCallbacks &PIC) {
876   if (!OptBisector->isEnabled())
877     return;
878   PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
879     return isIgnored(PassID) ||
880            OptBisector->checkPass(PassID, getBisectDescription(IR));
881   });
882 }
883 
884 void PrintPassInstrumentation::registerCallbacks(
885     PassInstrumentationCallbacks &PIC) {
886   if (!DebugLogging)
887     return;
888 
889   std::vector<StringRef> SpecialPasses = {"PassManager"};
890   if (!DebugPMVerbose)
891     SpecialPasses.emplace_back("PassAdaptor");
892 
893   PIC.registerBeforeSkippedPassCallback(
894       [SpecialPasses](StringRef PassID, Any IR) {
895         assert(!isSpecialPass(PassID, SpecialPasses) &&
896                "Unexpectedly skipping special pass");
897 
898         dbgs() << "Skipping pass: " << PassID << " on ";
899         unwrapAndPrint(dbgs(), IR, "", false, true);
900       });
901 
902   PIC.registerBeforeNonSkippedPassCallback(
903       [SpecialPasses](StringRef PassID, Any IR) {
904         if (isSpecialPass(PassID, SpecialPasses))
905           return;
906 
907         dbgs() << "Running pass: " << PassID << " on ";
908         unwrapAndPrint(dbgs(), IR, "", false, true);
909       });
910 
911   PIC.registerBeforeAnalysisCallback([](StringRef PassID, Any IR) {
912     dbgs() << "Running analysis: " << PassID << " on ";
913     unwrapAndPrint(dbgs(), IR, "", false, true);
914   });
915 }
916 
917 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
918                                              bool TrackBBLifetime) {
919   if (TrackBBLifetime)
920     BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
921   for (const auto &BB : *F) {
922     if (BBGuards)
923       BBGuards->try_emplace(intptr_t(&BB), &BB);
924     for (auto *Succ : successors(&BB)) {
925       Graph[&BB][Succ]++;
926       if (BBGuards)
927         BBGuards->try_emplace(intptr_t(Succ), Succ);
928     }
929   }
930 }
931 
932 static void printBBName(raw_ostream &out, const BasicBlock *BB) {
933   if (BB->hasName()) {
934     out << BB->getName() << "<" << BB << ">";
935     return;
936   }
937 
938   if (!BB->getParent()) {
939     out << "unnamed_removed<" << BB << ">";
940     return;
941   }
942 
943   if (BB == &BB->getParent()->getEntryBlock()) {
944     out << "entry"
945         << "<" << BB << ">";
946     return;
947   }
948 
949   unsigned FuncOrderBlockNum = 0;
950   for (auto &FuncBB : *BB->getParent()) {
951     if (&FuncBB == BB)
952       break;
953     FuncOrderBlockNum++;
954   }
955   out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
956 }
957 
958 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
959                                                         const CFG &Before,
960                                                         const CFG &After) {
961   assert(!After.isPoisoned());
962   if (Before.isPoisoned()) {
963     out << "Some blocks were deleted\n";
964     return;
965   }
966 
967   // Find and print graph differences.
968   if (Before.Graph.size() != After.Graph.size())
969     out << "Different number of non-leaf basic blocks: before="
970         << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
971 
972   for (auto &BB : Before.Graph) {
973     auto BA = After.Graph.find(BB.first);
974     if (BA == After.Graph.end()) {
975       out << "Non-leaf block ";
976       printBBName(out, BB.first);
977       out << " is removed (" << BB.second.size() << " successors)\n";
978     }
979   }
980 
981   for (auto &BA : After.Graph) {
982     auto BB = Before.Graph.find(BA.first);
983     if (BB == Before.Graph.end()) {
984       out << "Non-leaf block ";
985       printBBName(out, BA.first);
986       out << " is added (" << BA.second.size() << " successors)\n";
987       continue;
988     }
989 
990     if (BB->second == BA.second)
991       continue;
992 
993     out << "Different successors of block ";
994     printBBName(out, BA.first);
995     out << " (unordered):\n";
996     out << "- before (" << BB->second.size() << "): ";
997     for (auto &SuccB : BB->second) {
998       printBBName(out, SuccB.first);
999       if (SuccB.second != 1)
1000         out << "(" << SuccB.second << "), ";
1001       else
1002         out << ", ";
1003     }
1004     out << "\n";
1005     out << "- after (" << BA.second.size() << "): ";
1006     for (auto &SuccA : BA.second) {
1007       printBBName(out, SuccA.first);
1008       if (SuccA.second != 1)
1009         out << "(" << SuccA.second << "), ";
1010       else
1011         out << ", ";
1012     }
1013     out << "\n";
1014   }
1015 }
1016 
1017 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1018 // passes, that reported they kept CFG analyses up-to-date, did not actually
1019 // change CFG. This check is done as follows. Before every functional pass in
1020 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1021 // PreservedCFGCheckerInstrumentation::CFG) is requested from
1022 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1023 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1024 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1025 // available) is checked to be equal to a freshly created CFG snapshot.
1026 struct PreservedCFGCheckerAnalysis
1027     : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
1028   friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;
1029 
1030   static AnalysisKey Key;
1031 
1032 public:
1033   /// Provide the result type for this analysis pass.
1034   using Result = PreservedCFGCheckerInstrumentation::CFG;
1035 
1036   /// Run the analysis pass over a function and produce CFG.
1037   Result run(Function &F, FunctionAnalysisManager &FAM) {
1038     return Result(&F, /* TrackBBLifetime */ true);
1039   }
1040 };
1041 
1042 AnalysisKey PreservedCFGCheckerAnalysis::Key;
1043 
1044 bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
1045     Function &F, const PreservedAnalyses &PA,
1046     FunctionAnalysisManager::Invalidator &) {
1047   auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
1048   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1049            PAC.preservedSet<CFGAnalyses>());
1050 }
1051 
1052 void PreservedCFGCheckerInstrumentation::registerCallbacks(
1053     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) {
1054   if (!VerifyPreservedCFG)
1055     return;
1056 
1057   FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1058 
1059   auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore,
1060                      const CFG &GraphAfter) {
1061     if (GraphAfter == GraphBefore)
1062       return;
1063 
1064     dbgs() << "Error: " << Pass
1065            << " does not invalidate CFG analyses but CFG changes detected in "
1066               "function @"
1067            << FuncName << ":\n";
1068     CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
1069     report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
1070   };
1071 
1072   PIC.registerBeforeNonSkippedPassCallback(
1073       [this, &FAM](StringRef P, Any IR) {
1074         assert(&PassStack.emplace_back(P));
1075         (void)this;
1076         if (!any_isa<const Function *>(IR))
1077           return;
1078 
1079         const auto *F = any_cast<const Function *>(IR);
1080         // Make sure a fresh CFG snapshot is available before the pass.
1081         FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F));
1082       });
1083 
1084   PIC.registerAfterPassInvalidatedCallback(
1085       [this](StringRef P, const PreservedAnalyses &PassPA) {
1086         assert(PassStack.pop_back_val() == P &&
1087                "Before and After callbacks must correspond");
1088         (void)this;
1089       });
1090 
1091   PIC.registerAfterPassCallback([this, &FAM,
1092                                  checkCFG](StringRef P, Any IR,
1093                                            const PreservedAnalyses &PassPA) {
1094     assert(PassStack.pop_back_val() == P &&
1095            "Before and After callbacks must correspond");
1096     (void)this;
1097 
1098     if (!any_isa<const Function *>(IR))
1099       return;
1100 
1101     if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() &&
1102         !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>())
1103       return;
1104 
1105     const auto *F = any_cast<const Function *>(IR);
1106     if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>(
1107             *const_cast<Function *>(F)))
1108       checkCFG(P, F->getName(), *GraphBefore,
1109                CFG(F, /* TrackBBLifetime */ false));
1110   });
1111 }
1112 
1113 void VerifyInstrumentation::registerCallbacks(
1114     PassInstrumentationCallbacks &PIC) {
1115   PIC.registerAfterPassCallback(
1116       [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1117         if (isIgnored(P) || P == "VerifierPass")
1118           return;
1119         if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
1120           const Function *F;
1121           if (any_isa<const Loop *>(IR))
1122             F = any_cast<const Loop *>(IR)->getHeader()->getParent();
1123           else
1124             F = any_cast<const Function *>(IR);
1125           if (DebugLogging)
1126             dbgs() << "Verifying function " << F->getName() << "\n";
1127 
1128           if (verifyFunction(*F))
1129             report_fatal_error("Broken function found, compilation aborted!");
1130         } else if (any_isa<const Module *>(IR) ||
1131                    any_isa<const LazyCallGraph::SCC *>(IR)) {
1132           const Module *M;
1133           if (any_isa<const LazyCallGraph::SCC *>(IR))
1134             M = any_cast<const LazyCallGraph::SCC *>(IR)
1135                     ->begin()
1136                     ->getFunction()
1137                     .getParent();
1138           else
1139             M = any_cast<const Module *>(IR);
1140           if (DebugLogging)
1141             dbgs() << "Verifying module " << M->getName() << "\n";
1142 
1143           if (verifyModule(*M))
1144             report_fatal_error("Broken module found, compilation aborted!");
1145         }
1146       });
1147 }
1148 
1149 InLineChangePrinter::~InLineChangePrinter() {}
1150 
1151 void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID,
1152                                                    ChangedIRData &D) {
1153   ChangedIRComparer::analyzeIR(IR, D);
1154 }
1155 
1156 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
1157                                       const ChangedIRData &Before,
1158                                       const ChangedIRData &After, Any IR) {
1159   if (Name == "")
1160     Name = " (module)";
1161   SmallString<20> Banner =
1162       formatv("*** IR Dump After {0} ***{1}\n", PassID, Name);
1163   Out << Banner;
1164   ChangedIRComparer(Out, Before, After, UseColour)
1165       .compare(IR, "", PassID, Name);
1166   Out << "\n";
1167 }
1168 
1169 bool InLineChangePrinter::same(const ChangedIRData &D1,
1170                                const ChangedIRData &D2) {
1171   return D1 == D2;
1172 }
1173 
1174 void ChangedIRComparer::handleFunctionCompare(StringRef Name, StringRef Prefix,
1175                                               StringRef PassID, bool InModule,
1176                                               const ChangedFuncData &Before,
1177                                               const ChangedFuncData &After) {
1178   // Print a banner when this is being shown in the context of a module
1179   if (InModule)
1180     Out << "\n*** IR for function " << Name << " ***\n";
1181 
1182   ChangedFuncData::report(
1183       Before, After, [&](const ChangedBlockData *B, const ChangedBlockData *A) {
1184         StringRef BStr = B ? B->getBody() : "\n";
1185         StringRef AStr = A ? A->getBody() : "\n";
1186         const std::string Removed =
1187             UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
1188         const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
1189         const std::string NoChange = " %l\n";
1190         Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
1191       });
1192 }
1193 
1194 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
1195   if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1196       PrintChanged == ChangePrinter::PrintChangedDiffQuiet ||
1197       PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1198       PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet)
1199     TextChangeReporter<ChangedIRData>::registerRequiredCallbacks(PIC);
1200 }
1201 
1202 StandardInstrumentations::StandardInstrumentations(bool DebugLogging,
1203                                                    bool VerifyEach)
1204     : PrintPass(DebugLogging), OptNone(DebugLogging),
1205       PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose),
1206       PrintChangedDiff(
1207           PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1208               PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose,
1209           PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1210               PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet),
1211       Verify(DebugLogging), VerifyEach(VerifyEach) {}
1212 
1213 void StandardInstrumentations::registerCallbacks(
1214     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) {
1215   PrintIR.registerCallbacks(PIC);
1216   PrintPass.registerCallbacks(PIC);
1217   TimePasses.registerCallbacks(PIC);
1218   OptNone.registerCallbacks(PIC);
1219   OptBisect.registerCallbacks(PIC);
1220   if (FAM)
1221     PreservedCFGChecker.registerCallbacks(PIC, *FAM);
1222   PrintChangedIR.registerCallbacks(PIC);
1223   PseudoProbeVerification.registerCallbacks(PIC);
1224   if (VerifyEach)
1225     Verify.registerCallbacks(PIC);
1226   PrintChangedDiff.registerCallbacks(PIC);
1227 }
1228 
1229 namespace llvm {
1230 
1231 template class ChangeReporter<std::string>;
1232 template class TextChangeReporter<std::string>;
1233 
1234 template class ChangeReporter<ChangedIRData>;
1235 template class TextChangeReporter<ChangedIRData>;
1236 
1237 } // namespace llvm
1238