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 /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
197 /// certain global filters. Will never return nullptr if \p Force is true.
198 const Module *unwrapModule(Any IR, bool Force = false) {
199   if (any_isa<const Module *>(IR))
200     return any_cast<const Module *>(IR);
201 
202   if (any_isa<const Function *>(IR)) {
203     const Function *F = any_cast<const Function *>(IR);
204     if (!Force && !isFunctionInPrintList(F->getName()))
205       return nullptr;
206 
207     return F->getParent();
208   }
209 
210   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
211     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
212     for (const LazyCallGraph::Node &N : *C) {
213       const Function &F = N.getFunction();
214       if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
215         return F.getParent();
216       }
217     }
218     assert(!Force && "Expected a module");
219     return nullptr;
220   }
221 
222   if (any_isa<const Loop *>(IR)) {
223     const Loop *L = any_cast<const Loop *>(IR);
224     const Function *F = L->getHeader()->getParent();
225     if (!Force && !isFunctionInPrintList(F->getName()))
226       return nullptr;
227     return F->getParent();
228   }
229 
230   llvm_unreachable("Unknown IR unit");
231 }
232 
233 void printIR(raw_ostream &OS, const Function *F) {
234   if (!isFunctionInPrintList(F->getName()))
235     return;
236   OS << *F;
237 }
238 
239 void printIR(raw_ostream &OS, const Module *M,
240              bool ShouldPreserveUseListOrder = false) {
241   if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
242     M->print(OS, nullptr, ShouldPreserveUseListOrder);
243   } else {
244     for (const auto &F : M->functions()) {
245       printIR(OS, &F);
246     }
247   }
248 }
249 
250 void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {
251   for (const LazyCallGraph::Node &N : *C) {
252     const Function &F = N.getFunction();
253     if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
254       F.print(OS);
255     }
256   }
257 }
258 
259 void printIR(raw_ostream &OS, const Loop *L) {
260   const Function *F = L->getHeader()->getParent();
261   if (!isFunctionInPrintList(F->getName()))
262     return;
263   printLoop(const_cast<Loop &>(*L), OS);
264 }
265 
266 std::string getIRName(Any IR) {
267   if (any_isa<const Module *>(IR))
268     return "[module]";
269 
270   if (any_isa<const Function *>(IR)) {
271     const Function *F = any_cast<const Function *>(IR);
272     return F->getName().str();
273   }
274 
275   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
276     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
277     return C->getName();
278   }
279 
280   if (any_isa<const Loop *>(IR)) {
281     const Loop *L = any_cast<const Loop *>(IR);
282     std::string S;
283     raw_string_ostream OS(S);
284     L->print(OS, /*Verbose*/ false, /*PrintNested*/ false);
285     return OS.str();
286   }
287 
288   llvm_unreachable("Unknown wrapped IR type");
289 }
290 
291 bool moduleContainsFilterPrintFunc(const Module &M) {
292   return any_of(M.functions(),
293                 [](const Function &F) {
294                   return isFunctionInPrintList(F.getName());
295                 }) ||
296          isFunctionInPrintList("*");
297 }
298 
299 bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
300   return any_of(C,
301                 [](const LazyCallGraph::Node &N) {
302                   return isFunctionInPrintList(N.getName());
303                 }) ||
304          isFunctionInPrintList("*");
305 }
306 
307 bool shouldPrintIR(Any IR) {
308   if (any_isa<const Module *>(IR)) {
309     const Module *M = any_cast<const Module *>(IR);
310     return moduleContainsFilterPrintFunc(*M);
311   }
312 
313   if (any_isa<const Function *>(IR)) {
314     const Function *F = any_cast<const Function *>(IR);
315     return isFunctionInPrintList(F->getName());
316   }
317 
318   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
319     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
320     return sccContainsFilterPrintFunc(*C);
321   }
322 
323   if (any_isa<const Loop *>(IR)) {
324     const Loop *L = any_cast<const Loop *>(IR);
325     return isFunctionInPrintList(L->getHeader()->getParent()->getName());
326   }
327   llvm_unreachable("Unknown wrapped IR type");
328 }
329 
330 /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
331 /// llvm::Any and does actual print job.
332 void unwrapAndPrint(raw_ostream &OS, Any IR,
333                     bool ShouldPreserveUseListOrder = false) {
334   if (!shouldPrintIR(IR))
335     return;
336 
337   if (forcePrintModuleIR()) {
338     auto *M = unwrapModule(IR);
339     assert(M && "should have unwrapped module");
340     printIR(OS, M, ShouldPreserveUseListOrder);
341     return;
342   }
343 
344   if (any_isa<const Module *>(IR)) {
345     const Module *M = any_cast<const Module *>(IR);
346     printIR(OS, M, ShouldPreserveUseListOrder);
347     return;
348   }
349 
350   if (any_isa<const Function *>(IR)) {
351     const Function *F = any_cast<const Function *>(IR);
352     printIR(OS, F);
353     return;
354   }
355 
356   if (any_isa<const LazyCallGraph::SCC *>(IR)) {
357     const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
358     printIR(OS, C);
359     return;
360   }
361 
362   if (any_isa<const Loop *>(IR)) {
363     const Loop *L = any_cast<const Loop *>(IR);
364     printIR(OS, L);
365     return;
366   }
367   llvm_unreachable("Unknown wrapped IR type");
368 }
369 
370 // Return true when this is a pass for which changes should be ignored
371 bool isIgnored(StringRef PassID) {
372   return isSpecialPass(PassID,
373                        {"PassManager", "PassAdaptor", "AnalysisManagerProxy"});
374 }
375 
376 } // namespace
377 
378 template <typename IRUnitT>
379 ChangeReporter<IRUnitT>::~ChangeReporter<IRUnitT>() {
380   assert(BeforeStack.empty() && "Problem with Change Printer stack.");
381 }
382 
383 template <typename IRUnitT>
384 bool ChangeReporter<IRUnitT>::isInterestingFunction(const Function &F) {
385   return isFunctionInPrintList(F.getName());
386 }
387 
388 template <typename IRUnitT>
389 bool ChangeReporter<IRUnitT>::isInterestingPass(StringRef PassID) {
390   if (isIgnored(PassID))
391     return false;
392 
393   static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
394                                                         PrintPassesList.end());
395   return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
396 }
397 
398 // Return true when this is a pass on IR for which printing
399 // of changes is desired.
400 template <typename IRUnitT>
401 bool ChangeReporter<IRUnitT>::isInteresting(Any IR, StringRef PassID) {
402   if (!isInterestingPass(PassID))
403     return false;
404   if (any_isa<const Function *>(IR))
405     return isInterestingFunction(*any_cast<const Function *>(IR));
406   return true;
407 }
408 
409 template <typename IRUnitT>
410 void ChangeReporter<IRUnitT>::saveIRBeforePass(Any IR, StringRef PassID) {
411   // Always need to place something on the stack because invalidated passes
412   // are not given the IR so it cannot be determined whether the pass was for
413   // something that was filtered out.
414   BeforeStack.emplace_back();
415 
416   if (!isInteresting(IR, PassID))
417     return;
418   // Is this the initial IR?
419   if (InitialIR) {
420     InitialIR = false;
421     if (VerboseMode)
422       handleInitialIR(IR);
423   }
424 
425   // Save the IR representation on the stack.
426   IRUnitT &Data = BeforeStack.back();
427   generateIRRepresentation(IR, PassID, Data);
428 }
429 
430 template <typename IRUnitT>
431 void ChangeReporter<IRUnitT>::handleIRAfterPass(Any IR, StringRef PassID) {
432   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
433 
434   std::string Name = getIRName(IR);
435 
436   if (isIgnored(PassID)) {
437     if (VerboseMode)
438       handleIgnored(PassID, Name);
439   } else if (!isInteresting(IR, PassID)) {
440     if (VerboseMode)
441       handleFiltered(PassID, Name);
442   } else {
443     // Get the before rep from the stack
444     IRUnitT &Before = BeforeStack.back();
445     // Create the after rep
446     IRUnitT After;
447     generateIRRepresentation(IR, PassID, After);
448 
449     // Was there a change in IR?
450     if (same(Before, After)) {
451       if (VerboseMode)
452         omitAfter(PassID, Name);
453     } else
454       handleAfter(PassID, Name, Before, After, IR);
455   }
456   BeforeStack.pop_back();
457 }
458 
459 template <typename IRUnitT>
460 void ChangeReporter<IRUnitT>::handleInvalidatedPass(StringRef PassID) {
461   assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
462 
463   // Always flag it as invalidated as we cannot determine when
464   // a pass for a filtered function is invalidated since we do not
465   // get the IR in the call.  Also, the output is just alternate
466   // forms of the banner anyway.
467   if (VerboseMode)
468     handleInvalidated(PassID);
469   BeforeStack.pop_back();
470 }
471 
472 template <typename IRUnitT>
473 void ChangeReporter<IRUnitT>::registerRequiredCallbacks(
474     PassInstrumentationCallbacks &PIC) {
475   PIC.registerBeforeNonSkippedPassCallback(
476       [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
477 
478   PIC.registerAfterPassCallback(
479       [this](StringRef P, Any IR, const PreservedAnalyses &) {
480         handleIRAfterPass(IR, P);
481       });
482   PIC.registerAfterPassInvalidatedCallback(
483       [this](StringRef P, const PreservedAnalyses &) {
484         handleInvalidatedPass(P);
485       });
486 }
487 
488 ChangedBlockData::ChangedBlockData(const BasicBlock &B)
489     : Label(B.getName().str()) {
490   raw_string_ostream SS(Body);
491   B.print(SS, nullptr, true, true);
492 }
493 
494 template <typename IRUnitT>
495 TextChangeReporter<IRUnitT>::TextChangeReporter(bool Verbose)
496     : ChangeReporter<IRUnitT>(Verbose), Out(dbgs()) {}
497 
498 template <typename IRUnitT>
499 void TextChangeReporter<IRUnitT>::handleInitialIR(Any IR) {
500   // Always print the module.
501   // Unwrap and print directly to avoid filtering problems in general routines.
502   auto *M = unwrapModule(IR, /*Force=*/true);
503   assert(M && "Expected module to be unwrapped when forced.");
504   Out << "*** IR Dump At Start ***\n";
505   M->print(Out, nullptr,
506            /*ShouldPreserveUseListOrder=*/true);
507 }
508 
509 template <typename IRUnitT>
510 void TextChangeReporter<IRUnitT>::omitAfter(StringRef PassID,
511                                             std::string &Name) {
512   Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
513                  PassID, Name);
514 }
515 
516 template <typename IRUnitT>
517 void TextChangeReporter<IRUnitT>::handleInvalidated(StringRef PassID) {
518   Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
519 }
520 
521 template <typename IRUnitT>
522 void TextChangeReporter<IRUnitT>::handleFiltered(StringRef PassID,
523                                                  std::string &Name) {
524   SmallString<20> Banner =
525       formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);
526   Out << Banner;
527 }
528 
529 template <typename IRUnitT>
530 void TextChangeReporter<IRUnitT>::handleIgnored(StringRef PassID,
531                                                 std::string &Name) {
532   Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);
533 }
534 
535 IRChangedPrinter::~IRChangedPrinter() {}
536 
537 void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
538   if (PrintChanged == ChangePrinter::PrintChangedVerbose ||
539       PrintChanged == ChangePrinter::PrintChangedQuiet)
540     TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
541 }
542 
543 void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
544                                                 std::string &Output) {
545   raw_string_ostream OS(Output);
546   unwrapAndPrint(OS, IR,
547                  /*ShouldPreserveUseListOrder=*/true);
548   OS.str();
549 }
550 
551 void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
552                                    const std::string &Before,
553                                    const std::string &After, Any) {
554   // Report the IR before the changes when requested.
555   if (PrintChangedBefore)
556     Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
557         << Before;
558 
559   // We might not get anything to print if we only want to print a specific
560   // function but it gets deleted.
561   if (After.empty()) {
562     Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";
563     return;
564   }
565 
566   Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;
567 }
568 
569 bool IRChangedPrinter::same(const std::string &S1, const std::string &S2) {
570   return S1 == S2;
571 }
572 
573 template <typename IRData>
574 void OrderedChangedData<IRData>::report(
575     const OrderedChangedData &Before, const OrderedChangedData &After,
576     function_ref<void(const IRData *, const IRData *)> HandlePair) {
577   const auto &BFD = Before.getData();
578   const auto &AFD = After.getData();
579   std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
580   std::vector<std::string>::const_iterator BE = Before.getOrder().end();
581   std::vector<std::string>::const_iterator AI = After.getOrder().begin();
582   std::vector<std::string>::const_iterator AE = After.getOrder().end();
583 
584   auto handlePotentiallyRemovedIRData = [&](std::string S) {
585     // The order in LLVM may have changed so check if still exists.
586     if (!AFD.count(S)) {
587       // This has been removed.
588       HandlePair(&BFD.find(*BI)->getValue(), nullptr);
589     }
590   };
591   auto handleNewIRData = [&](std::vector<const IRData *> &Q) {
592     // Print out any queued up new sections
593     for (const IRData *NBI : Q)
594       HandlePair(nullptr, NBI);
595     Q.clear();
596   };
597 
598   // Print out the IRData in the after order, with before ones interspersed
599   // appropriately (ie, somewhere near where they were in the before list).
600   // Start at the beginning of both lists.  Loop through the
601   // after list.  If an element is common, then advance in the before list
602   // reporting the removed ones until the common one is reached.  Report any
603   // queued up new ones and then report the common one.  If an element is not
604   // common, then enqueue it for reporting.  When the after list is exhausted,
605   // loop through the before list, reporting any removed ones.  Finally,
606   // report the rest of the enqueued new ones.
607   std::vector<const IRData *> NewIRDataQueue;
608   while (AI != AE) {
609     if (!BFD.count(*AI)) {
610       // This section is new so place it in the queue.  This will cause it
611       // to be reported after deleted sections.
612       NewIRDataQueue.emplace_back(&AFD.find(*AI)->getValue());
613       ++AI;
614       continue;
615     }
616     // This section is in both; advance and print out any before-only
617     // until we get to it.
618     while (*BI != *AI) {
619       handlePotentiallyRemovedIRData(*BI);
620       ++BI;
621     }
622     // Report any new sections that were queued up and waiting.
623     handleNewIRData(NewIRDataQueue);
624 
625     const IRData &AData = AFD.find(*AI)->getValue();
626     const IRData &BData = BFD.find(*AI)->getValue();
627     HandlePair(&BData, &AData);
628     ++BI;
629     ++AI;
630   }
631 
632   // Check any remaining before sections to see if they have been removed
633   while (BI != BE) {
634     handlePotentiallyRemovedIRData(*BI);
635     ++BI;
636   }
637 
638   handleNewIRData(NewIRDataQueue);
639 }
640 
641 void ChangedIRComparer::compare(Any IR, StringRef Prefix, StringRef PassID,
642                                 StringRef Name) {
643   if (!getModuleForComparison(IR)) {
644     // Not a module so just handle the single function.
645     assert(Before.getData().size() == 1 && "Expected only one function.");
646     assert(After.getData().size() == 1 && "Expected only one function.");
647     handleFunctionCompare(Name, Prefix, PassID, false,
648                           Before.getData().begin()->getValue(),
649                           After.getData().begin()->getValue());
650     return;
651   }
652 
653   ChangedIRData::report(
654       Before, After, [&](const ChangedFuncData *B, const ChangedFuncData *A) {
655         ChangedFuncData Missing;
656         if (!B)
657           B = &Missing;
658         else if (!A)
659           A = &Missing;
660         assert(B != &Missing && A != &Missing &&
661                "Both functions cannot be missing.");
662         handleFunctionCompare(Name, Prefix, PassID, true, *B, *A);
663       });
664 }
665 
666 void ChangedIRComparer::analyzeIR(Any IR, ChangedIRData &Data) {
667   if (const Module *M = getModuleForComparison(IR)) {
668     // Create data for each existing/interesting function in the module.
669     for (const Function &F : *M)
670       generateFunctionData(Data, F);
671     return;
672   }
673 
674   const Function *F = nullptr;
675   if (any_isa<const Function *>(IR))
676     F = any_cast<const Function *>(IR);
677   else {
678     assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
679     const Loop *L = any_cast<const Loop *>(IR);
680     F = L->getHeader()->getParent();
681   }
682   assert(F && "Unknown IR unit.");
683   generateFunctionData(Data, *F);
684 }
685 
686 const Module *ChangedIRComparer::getModuleForComparison(Any IR) {
687   if (any_isa<const Module *>(IR))
688     return any_cast<const Module *>(IR);
689   if (any_isa<const LazyCallGraph::SCC *>(IR))
690     return any_cast<const LazyCallGraph::SCC *>(IR)
691         ->begin()
692         ->getFunction()
693         .getParent();
694   return nullptr;
695 }
696 
697 bool ChangedIRComparer::generateFunctionData(ChangedIRData &Data,
698                                              const Function &F) {
699   if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
700     ChangedFuncData CFD;
701     for (const auto &B : F) {
702       CFD.getOrder().emplace_back(B.getName());
703       CFD.getData().insert({B.getName(), B});
704     }
705     Data.getOrder().emplace_back(F.getName());
706     Data.getData().insert({F.getName(), CFD});
707     return true;
708   }
709   return false;
710 }
711 
712 PrintIRInstrumentation::~PrintIRInstrumentation() {
713   assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
714 }
715 
716 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
717   assert(StoreModuleDesc);
718   const Module *M = unwrapModule(IR);
719   ModuleDescStack.emplace_back(M, getIRName(IR), PassID);
720 }
721 
722 PrintIRInstrumentation::PrintModuleDesc
723 PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
724   assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
725   PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
726   assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
727   return ModuleDesc;
728 }
729 
730 void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
731   if (isIgnored(PassID))
732     return;
733 
734   // Saving Module for AfterPassInvalidated operations.
735   // Note: here we rely on a fact that we do not change modules while
736   // traversing the pipeline, so the latest captured module is good
737   // for all print operations that has not happen yet.
738   if (StoreModuleDesc && shouldPrintAfterPass(PassID))
739     pushModuleDesc(PassID, IR);
740 
741   if (!shouldPrintBeforePass(PassID))
742     return;
743 
744   if (!shouldPrintIR(IR))
745     return;
746 
747   dbgs() << "*** IR Dump Before " << PassID << " on " << getIRName(IR)
748          << " ***\n";
749   unwrapAndPrint(dbgs(), IR);
750 }
751 
752 void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
753   if (isIgnored(PassID))
754     return;
755 
756   if (!shouldPrintAfterPass(PassID))
757     return;
758 
759   if (StoreModuleDesc) {
760     const Module *M;
761     std::string IRName;
762     StringRef StoredPassID;
763     std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
764     assert(StoredPassID == PassID && "mismatched PassID");
765   }
766 
767   if (!shouldPrintIR(IR))
768     return;
769 
770   dbgs() << "*** IR Dump After " << PassID << " on " << getIRName(IR)
771          << " ***\n";
772   unwrapAndPrint(dbgs(), IR);
773 }
774 
775 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
776   StringRef PassName = PIC->getPassNameForClassName(PassID);
777   if (!StoreModuleDesc || !shouldPrintAfterPass(PassName))
778     return;
779 
780   if (isIgnored(PassID))
781     return;
782 
783   const Module *M;
784   std::string IRName;
785   StringRef StoredPassID;
786   std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
787   assert(StoredPassID == PassID && "mismatched PassID");
788   // Additional filtering (e.g. -filter-print-func) can lead to module
789   // printing being skipped.
790   if (!M)
791     return;
792 
793   SmallString<20> Banner =
794       formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID, IRName);
795   dbgs() << Banner << "\n";
796   printIR(dbgs(), M);
797 }
798 
799 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
800   if (shouldPrintBeforeAll())
801     return true;
802 
803   StringRef PassName = PIC->getPassNameForClassName(PassID);
804   return llvm::is_contained(printBeforePasses(), PassName);
805 }
806 
807 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
808   if (shouldPrintAfterAll())
809     return true;
810 
811   StringRef PassName = PIC->getPassNameForClassName(PassID);
812   return llvm::is_contained(printAfterPasses(), PassName);
813 }
814 
815 void PrintIRInstrumentation::registerCallbacks(
816     PassInstrumentationCallbacks &PIC) {
817   this->PIC = &PIC;
818 
819   // BeforePass callback is not just for printing, it also saves a Module
820   // for later use in AfterPassInvalidated.
821   StoreModuleDesc = forcePrintModuleIR() && shouldPrintAfterSomePass();
822   if (shouldPrintBeforeSomePass() || StoreModuleDesc)
823     PIC.registerBeforeNonSkippedPassCallback(
824         [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
825 
826   if (shouldPrintAfterSomePass()) {
827     PIC.registerAfterPassCallback(
828         [this](StringRef P, Any IR, const PreservedAnalyses &) {
829           this->printAfterPass(P, IR);
830         });
831     PIC.registerAfterPassInvalidatedCallback(
832         [this](StringRef P, const PreservedAnalyses &) {
833           this->printAfterPassInvalidated(P);
834         });
835   }
836 }
837 
838 void OptNoneInstrumentation::registerCallbacks(
839     PassInstrumentationCallbacks &PIC) {
840   PIC.registerShouldRunOptionalPassCallback(
841       [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
842 }
843 
844 bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
845   const Function *F = nullptr;
846   if (any_isa<const Function *>(IR)) {
847     F = any_cast<const Function *>(IR);
848   } else if (any_isa<const Loop *>(IR)) {
849     F = any_cast<const Loop *>(IR)->getHeader()->getParent();
850   }
851   bool ShouldRun = !(F && F->hasOptNone());
852   if (!ShouldRun && DebugLogging) {
853     errs() << "Skipping pass " << PassID << " on " << F->getName()
854            << " due to optnone attribute\n";
855   }
856   return ShouldRun;
857 }
858 
859 void OptBisectInstrumentation::registerCallbacks(
860     PassInstrumentationCallbacks &PIC) {
861   if (!OptBisector->isEnabled())
862     return;
863   PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
864     return isIgnored(PassID) || OptBisector->checkPass(PassID, getIRName(IR));
865   });
866 }
867 
868 void PrintPassInstrumentation::registerCallbacks(
869     PassInstrumentationCallbacks &PIC) {
870   if (!DebugLogging)
871     return;
872 
873   std::vector<StringRef> SpecialPasses = {"PassManager"};
874   if (!DebugPMVerbose)
875     SpecialPasses.emplace_back("PassAdaptor");
876 
877   PIC.registerBeforeSkippedPassCallback(
878       [SpecialPasses](StringRef PassID, Any IR) {
879         assert(!isSpecialPass(PassID, SpecialPasses) &&
880                "Unexpectedly skipping special pass");
881 
882         dbgs() << "Skipping pass: " << PassID << " on " << getIRName(IR)
883                << "\n";
884       });
885 
886   PIC.registerBeforeNonSkippedPassCallback(
887       [SpecialPasses](StringRef PassID, Any IR) {
888         if (isSpecialPass(PassID, SpecialPasses))
889           return;
890 
891         dbgs() << "Running pass: " << PassID << " on " << getIRName(IR) << "\n";
892       });
893 
894   PIC.registerBeforeAnalysisCallback([](StringRef PassID, Any IR) {
895     dbgs() << "Running analysis: " << PassID << " on " << getIRName(IR) << "\n";
896   });
897 }
898 
899 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
900                                              bool TrackBBLifetime) {
901   if (TrackBBLifetime)
902     BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
903   for (const auto &BB : *F) {
904     if (BBGuards)
905       BBGuards->try_emplace(intptr_t(&BB), &BB);
906     for (auto *Succ : successors(&BB)) {
907       Graph[&BB][Succ]++;
908       if (BBGuards)
909         BBGuards->try_emplace(intptr_t(Succ), Succ);
910     }
911   }
912 }
913 
914 static void printBBName(raw_ostream &out, const BasicBlock *BB) {
915   if (BB->hasName()) {
916     out << BB->getName() << "<" << BB << ">";
917     return;
918   }
919 
920   if (!BB->getParent()) {
921     out << "unnamed_removed<" << BB << ">";
922     return;
923   }
924 
925   if (BB == &BB->getParent()->getEntryBlock()) {
926     out << "entry"
927         << "<" << BB << ">";
928     return;
929   }
930 
931   unsigned FuncOrderBlockNum = 0;
932   for (auto &FuncBB : *BB->getParent()) {
933     if (&FuncBB == BB)
934       break;
935     FuncOrderBlockNum++;
936   }
937   out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
938 }
939 
940 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out,
941                                                         const CFG &Before,
942                                                         const CFG &After) {
943   assert(!After.isPoisoned());
944   if (Before.isPoisoned()) {
945     out << "Some blocks were deleted\n";
946     return;
947   }
948 
949   // Find and print graph differences.
950   if (Before.Graph.size() != After.Graph.size())
951     out << "Different number of non-leaf basic blocks: before="
952         << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
953 
954   for (auto &BB : Before.Graph) {
955     auto BA = After.Graph.find(BB.first);
956     if (BA == After.Graph.end()) {
957       out << "Non-leaf block ";
958       printBBName(out, BB.first);
959       out << " is removed (" << BB.second.size() << " successors)\n";
960     }
961   }
962 
963   for (auto &BA : After.Graph) {
964     auto BB = Before.Graph.find(BA.first);
965     if (BB == Before.Graph.end()) {
966       out << "Non-leaf block ";
967       printBBName(out, BA.first);
968       out << " is added (" << BA.second.size() << " successors)\n";
969       continue;
970     }
971 
972     if (BB->second == BA.second)
973       continue;
974 
975     out << "Different successors of block ";
976     printBBName(out, BA.first);
977     out << " (unordered):\n";
978     out << "- before (" << BB->second.size() << "): ";
979     for (auto &SuccB : BB->second) {
980       printBBName(out, SuccB.first);
981       if (SuccB.second != 1)
982         out << "(" << SuccB.second << "), ";
983       else
984         out << ", ";
985     }
986     out << "\n";
987     out << "- after (" << BA.second.size() << "): ";
988     for (auto &SuccA : BA.second) {
989       printBBName(out, SuccA.first);
990       if (SuccA.second != 1)
991         out << "(" << SuccA.second << "), ";
992       else
993         out << ", ";
994     }
995     out << "\n";
996   }
997 }
998 
999 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1000 // passes, that reported they kept CFG analyses up-to-date, did not actually
1001 // change CFG. This check is done as follows. Before every functional pass in
1002 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1003 // PreservedCFGCheckerInstrumentation::CFG) is requested from
1004 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1005 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1006 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1007 // available) is checked to be equal to a freshly created CFG snapshot.
1008 struct PreservedCFGCheckerAnalysis
1009     : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
1010   friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>;
1011 
1012   static AnalysisKey Key;
1013 
1014 public:
1015   /// Provide the result type for this analysis pass.
1016   using Result = PreservedCFGCheckerInstrumentation::CFG;
1017 
1018   /// Run the analysis pass over a function and produce CFG.
1019   Result run(Function &F, FunctionAnalysisManager &FAM) {
1020     return Result(&F, /* TrackBBLifetime */ true);
1021   }
1022 };
1023 
1024 AnalysisKey PreservedCFGCheckerAnalysis::Key;
1025 
1026 bool PreservedCFGCheckerInstrumentation::CFG::invalidate(
1027     Function &F, const PreservedAnalyses &PA,
1028     FunctionAnalysisManager::Invalidator &) {
1029   auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
1030   return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1031            PAC.preservedSet<CFGAnalyses>());
1032 }
1033 
1034 void PreservedCFGCheckerInstrumentation::registerCallbacks(
1035     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) {
1036   if (!VerifyPreservedCFG)
1037     return;
1038 
1039   FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1040 
1041   auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore,
1042                      const CFG &GraphAfter) {
1043     if (GraphAfter == GraphBefore)
1044       return;
1045 
1046     dbgs() << "Error: " << Pass
1047            << " does not invalidate CFG analyses but CFG changes detected in "
1048               "function @"
1049            << FuncName << ":\n";
1050     CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
1051     report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
1052   };
1053 
1054   PIC.registerBeforeNonSkippedPassCallback(
1055       [this, &FAM](StringRef P, Any IR) {
1056         assert(&PassStack.emplace_back(P));
1057         (void)this;
1058         if (!any_isa<const Function *>(IR))
1059           return;
1060 
1061         const auto *F = any_cast<const Function *>(IR);
1062         // Make sure a fresh CFG snapshot is available before the pass.
1063         FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F));
1064       });
1065 
1066   PIC.registerAfterPassInvalidatedCallback(
1067       [this](StringRef P, const PreservedAnalyses &PassPA) {
1068         assert(PassStack.pop_back_val() == P &&
1069                "Before and After callbacks must correspond");
1070         (void)this;
1071       });
1072 
1073   PIC.registerAfterPassCallback([this, &FAM,
1074                                  checkCFG](StringRef P, Any IR,
1075                                            const PreservedAnalyses &PassPA) {
1076     assert(PassStack.pop_back_val() == P &&
1077            "Before and After callbacks must correspond");
1078     (void)this;
1079 
1080     if (!any_isa<const Function *>(IR))
1081       return;
1082 
1083     if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() &&
1084         !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>())
1085       return;
1086 
1087     const auto *F = any_cast<const Function *>(IR);
1088     if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>(
1089             *const_cast<Function *>(F)))
1090       checkCFG(P, F->getName(), *GraphBefore,
1091                CFG(F, /* TrackBBLifetime */ false));
1092   });
1093 }
1094 
1095 void VerifyInstrumentation::registerCallbacks(
1096     PassInstrumentationCallbacks &PIC) {
1097   PIC.registerAfterPassCallback(
1098       [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1099         if (isIgnored(P) || P == "VerifierPass")
1100           return;
1101         if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) {
1102           const Function *F;
1103           if (any_isa<const Loop *>(IR))
1104             F = any_cast<const Loop *>(IR)->getHeader()->getParent();
1105           else
1106             F = any_cast<const Function *>(IR);
1107           if (DebugLogging)
1108             dbgs() << "Verifying function " << F->getName() << "\n";
1109 
1110           if (verifyFunction(*F))
1111             report_fatal_error("Broken function found, compilation aborted!");
1112         } else if (any_isa<const Module *>(IR) ||
1113                    any_isa<const LazyCallGraph::SCC *>(IR)) {
1114           const Module *M;
1115           if (any_isa<const LazyCallGraph::SCC *>(IR))
1116             M = any_cast<const LazyCallGraph::SCC *>(IR)
1117                     ->begin()
1118                     ->getFunction()
1119                     .getParent();
1120           else
1121             M = any_cast<const Module *>(IR);
1122           if (DebugLogging)
1123             dbgs() << "Verifying module " << M->getName() << "\n";
1124 
1125           if (verifyModule(*M))
1126             report_fatal_error("Broken module found, compilation aborted!");
1127         }
1128       });
1129 }
1130 
1131 InLineChangePrinter::~InLineChangePrinter() {}
1132 
1133 void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID,
1134                                                    ChangedIRData &D) {
1135   ChangedIRComparer::analyzeIR(IR, D);
1136 }
1137 
1138 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name,
1139                                       const ChangedIRData &Before,
1140                                       const ChangedIRData &After, Any IR) {
1141   SmallString<20> Banner =
1142       formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);
1143   Out << Banner;
1144   ChangedIRComparer(Out, Before, After, UseColour)
1145       .compare(IR, "", PassID, Name);
1146   Out << "\n";
1147 }
1148 
1149 bool InLineChangePrinter::same(const ChangedIRData &D1,
1150                                const ChangedIRData &D2) {
1151   return D1 == D2;
1152 }
1153 
1154 void ChangedIRComparer::handleFunctionCompare(StringRef Name, StringRef Prefix,
1155                                               StringRef PassID, bool InModule,
1156                                               const ChangedFuncData &Before,
1157                                               const ChangedFuncData &After) {
1158   // Print a banner when this is being shown in the context of a module
1159   if (InModule)
1160     Out << "\n*** IR for function " << Name << " ***\n";
1161 
1162   ChangedFuncData::report(
1163       Before, After, [&](const ChangedBlockData *B, const ChangedBlockData *A) {
1164         StringRef BStr = B ? B->getBody() : "\n";
1165         StringRef AStr = A ? A->getBody() : "\n";
1166         const std::string Removed =
1167             UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
1168         const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
1169         const std::string NoChange = " %l\n";
1170         Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
1171       });
1172 }
1173 
1174 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
1175   if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1176       PrintChanged == ChangePrinter::PrintChangedDiffQuiet ||
1177       PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1178       PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet)
1179     TextChangeReporter<ChangedIRData>::registerRequiredCallbacks(PIC);
1180 }
1181 
1182 StandardInstrumentations::StandardInstrumentations(bool DebugLogging,
1183                                                    bool VerifyEach)
1184     : PrintPass(DebugLogging), OptNone(DebugLogging),
1185       PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose),
1186       PrintChangedDiff(
1187           PrintChanged == ChangePrinter::PrintChangedDiffVerbose ||
1188               PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose,
1189           PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose ||
1190               PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet),
1191       Verify(DebugLogging), VerifyEach(VerifyEach) {}
1192 
1193 void StandardInstrumentations::registerCallbacks(
1194     PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) {
1195   PrintIR.registerCallbacks(PIC);
1196   PrintPass.registerCallbacks(PIC);
1197   TimePasses.registerCallbacks(PIC);
1198   OptNone.registerCallbacks(PIC);
1199   OptBisect.registerCallbacks(PIC);
1200   if (FAM)
1201     PreservedCFGChecker.registerCallbacks(PIC, *FAM);
1202   PrintChangedIR.registerCallbacks(PIC);
1203   PseudoProbeVerification.registerCallbacks(PIC);
1204   if (VerifyEach)
1205     Verify.registerCallbacks(PIC);
1206   PrintChangedDiff.registerCallbacks(PIC);
1207 }
1208 
1209 namespace llvm {
1210 
1211 template class ChangeReporter<std::string>;
1212 template class TextChangeReporter<std::string>;
1213 
1214 template class ChangeReporter<ChangedIRData>;
1215 template class TextChangeReporter<ChangedIRData>;
1216 
1217 } // namespace llvm
1218