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   // We might not get anything to print if we only want to print a specific
544   // function but it gets deleted.
545   if (After.empty()) {
546     Out << "*** IR Deleted After " << PassID << Name << " ***\n";
547     return;
548   }
549 
550   assert(After.find("*** IR Dump") == 0 && "Unexpected banner format.");
551   StringRef AfterRef = After;
552   StringRef Banner =
553       AfterRef.take_until([](char C) -> bool { return C == '\n'; });
554 
555   // Report the IR before the changes when requested.
556   if (PrintChangedBefore) {
557     Out << "*** IR Dump Before" << Banner.substr(17);
558     // LazyCallGraph::SCC already has "(scc:..." in banner so only add
559     // in the name if it isn't already there.
560     if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
561       Out << Name;
562 
563     StringRef BeforeRef = Before;
564     Out << BeforeRef.substr(Banner.size());
565   }
566 
567   Out << Banner;
568 
569   // LazyCallGraph::SCC already has "(scc:..." in banner so only add
570   // in the name if it isn't already there.
571   if (Name.substr(0, 6) != " (scc:" && !forcePrintModuleIR())
572     Out << Name;
573 
574   Out << After.substr(Banner.size());
575 }
576 
577 bool IRChangedPrinter::same(const std::string &S1, const std::string &S2) {
578   return S1 == S2;
579 }
580 
581 template <typename IRData>
582 void OrderedChangedData<IRData>::report(
583     const OrderedChangedData &Before, const OrderedChangedData &After,
584     function_ref<void(const IRData *, const IRData *)> HandlePair) {
585   const auto &BFD = Before.getData();
586   const auto &AFD = After.getData();
587   std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
588   std::vector<std::string>::const_iterator BE = Before.getOrder().end();
589   std::vector<std::string>::const_iterator AI = After.getOrder().begin();
590   std::vector<std::string>::const_iterator AE = After.getOrder().end();
591 
592   auto handlePotentiallyRemovedIRData = [&](std::string S) {
593     // The order in LLVM may have changed so check if still exists.
594     if (!AFD.count(S)) {
595       // This has been removed.
596       HandlePair(&BFD.find(*BI)->getValue(), nullptr);
597     }
598   };
599   auto handleNewIRData = [&](std::vector<const IRData *> &Q) {
600     // Print out any queued up new sections
601     for (const IRData *NBI : Q)
602       HandlePair(nullptr, NBI);
603     Q.clear();
604   };
605 
606   // Print out the IRData in the after order, with before ones interspersed
607   // appropriately (ie, somewhere near where they were in the before list).
608   // Start at the beginning of both lists.  Loop through the
609   // after list.  If an element is common, then advance in the before list
610   // reporting the removed ones until the common one is reached.  Report any
611   // queued up new ones and then report the common one.  If an element is not
612   // common, then enqueue it for reporting.  When the after list is exhausted,
613   // loop through the before list, reporting any removed ones.  Finally,
614   // report the rest of the enqueued new ones.
615   std::vector<const IRData *> NewIRDataQueue;
616   while (AI != AE) {
617     if (!BFD.count(*AI)) {
618       // This section is new so place it in the queue.  This will cause it
619       // to be reported after deleted sections.
620       NewIRDataQueue.emplace_back(&AFD.find(*AI)->getValue());
621       ++AI;
622       continue;
623     }
624     // This section is in both; advance and print out any before-only
625     // until we get to it.
626     while (*BI != *AI) {
627       handlePotentiallyRemovedIRData(*BI);
628       ++BI;
629     }
630     // Report any new sections that were queued up and waiting.
631     handleNewIRData(NewIRDataQueue);
632 
633     const IRData &AData = AFD.find(*AI)->getValue();
634     const IRData &BData = BFD.find(*AI)->getValue();
635     HandlePair(&BData, &AData);
636     ++BI;
637     ++AI;
638   }
639 
640   // Check any remaining before sections to see if they have been removed
641   while (BI != BE) {
642     handlePotentiallyRemovedIRData(*BI);
643     ++BI;
644   }
645 
646   handleNewIRData(NewIRDataQueue);
647 }
648 
649 void ChangedIRComparer::compare(Any IR, StringRef Prefix, StringRef PassID,
650                                 StringRef Name) {
651   if (!getModuleForComparison(IR)) {
652     // Not a module so just handle the single function.
653     assert(Before.getData().size() == 1 && "Expected only one function.");
654     assert(After.getData().size() == 1 && "Expected only one function.");
655     handleFunctionCompare(Name, Prefix, PassID, false,
656                           Before.getData().begin()->getValue(),
657                           After.getData().begin()->getValue());
658     return;
659   }
660 
661   ChangedIRData::report(
662       Before, After, [&](const ChangedFuncData *B, const ChangedFuncData *A) {
663         ChangedFuncData Missing;
664         if (!B)
665           B = &Missing;
666         else if (!A)
667           A = &Missing;
668         assert(B != &Missing && A != &Missing &&
669                "Both functions cannot be missing.");
670         handleFunctionCompare(Name, Prefix, PassID, true, *B, *A);
671       });
672 }
673 
674 void ChangedIRComparer::analyzeIR(Any IR, ChangedIRData &Data) {
675   if (const Module *M = getModuleForComparison(IR)) {
676     // Create data for each existing/interesting function in the module.
677     for (const Function &F : *M)
678       generateFunctionData(Data, F);
679     return;
680   }
681 
682   const Function *F = nullptr;
683   if (any_isa<const Function *>(IR))
684     F = any_cast<const Function *>(IR);
685   else {
686     assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
687     const Loop *L = any_cast<const Loop *>(IR);
688     F = L->getHeader()->getParent();
689   }
690   assert(F && "Unknown IR unit.");
691   generateFunctionData(Data, *F);
692 }
693 
694 const Module *ChangedIRComparer::getModuleForComparison(Any IR) {
695   if (any_isa<const Module *>(IR))
696     return any_cast<const Module *>(IR);
697   if (any_isa<const LazyCallGraph::SCC *>(IR))
698     return any_cast<const LazyCallGraph::SCC *>(IR)
699         ->begin()
700         ->getFunction()
701         .getParent();
702   return nullptr;
703 }
704 
705 bool ChangedIRComparer::generateFunctionData(ChangedIRData &Data,
706                                              const Function &F) {
707   if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
708     ChangedFuncData CFD;
709     for (const auto &B : F) {
710       CFD.getOrder().emplace_back(B.getName());
711       CFD.getData().insert({B.getName(), B});
712     }
713     Data.getOrder().emplace_back(F.getName());
714     Data.getData().insert({F.getName(), CFD});
715     return true;
716   }
717   return false;
718 }
719 
720 PrintIRInstrumentation::~PrintIRInstrumentation() {
721   assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
722 }
723 
724 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
725   assert(StoreModuleDesc);
726   const Module *M = nullptr;
727   std::string Extra;
728   if (auto UnwrappedModule = unwrapModule(IR))
729     std::tie(M, Extra) = UnwrappedModule.getValue();
730   ModuleDescStack.emplace_back(M, Extra, PassID);
731 }
732 
733 PrintIRInstrumentation::PrintModuleDesc
734 PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
735   assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
736   PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
737   assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
738   return ModuleDesc;
739 }
740 
741 void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
742   if (isIgnored(PassID))
743     return;
744 
745   // Saving Module for AfterPassInvalidated operations.
746   // Note: here we rely on a fact that we do not change modules while
747   // traversing the pipeline, so the latest captured module is good
748   // for all print operations that has not happen yet.
749   if (StoreModuleDesc && shouldPrintAfterPass(PassID))
750     pushModuleDesc(PassID, IR);
751 
752   if (!shouldPrintBeforePass(PassID))
753     return;
754 
755   SmallString<20> Banner = formatv("*** IR Dump Before {0} ***", PassID);
756   unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
757 }
758 
759 void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
760   if (isIgnored(PassID))
761     return;
762 
763   if (!shouldPrintAfterPass(PassID))
764     return;
765 
766   if (StoreModuleDesc)
767     popModuleDesc(PassID);
768 
769   SmallString<20> Banner = formatv("*** IR Dump After {0} ***", PassID);
770   unwrapAndPrint(dbgs(), IR, Banner, forcePrintModuleIR());
771 }
772 
773 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
774   StringRef PassName = PIC->getPassNameForClassName(PassID);
775   if (!StoreModuleDesc || !shouldPrintAfterPass(PassName))
776     return;
777 
778   if (isIgnored(PassID))
779     return;
780 
781   const Module *M;
782   std::string Extra;
783   StringRef StoredPassID;
784   std::tie(M, Extra, StoredPassID) = popModuleDesc(PassID);
785   // Additional filtering (e.g. -filter-print-func) can lead to module
786   // printing being skipped.
787   if (!M)
788     return;
789 
790   SmallString<20> Banner =
791       formatv("*** IR Dump After {0} *** invalidated: ", PassID);
792   printIR(dbgs(), M, Banner, Extra);
793 }
794 
795 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
796   if (shouldPrintBeforeAll())
797     return true;
798 
799   StringRef PassName = PIC->getPassNameForClassName(PassID);
800   return llvm::is_contained(printBeforePasses(), PassName);
801 }
802 
803 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
804   if (shouldPrintAfterAll())
805     return true;
806 
807   StringRef PassName = PIC->getPassNameForClassName(PassID);
808   return llvm::is_contained(printAfterPasses(), PassName);
809 }
810 
811 void PrintIRInstrumentation::registerCallbacks(
812     PassInstrumentationCallbacks &PIC) {
813   this->PIC = &PIC;
814 
815   // BeforePass callback is not just for printing, it also saves a Module
816   // for later use in AfterPassInvalidated.
817   StoreModuleDesc = forcePrintModuleIR() && shouldPrintAfterSomePass();
818   if (shouldPrintBeforeSomePass() || StoreModuleDesc)
819     PIC.registerBeforeNonSkippedPassCallback(
820         [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
821 
822   if (shouldPrintAfterSomePass()) {
823     PIC.registerAfterPassCallback(
824         [this](StringRef P, Any IR, const PreservedAnalyses &) {
825           this->printAfterPass(P, IR);
826         });
827     PIC.registerAfterPassInvalidatedCallback(
828         [this](StringRef P, const PreservedAnalyses &) {
829           this->printAfterPassInvalidated(P);
830         });
831   }
832 }
833 
834 void OptNoneInstrumentation::registerCallbacks(
835     PassInstrumentationCallbacks &PIC) {
836   PIC.registerShouldRunOptionalPassCallback(
837       [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
838 }
839 
840 bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
841   const Function *F = nullptr;
842   if (any_isa<const Function *>(IR)) {
843     F = any_cast<const Function *>(IR);
844   } else if (any_isa<const Loop *>(IR)) {
845     F = any_cast<const Loop *>(IR)->getHeader()->getParent();
846   }
847   bool ShouldRun = !(F && F->hasOptNone());
848   if (!ShouldRun && DebugLogging) {
849     errs() << "Skipping pass " << PassID << " on " << F->getName()
850            << " due to optnone attribute\n";
851   }
852   return ShouldRun;
853 }
854 
855 static std::string getBisectDescription(Any IR) {
856   if (any_isa<const Module *>(IR)) {
857     const Module *M = any_cast<const Module *>(IR);
858     assert(M && "module should be valid for printing");
859     return "module (" + M->getName().str() + ")";
860   }
861 
862   if (any_isa<const Function *>(IR)) {
863     const Function *F = any_cast<const Function *>(IR);
864     assert(F && "function should be valid for printing");
865     return "function (" + F->getName().str() + ")";
866   }
867 
868   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
869     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
870     assert(C && "scc should be valid for printing");
871     return "SCC " + C->getName();
872   }
873 
874   if (any_isa<const Loop *>(IR)) {
875     return "loop";
876   }
877 
878   llvm_unreachable("Unknown wrapped IR type");
879 }
880 
881 void OptBisectInstrumentation::registerCallbacks(
882     PassInstrumentationCallbacks &PIC) {
883   if (!OptBisector->isEnabled())
884     return;
885   PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
886     return isIgnored(PassID) ||
887            OptBisector->checkPass(PassID, getBisectDescription(IR));
888   });
889 }
890 
891 void PrintPassInstrumentation::registerCallbacks(
892     PassInstrumentationCallbacks &PIC) {
893   if (!DebugLogging)
894     return;
895 
896   std::vector<StringRef> SpecialPasses = {"PassManager"};
897   if (!DebugPMVerbose)
898     SpecialPasses.emplace_back("PassAdaptor");
899 
900   PIC.registerBeforeSkippedPassCallback(
901       [SpecialPasses](StringRef PassID, Any IR) {
902         assert(!isSpecialPass(PassID, SpecialPasses) &&
903                "Unexpectedly skipping special pass");
904 
905         dbgs() << "Skipping pass: " << PassID << " on ";
906         unwrapAndPrint(dbgs(), IR, "", false, true);
907       });
908 
909   PIC.registerBeforeNonSkippedPassCallback(
910       [SpecialPasses](StringRef PassID, Any IR) {
911         if (isSpecialPass(PassID, SpecialPasses))
912           return;
913 
914         dbgs() << "Running pass: " << PassID << " on ";
915         unwrapAndPrint(dbgs(), IR, "", false, true);
916       });
917 
918   PIC.registerBeforeAnalysisCallback([](StringRef PassID, Any IR) {
919     dbgs() << "Running analysis: " << PassID << " on ";
920     unwrapAndPrint(dbgs(), IR, "", false, true);
921   });
922 }
923 
924 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
925                                              bool TrackBBLifetime) {
926   if (TrackBBLifetime)
927     BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
928   for (const auto &BB : *F) {
929     if (BBGuards)
930       BBGuards->try_emplace(intptr_t(&BB), &BB);
931     for (auto *Succ : successors(&BB)) {
932       Graph[&BB][Succ]++;
933       if (BBGuards)
934         BBGuards->try_emplace(intptr_t(Succ), Succ);
935     }
936   }
937 }
938 
939 static void printBBName(raw_ostream &out, const BasicBlock *BB) {
940   if (BB->hasName()) {
941     out << BB->getName() << "<" << BB << ">";
942     return;
943   }
944 
945   if (!BB->getParent()) {
946     out << "unnamed_removed<" << BB << ">";
947     return;
948   }
949 
950   if (BB == &BB->getParent()->getEntryBlock()) {
951     out << "entry"
952         << "<" << BB << ">";
953     return;
954   }
955 
956   unsigned FuncOrderBlockNum = 0;
957   for (auto &FuncBB : *BB->getParent()) {
958     if (&FuncBB == BB)
959       break;
960     FuncOrderBlockNum++;
961   }
962   out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
963 }
964 
965 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
966                                                         const CFG &Before,
967                                                         const CFG &After) {
968   assert(!After.isPoisoned());
969   if (Before.isPoisoned()) {
970     out << "Some blocks were deleted\n";
971     return;
972   }
973 
974   // Find and print graph differences.
975   if (Before.Graph.size() != After.Graph.size())
976     out << "Different number of non-leaf basic blocks: before="
977         << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
978 
979   for (auto &BB : Before.Graph) {
980     auto BA = After.Graph.find(BB.first);
981     if (BA == After.Graph.end()) {
982       out << "Non-leaf block ";
983       printBBName(out, BB.first);
984       out << " is removed (" << BB.second.size() << " successors)\n";
985     }
986   }
987 
988   for (auto &BA : After.Graph) {
989     auto BB = Before.Graph.find(BA.first);
990     if (BB == Before.Graph.end()) {
991       out << "Non-leaf block ";
992       printBBName(out, BA.first);
993       out << " is added (" << BA.second.size() << " successors)\n";
994       continue;
995     }
996 
997     if (BB->second == BA.second)
998       continue;
999 
1000     out << "Different successors of block ";
1001     printBBName(out, BA.first);
1002     out << " (unordered):\n";
1003     out << "- before (" << BB->second.size() << "): ";
1004     for (auto &SuccB : BB->second) {
1005       printBBName(out, SuccB.first);
1006       if (SuccB.second != 1)
1007         out << "(" << SuccB.second << "), ";
1008       else
1009         out << ", ";
1010     }
1011     out << "\n";
1012     out << "- after (" << BA.second.size() << "): ";
1013     for (auto &SuccA : BA.second) {
1014       printBBName(out, SuccA.first);
1015       if (SuccA.second != 1)
1016         out << "(" << SuccA.second << "), ";
1017       else
1018         out << ", ";
1019     }
1020     out << "\n";
1021   }
1022 }
1023 
1024 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1025 // passes, that reported they kept CFG analyses up-to-date, did not actually
1026 // change CFG. This check is done as follows. Before every functional pass in
1027 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1028 // PreservedCFGCheckerInstrumentation::CFG) is requested from
1029 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1030 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1031 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1032 // available) is checked to be equal to a freshly created CFG snapshot.
1033 struct PreservedCFGCheckerAnalysis
1034     : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
1035   friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;
1036 
1037   static AnalysisKey Key;
1038 
1039 public:
1040   /// Provide the result type for this analysis pass.
1041   using Result = PreservedCFGCheckerInstrumentation::CFG;
1042 
1043   /// Run the analysis pass over a function and produce CFG.
1044   Result run(Function &F, FunctionAnalysisManager &FAM) {
1045     return Result(&F, /* TrackBBLifetime */ true);
1046   }
1047 };
1048 
1049 AnalysisKey PreservedCFGCheckerAnalysis::Key;
1050 
1051 bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
1052     Function &F, const PreservedAnalyses &PA,
1053     FunctionAnalysisManager::Invalidator &) {
1054   auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
1055   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1056            PAC.preservedSet<CFGAnalyses>());
1057 }
1058 
1059 void PreservedCFGCheckerInstrumentation::registerCallbacks(
1060     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) {
1061   if (!VerifyPreservedCFG)
1062     return;
1063 
1064   FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1065 
1066   auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore,
1067                      const CFG &GraphAfter) {
1068     if (GraphAfter == GraphBefore)
1069       return;
1070 
1071     dbgs() << "Error: " << Pass
1072            << " does not invalidate CFG analyses but CFG changes detected in "
1073               "function @"
1074            << FuncName << ":\n";
1075     CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
1076     report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
1077   };
1078 
1079   PIC.registerBeforeNonSkippedPassCallback(
1080       [this, &FAM](StringRef P, Any IR) {
1081         assert(&PassStack.emplace_back(P));
1082         (void)this;
1083         if (!any_isa<const Function *>(IR))
1084           return;
1085 
1086         const auto *F = any_cast<const Function *>(IR);
1087         // Make sure a fresh CFG snapshot is available before the pass.
1088         FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F));
1089       });
1090 
1091   PIC.registerAfterPassInvalidatedCallback(
1092       [this](StringRef P, const PreservedAnalyses &PassPA) {
1093         assert(PassStack.pop_back_val() == P &&
1094                "Before and After callbacks must correspond");
1095         (void)this;
1096       });
1097 
1098   PIC.registerAfterPassCallback([this, &FAM,
1099                                  checkCFG](StringRef P, Any IR,
1100                                            const PreservedAnalyses &PassPA) {
1101     assert(PassStack.pop_back_val() == P &&
1102            "Before and After callbacks must correspond");
1103     (void)this;
1104 
1105     if (!any_isa<const Function *>(IR))
1106       return;
1107 
1108     if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() &&
1109         !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>())
1110       return;
1111 
1112     const auto *F = any_cast<const Function *>(IR);
1113     if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>(
1114             *const_cast<Function *>(F)))
1115       checkCFG(P, F->getName(), *GraphBefore,
1116                CFG(F, /* TrackBBLifetime */ false));
1117   });
1118 }
1119 
1120 void VerifyInstrumentation::registerCallbacks(
1121     PassInstrumentationCallbacks &PIC) {
1122   PIC.registerAfterPassCallback(
1123       [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1124         if (isIgnored(P) || P == "VerifierPass")
1125           return;
1126         if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
1127           const Function *F;
1128           if (any_isa<const Loop *>(IR))
1129             F = any_cast<const Loop *>(IR)->getHeader()->getParent();
1130           else
1131             F = any_cast<const Function *>(IR);
1132           if (DebugLogging)
1133             dbgs() << "Verifying function " << F->getName() << "\n";
1134 
1135           if (verifyFunction(*F))
1136             report_fatal_error("Broken function found, compilation aborted!");
1137         } else if (any_isa<const Module *>(IR) ||
1138                    any_isa<const LazyCallGraph::SCC *>(IR)) {
1139           const Module *M;
1140           if (any_isa<const LazyCallGraph::SCC *>(IR))
1141             M = any_cast<const LazyCallGraph::SCC *>(IR)
1142                     ->begin()
1143                     ->getFunction()
1144                     .getParent();
1145           else
1146             M = any_cast<const Module *>(IR);
1147           if (DebugLogging)
1148             dbgs() << "Verifying module " << M->getName() << "\n";
1149 
1150           if (verifyModule(*M))
1151             report_fatal_error("Broken module found, compilation aborted!");
1152         }
1153       });
1154 }
1155 
1156 InLineChangePrinter::~InLineChangePrinter() {}
1157 
1158 void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID,
1159                                                    ChangedIRData &D) {
1160   ChangedIRComparer::analyzeIR(IR, D);
1161 }
1162 
1163 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
1164                                       const ChangedIRData &Before,
1165                                       const ChangedIRData &After, Any IR) {
1166   if (Name == "")
1167     Name = " (module)";
1168   SmallString<20> Banner =
1169       formatv("*** IR Dump After {0} ***{1}\n", PassID, Name);
1170   Out << Banner;
1171   ChangedIRComparer(Out, Before, After, UseColour)
1172       .compare(IR, "", PassID, Name);
1173   Out << "\n";
1174 }
1175 
1176 bool InLineChangePrinter::same(const ChangedIRData &D1,
1177                                const ChangedIRData &D2) {
1178   return D1 == D2;
1179 }
1180 
1181 void ChangedIRComparer::handleFunctionCompare(StringRef Name, StringRef Prefix,
1182                                               StringRef PassID, bool InModule,
1183                                               const ChangedFuncData &Before,
1184                                               const ChangedFuncData &After) {
1185   // Print a banner when this is being shown in the context of a module
1186   if (InModule)
1187     Out << "\n*** IR for function " << Name << " ***\n";
1188 
1189   ChangedFuncData::report(
1190       Before, After, [&](const ChangedBlockData *B, const ChangedBlockData *A) {
1191         StringRef BStr = B ? B->getBody() : "\n";
1192         StringRef AStr = A ? A->getBody() : "\n";
1193         const std::string Removed =
1194             UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
1195         const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
1196         const std::string NoChange = " %l\n";
1197         Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
1198       });
1199 }
1200 
1201 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
1202   if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1203       PrintChanged == ChangePrinter::PrintChangedDiffQuiet ||
1204       PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1205       PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet)
1206     TextChangeReporter<ChangedIRData>::registerRequiredCallbacks(PIC);
1207 }
1208 
1209 StandardInstrumentations::StandardInstrumentations(bool DebugLogging,
1210                                                    bool VerifyEach)
1211     : PrintPass(DebugLogging), OptNone(DebugLogging),
1212       PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose),
1213       PrintChangedDiff(
1214           PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1215               PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose,
1216           PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1217               PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet),
1218       Verify(DebugLogging), VerifyEach(VerifyEach) {}
1219 
1220 void StandardInstrumentations::registerCallbacks(
1221     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) {
1222   PrintIR.registerCallbacks(PIC);
1223   PrintPass.registerCallbacks(PIC);
1224   TimePasses.registerCallbacks(PIC);
1225   OptNone.registerCallbacks(PIC);
1226   OptBisect.registerCallbacks(PIC);
1227   if (FAM)
1228     PreservedCFGChecker.registerCallbacks(PIC, *FAM);
1229   PrintChangedIR.registerCallbacks(PIC);
1230   PseudoProbeVerification.registerCallbacks(PIC);
1231   if (VerifyEach)
1232     Verify.registerCallbacks(PIC);
1233   PrintChangedDiff.registerCallbacks(PIC);
1234 }
1235 
1236 namespace llvm {
1237 
1238 template class ChangeReporter<std::string>;
1239 template class TextChangeReporter<std::string>;
1240 
1241 template class ChangeReporter<ChangedIRData>;
1242 template class TextChangeReporter<ChangedIRData>;
1243 
1244 } // namespace llvm
1245