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