LLVM 20.0.0git
StandardInstrumentations.cpp
Go to the documentation of this file.
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
16#include "llvm/ADT/Any.h"
18#include "llvm/ADT/StringRef.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/Module.h"
31#include "llvm/IR/PassManager.h"
32#include "llvm/IR/PrintPasses.h"
34#include "llvm/IR/Verifier.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/Error.h"
42#include "llvm/Support/Path.h"
44#include "llvm/Support/Regex.h"
47#include <unordered_map>
48#include <unordered_set>
49#include <utility>
50#include <vector>
51
52using namespace llvm;
53
54static cl::opt<bool> VerifyAnalysisInvalidation("verify-analysis-invalidation",
56#ifdef EXPENSIVE_CHECKS
57 cl::init(true)
58#else
59 cl::init(false)
60#endif
61);
62
63// An option that supports the -print-changed option. See
64// the description for -print-changed for an explanation of the use
65// of this option. Note that this option has no effect without -print-changed.
66static cl::opt<bool>
67 PrintChangedBefore("print-before-changed",
68 cl::desc("Print before passes that change them"),
69 cl::init(false), cl::Hidden);
70
71// An option for specifying the dot used by
72// print-changed=[dot-cfg | dot-cfg-quiet]
74 DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"),
75 cl::desc("system dot used by change reporters"));
76
77// An option that determines the colour used for elements that are only
78// in the before part. Must be a colour named in appendix J of
79// https://graphviz.org/pdf/dotguide.pdf
81 BeforeColour("dot-cfg-before-color",
82 cl::desc("Color for dot-cfg before elements"), cl::Hidden,
83 cl::init("red"));
84// An option that determines the colour used for elements that are only
85// in the after part. Must be a colour named in appendix J of
86// https://graphviz.org/pdf/dotguide.pdf
88 AfterColour("dot-cfg-after-color",
89 cl::desc("Color for dot-cfg after elements"), cl::Hidden,
90 cl::init("forestgreen"));
91// An option that determines the colour used for elements that are in both
92// the before and after parts. Must be a colour named in appendix J of
93// https://graphviz.org/pdf/dotguide.pdf
95 CommonColour("dot-cfg-common-color",
96 cl::desc("Color for dot-cfg common elements"), cl::Hidden,
97 cl::init("black"));
98
99// An option that determines where the generated website file (named
100// passes.html) and the associated pdf files (named diff_*.pdf) are saved.
102 "dot-cfg-dir",
103 cl::desc("Generate dot files into specified directory for changed IRs"),
104 cl::Hidden, cl::init("./"));
105
106// Options to print the IR that was being processed when a pass crashes.
108 "print-on-crash-path",
109 cl::desc("Print the last form of the IR before crash to a file"),
110 cl::Hidden);
111
113 "print-on-crash",
114 cl::desc("Print the last form of the IR before crash (use -print-on-crash-path to dump to a file)"),
115 cl::Hidden);
116
118 "opt-bisect-print-ir-path",
119 cl::desc("Print IR to path when opt-bisect-limit is reached"), cl::Hidden);
120
122 "print-pass-numbers", cl::init(false), cl::Hidden,
123 cl::desc("Print pass names and their ordinals"));
124
126 "print-before-pass-number", cl::init(0), cl::Hidden,
127 cl::desc("Print IR before the pass with this number as "
128 "reported by print-pass-numbers"));
129
131 PrintAfterPassNumber("print-after-pass-number", cl::init(0), cl::Hidden,
132 cl::desc("Print IR after the pass with this number as "
133 "reported by print-pass-numbers"));
134
136 "ir-dump-directory",
137 cl::desc("If specified, IR printed using the "
138 "-print-[before|after]{-all} options will be dumped into "
139 "files in this directory rather than written to stderr"),
140 cl::Hidden, cl::value_desc("filename"));
141
142template <typename IRUnitT> static const IRUnitT *unwrapIR(Any IR) {
143 const IRUnitT **IRPtr = llvm::any_cast<const IRUnitT *>(&IR);
144 return IRPtr ? *IRPtr : nullptr;
145}
146
147namespace {
148
149// An option for specifying an executable that will be called with the IR
150// everytime it changes in the opt pipeline. It will also be called on
151// the initial IR as it enters the pipeline. The executable will be passed
152// the name of a temporary file containing the IR and the PassID. This may
153// be used, for example, to call llc on the IR and run a test to determine
154// which pass makes a change that changes the functioning of the IR.
155// The usual modifier options work as expected.
157 TestChanged("exec-on-ir-change", cl::Hidden, cl::init(""),
158 cl::desc("exe called with module IR after each pass that "
159 "changes it"));
160
161/// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
162/// certain global filters. Will never return nullptr if \p Force is true.
163const Module *unwrapModule(Any IR, bool Force = false) {
164 if (const auto *M = unwrapIR<Module>(IR))
165 return M;
166
167 if (const auto *F = unwrapIR<Function>(IR)) {
168 if (!Force && !isFunctionInPrintList(F->getName()))
169 return nullptr;
170
171 return F->getParent();
172 }
173
174 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
175 for (const LazyCallGraph::Node &N : *C) {
176 const Function &F = N.getFunction();
177 if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
178 return F.getParent();
179 }
180 }
181 assert(!Force && "Expected a module");
182 return nullptr;
183 }
184
185 if (const auto *L = unwrapIR<Loop>(IR)) {
186 const Function *F = L->getHeader()->getParent();
187 if (!Force && !isFunctionInPrintList(F->getName()))
188 return nullptr;
189 return F->getParent();
190 }
191
192 if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
193 if (!Force && !isFunctionInPrintList(MF->getName()))
194 return nullptr;
195 return MF->getFunction().getParent();
196 }
197
198 llvm_unreachable("Unknown IR unit");
199}
200
201void printIR(raw_ostream &OS, const Function *F) {
202 if (!isFunctionInPrintList(F->getName()))
203 return;
204 OS << *F;
205}
207void printIR(raw_ostream &OS, const Module *M) {
209 M->print(OS, nullptr);
210 } else {
211 for (const auto &F : M->functions()) {
212 printIR(OS, &F);
213 }
215}
216
217void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {
218 for (const LazyCallGraph::Node &N : *C) {
219 const Function &F = N.getFunction();
220 if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
221 F.print(OS);
222 }
223 }
224}
225
226void printIR(raw_ostream &OS, const Loop *L) {
227 const Function *F = L->getHeader()->getParent();
228 if (!isFunctionInPrintList(F->getName()))
229 return;
230 printLoop(const_cast<Loop &>(*L), OS);
231}
232
233void printIR(raw_ostream &OS, const MachineFunction *MF) {
234 if (!isFunctionInPrintList(MF->getName()))
235 return;
236 MF->print(OS);
237}
238
239std::string getIRName(Any IR, bool demangled = false) {
240 if (unwrapIR<Module>(IR))
241 return "[module]";
242
243 if (const auto *F = unwrapIR<Function>(IR))
244 return demangled ? demangle(F->getName()) : F->getName().str();
245
246 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
247 return C->getName();
249 if (const auto *L = unwrapIR<Loop>(IR))
250 return "loop %" + L->getName().str() + " in function " +
251 L->getHeader()->getParent()->getName().str();
252
253 if (const auto *MF = unwrapIR<MachineFunction>(IR))
254 return demangled ? demangle(MF->getName()) : MF->getName().str();
256 llvm_unreachable("Unknown wrapped IR type");
258
259bool moduleContainsFilterPrintFunc(const Module &M) {
260 return any_of(M.functions(),
261 [](const Function &F) {
262 return isFunctionInPrintList(F.getName());
263 }) ||
265}
266
267bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
268 return any_of(C,
269 [](const LazyCallGraph::Node &N) {
270 return isFunctionInPrintList(N.getName());
271 }) ||
273}
274
275bool shouldPrintIR(Any IR) {
276 if (const auto *M = unwrapIR<Module>(IR))
277 return moduleContainsFilterPrintFunc(*M);
278
279 if (const auto *F = unwrapIR<Function>(IR))
280 return isFunctionInPrintList(F->getName());
281
282 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
283 return sccContainsFilterPrintFunc(*C);
284
285 if (const auto *L = unwrapIR<Loop>(IR))
286 return isFunctionInPrintList(L->getHeader()->getParent()->getName());
287
288 if (const auto *MF = unwrapIR<MachineFunction>(IR))
289 return isFunctionInPrintList(MF->getName());
290 llvm_unreachable("Unknown wrapped IR type");
291}
292
293/// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
294/// Any and does actual print job.
295void unwrapAndPrint(raw_ostream &OS, Any IR) {
296 if (!shouldPrintIR(IR))
297 return;
298
299 if (forcePrintModuleIR()) {
300 auto *M = unwrapModule(IR);
301 assert(M && "should have unwrapped module");
302 printIR(OS, M);
303 return;
304 }
305
306 if (const auto *M = unwrapIR<Module>(IR)) {
307 printIR(OS, M);
308 return;
309 }
310
311 if (const auto *F = unwrapIR<Function>(IR)) {
312 printIR(OS, F);
313 return;
314 }
315
316 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
317 printIR(OS, C);
318 return;
319 }
320
321 if (const auto *L = unwrapIR<Loop>(IR)) {
322 printIR(OS, L);
323 return;
324 }
325
326 if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
327 printIR(OS, MF);
328 return;
329 }
330 llvm_unreachable("Unknown wrapped IR type");
331}
332
333// Return true when this is a pass for which changes should be ignored
334bool isIgnored(StringRef PassID) {
335 return isSpecialPass(PassID,
336 {"PassManager", "PassAdaptor", "AnalysisManagerProxy",
337 "DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass",
338 "VerifierPass", "PrintModulePass", "PrintMIRPass",
339 "PrintMIRPreparePass"});
340}
341
342std::string makeHTMLReady(StringRef SR) {
343 std::string S;
344 while (true) {
345 StringRef Clean =
346 SR.take_until([](char C) { return C == '<' || C == '>'; });
347 S.append(Clean.str());
348 SR = SR.drop_front(Clean.size());
349 if (SR.size() == 0)
350 return S;
351 S.append(SR[0] == '<' ? "&lt;" : "&gt;");
352 SR = SR.drop_front();
353 }
354 llvm_unreachable("problems converting string to HTML");
355}
356
357// Return the module when that is the appropriate level of comparison for \p IR.
358const Module *getModuleForComparison(Any IR) {
359 if (const auto *M = unwrapIR<Module>(IR))
360 return M;
361 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
362 return C->begin()->getFunction().getParent();
363 return nullptr;
364}
366bool isInterestingFunction(const Function &F) {
367 return isFunctionInPrintList(F.getName());
368}
369
370// Return true when this is a pass on IR for which printing
371// of changes is desired.
373 if (isIgnored(PassID) || !isPassInPrintList(PassName))
374 return false;
375 if (const auto *F = unwrapIR<Function>(IR))
376 return isInterestingFunction(*F);
377 return true;
378}
379
380} // namespace
381
382template <typename T> ChangeReporter<T>::~ChangeReporter() {
383 assert(BeforeStack.empty() && "Problem with Change Printer stack.");
384}
385
386template <typename T>
389 // Is this the initial IR?
390 if (InitialIR) {
391 InitialIR = false;
392 if (VerboseMode)
393 handleInitialIR(IR);
394 }
395
396 // Always need to place something on the stack because invalidated passes
397 // are not given the IR so it cannot be determined whether the pass was for
398 // something that was filtered out.
399 BeforeStack.emplace_back();
400
401 if (!isInteresting(IR, PassID, PassName))
402 return;
403
404 // Save the IR representation on the stack.
405 T &Data = BeforeStack.back();
406 generateIRRepresentation(IR, PassID, Data);
407}
408
409template <typename T>
412 assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
413
414 std::string Name = getIRName(IR);
415
416 if (isIgnored(PassID)) {
417 if (VerboseMode)
418 handleIgnored(PassID, Name);
419 } else if (!isInteresting(IR, PassID, PassName)) {
420 if (VerboseMode)
421 handleFiltered(PassID, Name);
422 } else {
423 // Get the before rep from the stack
424 T &Before = BeforeStack.back();
425 // Create the after rep
426 T After;
427 generateIRRepresentation(IR, PassID, After);
428
429 // Was there a change in IR?
430 if (Before == After) {
431 if (VerboseMode)
432 omitAfter(PassID, Name);
433 } else
434 handleAfter(PassID, Name, Before, After, IR);
435 }
436 BeforeStack.pop_back();
437}
438
439template <typename T>
441 assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
442
443 // Always flag it as invalidated as we cannot determine when
444 // a pass for a filtered function is invalidated since we do not
445 // get the IR in the call. Also, the output is just alternate
446 // forms of the banner anyway.
447 if (VerboseMode)
448 handleInvalidated(PassID);
449 BeforeStack.pop_back();
450}
451
452template <typename T>
456 saveIRBeforePass(IR, P, PIC.getPassNameForClassName(P));
457 });
458
460 [&PIC, this](StringRef P, Any IR, const PreservedAnalyses &) {
461 handleIRAfterPass(IR, P, PIC.getPassNameForClassName(P));
462 });
464 [this](StringRef P, const PreservedAnalyses &) {
465 handleInvalidatedPass(P);
466 });
467}
468
469template <typename T>
471 : ChangeReporter<T>(Verbose), Out(dbgs()) {}
472
473template <typename T> void TextChangeReporter<T>::handleInitialIR(Any IR) {
474 // Always print the module.
475 // Unwrap and print directly to avoid filtering problems in general routines.
476 auto *M = unwrapModule(IR, /*Force=*/true);
477 assert(M && "Expected module to be unwrapped when forced.");
478 Out << "*** IR Dump At Start ***\n";
479 M->print(Out, nullptr);
480}
481
482template <typename T>
484 Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
485 PassID, Name);
486}
487
488template <typename T>
490 Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
491}
492
493template <typename T>
495 std::string &Name) {
496 SmallString<20> Banner =
497 formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);
498 Out << Banner;
499}
500
501template <typename T>
503 Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);
504}
505
507
512}
513
515 std::string &Output) {
516 raw_string_ostream OS(Output);
517 unwrapAndPrint(OS, IR);
518 OS.str();
519}
520
522 const std::string &Before,
523 const std::string &After, Any) {
524 // Report the IR before the changes when requested.
526 Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
527 << Before;
528
529 // We might not get anything to print if we only want to print a specific
530 // function but it gets deleted.
531 if (After.empty()) {
532 Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";
533 return;
534 }
535
536 Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;
537}
538
540
542 if (TestChanged != "")
544}
545
546void IRChangedTester::handleIR(const std::string &S, StringRef PassID) {
547 // Store the body into a temporary file
548 static SmallVector<int> FD{-1};
550 static SmallVector<std::string> FileName{""};
551 if (prepareTempFiles(FD, SR, FileName)) {
552 dbgs() << "Unable to create temporary file.";
553 return;
554 }
555 static ErrorOr<std::string> Exe = sys::findProgramByName(TestChanged);
556 if (!Exe) {
557 dbgs() << "Unable to find test-changed executable.";
558 return;
559 }
560
561 StringRef Args[] = {TestChanged, FileName[0], PassID};
562 int Result = sys::ExecuteAndWait(*Exe, Args);
563 if (Result < 0) {
564 dbgs() << "Error executing test-changed executable.";
565 return;
566 }
567
568 if (cleanUpTempFiles(FileName))
569 dbgs() << "Unable to remove temporary file.";
570}
571
573 // Always test the initial module.
574 // Unwrap and print directly to avoid filtering problems in general routines.
575 std::string S;
576 generateIRRepresentation(IR, "Initial IR", S);
577 handleIR(S, "Initial IR");
578}
579
580void IRChangedTester::omitAfter(StringRef PassID, std::string &Name) {}
582void IRChangedTester::handleFiltered(StringRef PassID, std::string &Name) {}
583void IRChangedTester::handleIgnored(StringRef PassID, std::string &Name) {}
585 const std::string &Before,
586 const std::string &After, Any) {
587 handleIR(After, PassID);
588}
589
590template <typename T>
593 function_ref<void(const T *, const T *)> HandlePair) {
594 const auto &BFD = Before.getData();
595 const auto &AFD = After.getData();
596 std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
597 std::vector<std::string>::const_iterator BE = Before.getOrder().end();
598 std::vector<std::string>::const_iterator AI = After.getOrder().begin();
599 std::vector<std::string>::const_iterator AE = After.getOrder().end();
600
601 auto HandlePotentiallyRemovedData = [&](std::string S) {
602 // The order in LLVM may have changed so check if still exists.
603 if (!AFD.count(S)) {
604 // This has been removed.
605 HandlePair(&BFD.find(*BI)->getValue(), nullptr);
606 }
607 };
608 auto HandleNewData = [&](std::vector<const T *> &Q) {
609 // Print out any queued up new sections
610 for (const T *NBI : Q)
611 HandlePair(nullptr, NBI);
612 Q.clear();
613 };
614
615 // Print out the data in the after order, with before ones interspersed
616 // appropriately (ie, somewhere near where they were in the before list).
617 // Start at the beginning of both lists. Loop through the
618 // after list. If an element is common, then advance in the before list
619 // reporting the removed ones until the common one is reached. Report any
620 // queued up new ones and then report the common one. If an element is not
621 // common, then enqueue it for reporting. When the after list is exhausted,
622 // loop through the before list, reporting any removed ones. Finally,
623 // report the rest of the enqueued new ones.
624 std::vector<const T *> NewDataQueue;
625 while (AI != AE) {
626 if (!BFD.count(*AI)) {
627 // This section is new so place it in the queue. This will cause it
628 // to be reported after deleted sections.
629 NewDataQueue.emplace_back(&AFD.find(*AI)->getValue());
630 ++AI;
631 continue;
632 }
633 // This section is in both; advance and print out any before-only
634 // until we get to it.
635 // It's possible that this section has moved to be later than before. This
636 // will mess up printing most blocks side by side, but it's a rare case and
637 // it's better than crashing.
638 while (BI != BE && *BI != *AI) {
639 HandlePotentiallyRemovedData(*BI);
640 ++BI;
641 }
642 // Report any new sections that were queued up and waiting.
643 HandleNewData(NewDataQueue);
644
645 const T &AData = AFD.find(*AI)->getValue();
646 const T &BData = BFD.find(*AI)->getValue();
647 HandlePair(&BData, &AData);
648 if (BI != BE)
649 ++BI;
650 ++AI;
651 }
652
653 // Check any remaining before sections to see if they have been removed
654 while (BI != BE) {
655 HandlePotentiallyRemovedData(*BI);
656 ++BI;
657 }
658
659 HandleNewData(NewDataQueue);
660}
661
662template <typename T>
664 bool CompareModule,
665 std::function<void(bool InModule, unsigned Minor,
666 const FuncDataT<T> &Before, const FuncDataT<T> &After)>
667 CompareFunc) {
668 if (!CompareModule) {
669 // Just handle the single function.
670 assert(Before.getData().size() == 1 && After.getData().size() == 1 &&
671 "Expected only one function.");
672 CompareFunc(false, 0, Before.getData().begin()->getValue(),
673 After.getData().begin()->getValue());
674 return;
675 }
676
677 unsigned Minor = 0;
678 FuncDataT<T> Missing("");
680 [&](const FuncDataT<T> *B, const FuncDataT<T> *A) {
681 assert((B || A) && "Both functions cannot be missing.");
682 if (!B)
683 B = &Missing;
684 else if (!A)
685 A = &Missing;
686 CompareFunc(true, Minor++, *B, *A);
687 });
688}
689
690template <typename T> void IRComparer<T>::analyzeIR(Any IR, IRDataT<T> &Data) {
691 if (const Module *M = getModuleForComparison(IR)) {
692 // Create data for each existing/interesting function in the module.
693 for (const Function &F : *M)
694 generateFunctionData(Data, F);
695 return;
696 }
697
698 if (const auto *F = unwrapIR<Function>(IR)) {
699 generateFunctionData(Data, *F);
700 return;
701 }
702
703 if (const auto *L = unwrapIR<Loop>(IR)) {
704 auto *F = L->getHeader()->getParent();
705 generateFunctionData(Data, *F);
706 return;
707 }
708
709 if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
710 generateFunctionData(Data, *MF);
711 return;
712 }
713
714 llvm_unreachable("Unknown IR unit");
715}
716
717static bool shouldGenerateData(const Function &F) {
718 return !F.isDeclaration() && isFunctionInPrintList(F.getName());
719}
720
721static bool shouldGenerateData(const MachineFunction &MF) {
722 return isFunctionInPrintList(MF.getName());
723}
724
725template <typename T>
726template <typename FunctionT>
728 if (shouldGenerateData(F)) {
729 FuncDataT<T> FD(F.front().getName().str());
730 int I = 0;
731 for (const auto &B : F) {
732 std::string BBName = B.getName().str();
733 if (BBName.empty()) {
734 BBName = formatv("{0}", I);
735 ++I;
736 }
737 FD.getOrder().emplace_back(BBName);
738 FD.getData().insert({BBName, B});
739 }
740 Data.getOrder().emplace_back(F.getName());
741 Data.getData().insert({F.getName(), FD});
742 return true;
743 }
744 return false;
745}
746
748 assert(PassRunDescriptorStack.empty() &&
749 "PassRunDescriptorStack is not empty at exit");
750}
751
753 SmallString<32> Result;
754 raw_svector_ostream ResultStream(Result);
755 const Module *M = unwrapModule(IR);
756 stable_hash NameHash = stable_hash_combine_string(M->getName());
757 unsigned int MaxHashWidth = sizeof(stable_hash) * 8 / 4;
758 write_hex(ResultStream, NameHash, HexPrintStyle::Lower, MaxHashWidth);
759 if (unwrapIR<Module>(IR)) {
760 ResultStream << "-module";
761 } else if (const auto *F = unwrapIR<Function>(IR)) {
762 ResultStream << "-function-";
763 stable_hash FunctionNameHash = stable_hash_combine_string(F->getName());
764 write_hex(ResultStream, FunctionNameHash, HexPrintStyle::Lower,
765 MaxHashWidth);
766 } else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
767 ResultStream << "-scc-";
768 stable_hash SCCNameHash = stable_hash_combine_string(C->getName());
769 write_hex(ResultStream, SCCNameHash, HexPrintStyle::Lower, MaxHashWidth);
770 } else if (const auto *L = unwrapIR<Loop>(IR)) {
771 ResultStream << "-loop-";
772 stable_hash LoopNameHash = stable_hash_combine_string(L->getName());
773 write_hex(ResultStream, LoopNameHash, HexPrintStyle::Lower, MaxHashWidth);
774 } else if (const auto *MF = unwrapIR<MachineFunction>(IR)) {
775 ResultStream << "-machine-function-";
776 stable_hash MachineFunctionNameHash =
778 write_hex(ResultStream, MachineFunctionNameHash, HexPrintStyle::Lower,
779 MaxHashWidth);
780 } else {
781 llvm_unreachable("Unknown wrapped IR type");
782 }
783 return Result;
784}
785
786std::string PrintIRInstrumentation::fetchDumpFilename(StringRef PassName,
787 Any IR) {
788 const StringRef RootDirectory = IRDumpDirectory;
789 assert(!RootDirectory.empty() &&
790 "The flag -ir-dump-directory must be passed to dump IR to files");
791 SmallString<128> ResultPath;
792 ResultPath += RootDirectory;
794 raw_svector_ostream FilenameStream(Filename);
795 FilenameStream << CurrentPassNumber;
796 FilenameStream << "-";
797 FilenameStream << getIRFileDisplayName(IR);
798 FilenameStream << "-";
799 FilenameStream << PassName;
800 sys::path::append(ResultPath, Filename);
801 return std::string(ResultPath);
802}
803
805 Before,
806 After,
808};
809
811 static constexpr std::array FileSuffixes = {"-before.ll", "-after.ll",
812 "-invalidated.ll"};
813 return FileSuffixes[static_cast<size_t>(Type)];
814}
815
816void PrintIRInstrumentation::pushPassRunDescriptor(
817 StringRef PassID, Any IR, std::string &DumpIRFilename) {
818 const Module *M = unwrapModule(IR);
819 PassRunDescriptorStack.emplace_back(
820 PassRunDescriptor(M, DumpIRFilename, getIRName(IR), PassID));
821}
822
823PrintIRInstrumentation::PassRunDescriptor
824PrintIRInstrumentation::popPassRunDescriptor(StringRef PassID) {
825 assert(!PassRunDescriptorStack.empty() && "empty PassRunDescriptorStack");
826 PassRunDescriptor Descriptor = PassRunDescriptorStack.pop_back_val();
827 assert(Descriptor.PassID == PassID && "malformed PassRunDescriptorStack");
828 return Descriptor;
829}
830
831// Callers are responsible for closing the returned file descriptor
832static int prepareDumpIRFileDescriptor(const StringRef DumpIRFilename) {
833 std::error_code EC;
834 auto ParentPath = llvm::sys::path::parent_path(DumpIRFilename);
835 if (!ParentPath.empty()) {
836 std::error_code EC = llvm::sys::fs::create_directories(ParentPath);
837 if (EC)
838 report_fatal_error(Twine("Failed to create directory ") + ParentPath +
839 " to support -ir-dump-directory: " + EC.message());
840 }
841 int Result = 0;
842 EC = sys::fs::openFile(DumpIRFilename, Result, sys::fs::CD_OpenAlways,
844 if (EC)
845 report_fatal_error(Twine("Failed to open ") + DumpIRFilename +
846 " to support -ir-dump-directory: " + EC.message());
847 return Result;
848}
849
850void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
851 if (isIgnored(PassID))
852 return;
853
854 std::string DumpIRFilename;
855 if (!IRDumpDirectory.empty() &&
856 (shouldPrintBeforePass(PassID) || shouldPrintAfterPass(PassID) ||
857 shouldPrintBeforeCurrentPassNumber() ||
858 shouldPrintAfterCurrentPassNumber()))
859 DumpIRFilename = fetchDumpFilename(PassID, IR);
860
861 // Saving Module for AfterPassInvalidated operations.
862 // Note: here we rely on a fact that we do not change modules while
863 // traversing the pipeline, so the latest captured module is good
864 // for all print operations that has not happen yet.
865 if (shouldPrintAfterPass(PassID))
866 pushPassRunDescriptor(PassID, IR, DumpIRFilename);
867
868 if (!shouldPrintIR(IR))
869 return;
870
871 ++CurrentPassNumber;
872
873 if (shouldPrintPassNumbers())
874 dbgs() << " Running pass " << CurrentPassNumber << " " << PassID
875 << " on " << getIRName(IR) << "\n";
876
877 if (shouldPrintAfterCurrentPassNumber())
878 pushPassRunDescriptor(PassID, IR, DumpIRFilename);
879
880 if (!shouldPrintBeforePass(PassID) && !shouldPrintBeforeCurrentPassNumber())
881 return;
882
883 auto WriteIRToStream = [&](raw_ostream &Stream) {
884 Stream << "; *** IR Dump Before ";
885 if (shouldPrintBeforeSomePassNumber())
886 Stream << CurrentPassNumber << "-";
887 Stream << PassID << " on " << getIRName(IR) << " ***\n";
888 unwrapAndPrint(Stream, IR);
889 };
890
891 if (!DumpIRFilename.empty()) {
892 DumpIRFilename += getFileSuffix(IRDumpFileSuffixType::Before);
893 llvm::raw_fd_ostream DumpIRFileStream{
894 prepareDumpIRFileDescriptor(DumpIRFilename), /* shouldClose */ true};
895 WriteIRToStream(DumpIRFileStream);
896 } else {
897 WriteIRToStream(dbgs());
898 }
899}
900
901void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
902 if (isIgnored(PassID))
903 return;
904
905 if (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber())
906 return;
907
908 auto [M, DumpIRFilename, IRName, StoredPassID] = popPassRunDescriptor(PassID);
909 assert(StoredPassID == PassID && "mismatched PassID");
910
911 if (!shouldPrintIR(IR) ||
912 (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber()))
913 return;
914
915 auto WriteIRToStream = [&](raw_ostream &Stream, const StringRef IRName) {
916 Stream << "; *** IR Dump After ";
917 if (shouldPrintAfterSomePassNumber())
918 Stream << CurrentPassNumber << "-";
919 Stream << StringRef(formatv("{0}", PassID)) << " on " << IRName << " ***\n";
920 unwrapAndPrint(Stream, IR);
921 };
922
923 if (!IRDumpDirectory.empty()) {
924 assert(!DumpIRFilename.empty() && "DumpIRFilename must not be empty and "
925 "should be set in printBeforePass");
926 const std::string DumpIRFilenameWithSuffix =
927 DumpIRFilename + getFileSuffix(IRDumpFileSuffixType::After).str();
928 llvm::raw_fd_ostream DumpIRFileStream{
929 prepareDumpIRFileDescriptor(DumpIRFilenameWithSuffix),
930 /* shouldClose */ true};
931 WriteIRToStream(DumpIRFileStream, IRName);
932 } else {
933 WriteIRToStream(dbgs(), IRName);
934 }
935}
936
937void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
938 if (isIgnored(PassID))
939 return;
940
941 if (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber())
942 return;
943
944 auto [M, DumpIRFilename, IRName, StoredPassID] = popPassRunDescriptor(PassID);
945 assert(StoredPassID == PassID && "mismatched PassID");
946 // Additional filtering (e.g. -filter-print-func) can lead to module
947 // printing being skipped.
948 if (!M ||
949 (!shouldPrintAfterPass(PassID) && !shouldPrintAfterCurrentPassNumber()))
950 return;
951
952 auto WriteIRToStream = [&](raw_ostream &Stream, const Module *M,
953 const StringRef IRName) {
954 SmallString<20> Banner;
955 Banner = formatv("; *** IR Dump After {0} on {1} (invalidated) ***", PassID,
956 IRName);
957 Stream << Banner << "\n";
958 printIR(Stream, M);
959 };
960
961 if (!IRDumpDirectory.empty()) {
962 assert(!DumpIRFilename.empty() && "DumpIRFilename must not be empty and "
963 "should be set in printBeforePass");
964 const std::string DumpIRFilenameWithSuffix =
965 DumpIRFilename + getFileSuffix(IRDumpFileSuffixType::Invalidated).str();
966 llvm::raw_fd_ostream DumpIRFileStream{
967 prepareDumpIRFileDescriptor(DumpIRFilenameWithSuffix),
968 /* shouldClose */ true};
969 WriteIRToStream(DumpIRFileStream, M, IRName);
970 } else {
971 WriteIRToStream(dbgs(), M, IRName);
972 }
973}
974
975bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
977 return true;
978
981}
982
983bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
985 return true;
986
989}
990
991bool PrintIRInstrumentation::shouldPrintBeforeCurrentPassNumber() {
992 return shouldPrintBeforeSomePassNumber() &&
993 (CurrentPassNumber == PrintBeforePassNumber);
994}
995
996bool PrintIRInstrumentation::shouldPrintAfterCurrentPassNumber() {
997 return shouldPrintAfterSomePassNumber() &&
998 (CurrentPassNumber == PrintAfterPassNumber);
999}
1000
1001bool PrintIRInstrumentation::shouldPrintPassNumbers() {
1002 return PrintPassNumbers;
1003}
1004
1005bool PrintIRInstrumentation::shouldPrintBeforeSomePassNumber() {
1006 return PrintBeforePassNumber > 0;
1007}
1008
1009bool PrintIRInstrumentation::shouldPrintAfterSomePassNumber() {
1010 return PrintAfterPassNumber > 0;
1011}
1012
1015 this->PIC = &PIC;
1016
1017 // BeforePass callback is not just for printing, it also saves a Module
1018 // for later use in AfterPassInvalidated and keeps tracks of the
1019 // CurrentPassNumber.
1020 if (shouldPrintPassNumbers() || shouldPrintBeforeSomePassNumber() ||
1021 shouldPrintAfterSomePassNumber() || shouldPrintBeforeSomePass() ||
1024 [this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
1025
1026 if (shouldPrintAfterSomePass() || shouldPrintAfterSomePassNumber()) {
1028 [this](StringRef P, Any IR, const PreservedAnalyses &) {
1029 this->printAfterPass(P, IR);
1030 });
1032 [this](StringRef P, const PreservedAnalyses &) {
1033 this->printAfterPassInvalidated(P);
1034 });
1035 }
1036}
1037
1041 [this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
1042}
1043
1044bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
1045 const auto *F = unwrapIR<Function>(IR);
1046 if (!F) {
1047 if (const auto *L = unwrapIR<Loop>(IR))
1048 F = L->getHeader()->getParent();
1049 }
1050 bool ShouldRun = !(F && F->hasOptNone());
1051 if (!ShouldRun && DebugLogging) {
1052 errs() << "Skipping pass " << PassID << " on " << F->getName()
1053 << " due to optnone attribute\n";
1054 }
1055 return ShouldRun;
1056}
1057
1059 if (isIgnored(PassName))
1060 return true;
1061
1062 bool ShouldRun =
1063 Context.getOptPassGate().shouldRunPass(PassName, getIRName(IR));
1064 if (!ShouldRun && !this->HasWrittenIR && !OptBisectPrintIRPath.empty()) {
1065 // FIXME: print IR if limit is higher than number of opt-bisect
1066 // invocations
1067 this->HasWrittenIR = true;
1068 const Module *M = unwrapModule(IR, /*Force=*/true);
1069 assert((M && &M->getContext() == &Context) && "Missing/Mismatching Module");
1070 std::error_code EC;
1072 if (EC)
1074 M->print(OS, nullptr);
1075 }
1076 return ShouldRun;
1077}
1078
1081 OptPassGate &PassGate = Context.getOptPassGate();
1082 if (!PassGate.isEnabled())
1083 return;
1084
1086 return this->shouldRun(PassName, IR);
1087 });
1088}
1089
1090raw_ostream &PrintPassInstrumentation::print() {
1091 if (Opts.Indent) {
1092 assert(Indent >= 0);
1093 dbgs().indent(Indent);
1094 }
1095 return dbgs();
1096}
1097
1100 if (!Enabled)
1101 return;
1102
1103 std::vector<StringRef> SpecialPasses;
1104 if (!Opts.Verbose) {
1105 SpecialPasses.emplace_back("PassManager");
1106 SpecialPasses.emplace_back("PassAdaptor");
1107 }
1108
1109 PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID,
1110 Any IR) {
1111 assert(!isSpecialPass(PassID, SpecialPasses) &&
1112 "Unexpectedly skipping special pass");
1113
1114 print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n";
1115 });
1116 PIC.registerBeforeNonSkippedPassCallback([this, SpecialPasses](
1117 StringRef PassID, Any IR) {
1118 if (isSpecialPass(PassID, SpecialPasses))
1119 return;
1120
1121 auto &OS = print();
1122 OS << "Running pass: " << PassID << " on " << getIRName(IR);
1123 if (const auto *F = unwrapIR<Function>(IR)) {
1124 unsigned Count = F->getInstructionCount();
1125 OS << " (" << Count << " instruction";
1126 if (Count != 1)
1127 OS << 's';
1128 OS << ')';
1129 } else if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR)) {
1130 int Count = C->size();
1131 OS << " (" << Count << " node";
1132 if (Count != 1)
1133 OS << 's';
1134 OS << ')';
1135 }
1136 OS << "\n";
1137 Indent += 2;
1138 });
1140 [this, SpecialPasses](StringRef PassID, Any IR,
1141 const PreservedAnalyses &) {
1142 if (isSpecialPass(PassID, SpecialPasses))
1143 return;
1144
1145 Indent -= 2;
1146 });
1148 [this, SpecialPasses](StringRef PassID, Any IR) {
1149 if (isSpecialPass(PassID, SpecialPasses))
1150 return;
1151
1152 Indent -= 2;
1153 });
1154
1155 if (!Opts.SkipAnalyses) {
1157 print() << "Running analysis: " << PassID << " on " << getIRName(IR)
1158 << "\n";
1159 Indent += 2;
1160 });
1162 [this](StringRef PassID, Any IR) { Indent -= 2; });
1164 print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR)
1165 << "\n";
1166 });
1168 print() << "Clearing all analysis results for: " << IRName << "\n";
1169 });
1170 }
1171}
1172
1174 bool TrackBBLifetime) {
1175 if (TrackBBLifetime)
1177 for (const auto &BB : *F) {
1178 if (BBGuards)
1179 BBGuards->try_emplace(intptr_t(&BB), &BB);
1180 for (const auto *Succ : successors(&BB)) {
1181 Graph[&BB][Succ]++;
1182 if (BBGuards)
1183 BBGuards->try_emplace(intptr_t(Succ), Succ);
1184 }
1185 }
1186}
1187
1188static void printBBName(raw_ostream &out, const BasicBlock *BB) {
1189 if (BB->hasName()) {
1190 out << BB->getName() << "<" << BB << ">";
1191 return;
1192 }
1193
1194 if (!BB->getParent()) {
1195 out << "unnamed_removed<" << BB << ">";
1196 return;
1197 }
1198
1199 if (BB->isEntryBlock()) {
1200 out << "entry"
1201 << "<" << BB << ">";
1202 return;
1203 }
1204
1205 unsigned FuncOrderBlockNum = 0;
1206 for (auto &FuncBB : *BB->getParent()) {
1207 if (&FuncBB == BB)
1208 break;
1209 FuncOrderBlockNum++;
1210 }
1211 out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">";
1212}
1213
1215 const CFG &Before,
1216 const CFG &After) {
1217 assert(!After.isPoisoned());
1218 if (Before.isPoisoned()) {
1219 out << "Some blocks were deleted\n";
1220 return;
1221 }
1222
1223 // Find and print graph differences.
1224 if (Before.Graph.size() != After.Graph.size())
1225 out << "Different number of non-leaf basic blocks: before="
1226 << Before.Graph.size() << ", after=" << After.Graph.size() << "\n";
1227
1228 for (auto &BB : Before.Graph) {
1229 auto BA = After.Graph.find(BB.first);
1230 if (BA == After.Graph.end()) {
1231 out << "Non-leaf block ";
1232 printBBName(out, BB.first);
1233 out << " is removed (" << BB.second.size() << " successors)\n";
1234 }
1235 }
1236
1237 for (auto &BA : After.Graph) {
1238 auto BB = Before.Graph.find(BA.first);
1239 if (BB == Before.Graph.end()) {
1240 out << "Non-leaf block ";
1241 printBBName(out, BA.first);
1242 out << " is added (" << BA.second.size() << " successors)\n";
1243 continue;
1244 }
1245
1246 if (BB->second == BA.second)
1247 continue;
1248
1249 out << "Different successors of block ";
1250 printBBName(out, BA.first);
1251 out << " (unordered):\n";
1252 out << "- before (" << BB->second.size() << "): ";
1253 for (auto &SuccB : BB->second) {
1254 printBBName(out, SuccB.first);
1255 if (SuccB.second != 1)
1256 out << "(" << SuccB.second << "), ";
1257 else
1258 out << ", ";
1259 }
1260 out << "\n";
1261 out << "- after (" << BA.second.size() << "): ";
1262 for (auto &SuccA : BA.second) {
1263 printBBName(out, SuccA.first);
1264 if (SuccA.second != 1)
1265 out << "(" << SuccA.second << "), ";
1266 else
1267 out << ", ";
1268 }
1269 out << "\n";
1270 }
1271}
1272
1273// PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check
1274// passes, that reported they kept CFG analyses up-to-date, did not actually
1275// change CFG. This check is done as follows. Before every functional pass in
1276// BeforeNonSkippedPassCallback a CFG snapshot (an instance of
1277// PreservedCFGCheckerInstrumentation::CFG) is requested from
1278// FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the
1279// functional pass finishes and reports that CFGAnalyses or AllAnalyses are
1280// up-to-date then the cached result of PreservedCFGCheckerAnalysis (if
1281// available) is checked to be equal to a freshly created CFG snapshot.
1283 : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> {
1285
1287
1288public:
1289 /// Provide the result type for this analysis pass.
1291
1292 /// Run the analysis pass over a function and produce CFG.
1294 return Result(&F, /* TrackBBLifetime */ true);
1295 }
1296};
1297
1299
1301 : public AnalysisInfoMixin<PreservedFunctionHashAnalysis> {
1303
1306 };
1307
1309
1311 return Result{StructuralHash(F)};
1312 }
1313};
1314
1316
1318 : public AnalysisInfoMixin<PreservedModuleHashAnalysis> {
1320
1321 struct ModuleHash {
1323 };
1324
1326
1328 return Result{StructuralHash(F)};
1329 }
1330};
1331
1333
1335 Function &F, const PreservedAnalyses &PA,
1337 auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>();
1338 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
1339 PAC.preservedSet<CFGAnalyses>());
1340}
1341
1344
1345 if (const auto *MaybeF = unwrapIR<Function>(IR)) {
1346 Functions.push_back(const_cast<Function *>(MaybeF));
1347 } else if (const auto *MaybeM = unwrapIR<Module>(IR)) {
1348 for (Function &F : *const_cast<Module *>(MaybeM))
1349 Functions.push_back(&F);
1350 }
1351 return Functions;
1352}
1353
1357 return;
1358
1359 bool Registered = false;
1360 PIC.registerBeforeNonSkippedPassCallback([this, &MAM, Registered](
1361 StringRef P, Any IR) mutable {
1362#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1363 assert(&PassStack.emplace_back(P));
1364#endif
1365 (void)this;
1366
1368 *const_cast<Module *>(unwrapModule(IR, /*Force=*/true)))
1369 .getManager();
1370 if (!Registered) {
1371 FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); });
1373 MAM.registerPass([&] { return PreservedModuleHashAnalysis(); });
1374 Registered = true;
1375 }
1376
1377 for (Function *F : GetFunctions(IR)) {
1378 // Make sure a fresh CFG snapshot is available before the pass.
1381 }
1382
1383 if (const auto *MPtr = unwrapIR<Module>(IR)) {
1384 auto &M = *const_cast<Module *>(MPtr);
1386 }
1387 });
1388
1390 [this](StringRef P, const PreservedAnalyses &PassPA) {
1391#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1392 assert(PassStack.pop_back_val() == P &&
1393 "Before and After callbacks must correspond");
1394#endif
1395 (void)this;
1396 });
1397
1399 const PreservedAnalyses &PassPA) {
1400#ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS
1401 assert(PassStack.pop_back_val() == P &&
1402 "Before and After callbacks must correspond");
1403#endif
1404 (void)this;
1405
1406 // We have to get the FAM via the MAM, rather than directly use a passed in
1407 // FAM because if MAM has not cached the FAM, it won't invalidate function
1408 // analyses in FAM.
1410 *const_cast<Module *>(unwrapModule(IR, /*Force=*/true)))
1411 .getManager();
1412
1413 for (Function *F : GetFunctions(IR)) {
1414 if (auto *HashBefore =
1416 if (HashBefore->Hash != StructuralHash(*F)) {
1418 "Function @{0} changed by {1} without invalidating analyses",
1419 F->getName(), P));
1420 }
1421 }
1422
1423 auto CheckCFG = [](StringRef Pass, StringRef FuncName,
1424 const CFG &GraphBefore, const CFG &GraphAfter) {
1425 if (GraphAfter == GraphBefore)
1426 return;
1427
1428 dbgs()
1429 << "Error: " << Pass
1430 << " does not invalidate CFG analyses but CFG changes detected in "
1431 "function @"
1432 << FuncName << ":\n";
1433 CFG::printDiff(dbgs(), GraphBefore, GraphAfter);
1434 report_fatal_error(Twine("CFG unexpectedly changed by ", Pass));
1435 };
1436
1437 if (auto *GraphBefore =
1439 CheckCFG(P, F->getName(), *GraphBefore,
1440 CFG(F, /* TrackBBLifetime */ false));
1441 }
1442 if (const auto *MPtr = unwrapIR<Module>(IR)) {
1443 auto &M = *const_cast<Module *>(MPtr);
1444 if (auto *HashBefore =
1446 if (HashBefore->Hash != StructuralHash(M)) {
1448 "Module changed by {0} without invalidating analyses", P));
1449 }
1450 }
1451 }
1452 });
1453}
1454
1458 [this, MAM](StringRef P, Any IR, const PreservedAnalyses &PassPA) {
1459 if (isIgnored(P) || P == "VerifierPass")
1460 return;
1461 const auto *F = unwrapIR<Function>(IR);
1462 if (!F) {
1463 if (const auto *L = unwrapIR<Loop>(IR))
1464 F = L->getHeader()->getParent();
1465 }
1466
1467 if (F) {
1468 if (DebugLogging)
1469 dbgs() << "Verifying function " << F->getName() << "\n";
1470
1471 if (verifyFunction(*F, &errs()))
1472 report_fatal_error(formatv("Broken function found after pass "
1473 "\"{0}\", compilation aborted!",
1474 P));
1475 } else {
1476 const auto *M = unwrapIR<Module>(IR);
1477 if (!M) {
1478 if (const auto *C = unwrapIR<LazyCallGraph::SCC>(IR))
1479 M = C->begin()->getFunction().getParent();
1480 }
1481
1482 if (M) {
1483 if (DebugLogging)
1484 dbgs() << "Verifying module " << M->getName() << "\n";
1485
1486 if (verifyModule(*M, &errs()))
1487 report_fatal_error(formatv("Broken module found after pass "
1488 "\"{0}\", compilation aborted!",
1489 P));
1490 }
1491
1492 if (auto *MF = unwrapIR<MachineFunction>(IR)) {
1493 if (DebugLogging)
1494 dbgs() << "Verifying machine function " << MF->getName() << '\n';
1495 std::string Banner =
1496 formatv("Broken machine function found after pass "
1497 "\"{0}\", compilation aborted!",
1498 P);
1499 if (MAM) {
1500 Module &M = const_cast<Module &>(*MF->getFunction().getParent());
1501 auto &MFAM =
1503 .getManager();
1505 Verifier.run(const_cast<MachineFunction &>(*MF), MFAM);
1506 } else {
1507 verifyMachineFunction(Banner, *MF);
1508 }
1509 }
1510 }
1511 });
1512}
1513
1515
1517 StringRef PassID,
1520}
1521
1525 Any IR) {
1526 SmallString<20> Banner =
1527 formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name);
1528 Out << Banner;
1530 .compare(getModuleForComparison(IR),
1531 [&](bool InModule, unsigned Minor,
1533 const FuncDataT<EmptyData> &After) -> void {
1534 handleFunctionCompare(Name, "", PassID, " on ", InModule,
1535 Minor, Before, After);
1536 });
1537 Out << "\n";
1538}
1539
1541 StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,
1542 bool InModule, unsigned Minor, const FuncDataT<EmptyData> &Before,
1543 const FuncDataT<EmptyData> &After) {
1544 // Print a banner when this is being shown in the context of a module
1545 if (InModule)
1546 Out << "\n*** IR for function " << Name << " ***\n";
1547
1549 Before, After,
1550 [&](const BlockDataT<EmptyData> *B, const BlockDataT<EmptyData> *A) {
1551 StringRef BStr = B ? B->getBody() : "\n";
1552 StringRef AStr = A ? A->getBody() : "\n";
1553 const std::string Removed =
1554 UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n";
1555 const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n";
1556 const std::string NoChange = " %l\n";
1557 Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange);
1558 });
1559}
1560
1566 TextChangeReporter<IRDataT<EmptyData>>::registerRequiredCallbacks(PIC);
1567}
1568
1570
1574 return;
1576 [this](StringRef P, Any IR) { this->runBeforePass(P, IR); });
1578 [this](StringRef P, Any IR, const PreservedAnalyses &) {
1579 this->runAfterPass();
1580 },
1581 true);
1583 [this](StringRef P, const PreservedAnalyses &) { this->runAfterPass(); },
1584 true);
1586 [this](StringRef P, Any IR) { this->runBeforePass(P, IR); });
1588 [this](StringRef P, Any IR) { this->runAfterPass(); }, true);
1589}
1590
1591void TimeProfilingPassesHandler::runBeforePass(StringRef PassID, Any IR) {
1592 timeTraceProfilerBegin(PassID, getIRName(IR, true));
1593}
1594
1595void TimeProfilingPassesHandler::runAfterPass() { timeTraceProfilerEnd(); }
1596
1597namespace {
1598
1599class DisplayNode;
1600class DotCfgDiffDisplayGraph;
1601
1602// Base class for a node or edge in the dot-cfg-changes graph.
1603class DisplayElement {
1604public:
1605 // Is this in before, after, or both?
1606 StringRef getColour() const { return Colour; }
1607
1608protected:
1609 DisplayElement(StringRef Colour) : Colour(Colour) {}
1610 const StringRef Colour;
1611};
1612
1613// An edge representing a transition between basic blocks in the
1614// dot-cfg-changes graph.
1615class DisplayEdge : public DisplayElement {
1616public:
1617 DisplayEdge(std::string Value, DisplayNode &Node, StringRef Colour)
1618 : DisplayElement(Colour), Value(Value), Node(Node) {}
1619 // The value on which the transition is made.
1620 std::string getValue() const { return Value; }
1621 // The node (representing a basic block) reached by this transition.
1622 const DisplayNode &getDestinationNode() const { return Node; }
1623
1624protected:
1625 std::string Value;
1626 const DisplayNode &Node;
1627};
1628
1629// A node in the dot-cfg-changes graph which represents a basic block.
1630class DisplayNode : public DisplayElement {
1631public:
1632 // \p C is the content for the node, \p T indicates the colour for the
1633 // outline of the node
1634 DisplayNode(std::string Content, StringRef Colour)
1635 : DisplayElement(Colour), Content(Content) {}
1636
1637 // Iterator to the child nodes. Required by GraphWriter.
1638 using ChildIterator = std::unordered_set<DisplayNode *>::const_iterator;
1639 ChildIterator children_begin() const { return Children.cbegin(); }
1640 ChildIterator children_end() const { return Children.cend(); }
1641
1642 // Iterator for the edges. Required by GraphWriter.
1643 using EdgeIterator = std::vector<DisplayEdge *>::const_iterator;
1644 EdgeIterator edges_begin() const { return EdgePtrs.cbegin(); }
1645 EdgeIterator edges_end() const { return EdgePtrs.cend(); }
1646
1647 // Create an edge to \p Node on value \p Value, with colour \p Colour.
1648 void createEdge(StringRef Value, DisplayNode &Node, StringRef Colour);
1649
1650 // Return the content of this node.
1651 std::string getContent() const { return Content; }
1652
1653 // Return the edge to node \p S.
1654 const DisplayEdge &getEdge(const DisplayNode &To) const {
1655 assert(EdgeMap.find(&To) != EdgeMap.end() && "Expected to find edge.");
1656 return *EdgeMap.find(&To)->second;
1657 }
1658
1659 // Return the value for the transition to basic block \p S.
1660 // Required by GraphWriter.
1661 std::string getEdgeSourceLabel(const DisplayNode &Sink) const {
1662 return getEdge(Sink).getValue();
1663 }
1664
1665 void createEdgeMap();
1666
1667protected:
1668 const std::string Content;
1669
1670 // Place to collect all of the edges. Once they are all in the vector,
1671 // the vector will not reallocate so then we can use pointers to them,
1672 // which are required by the graph writing routines.
1673 std::vector<DisplayEdge> Edges;
1674
1675 std::vector<DisplayEdge *> EdgePtrs;
1676 std::unordered_set<DisplayNode *> Children;
1677 std::unordered_map<const DisplayNode *, const DisplayEdge *> EdgeMap;
1678
1679 // Safeguard adding of edges.
1680 bool AllEdgesCreated = false;
1681};
1682
1683// Class representing a difference display (corresponds to a pdf file).
1684class DotCfgDiffDisplayGraph {
1685public:
1686 DotCfgDiffDisplayGraph(std::string Name) : GraphName(Name) {}
1687
1688 // Generate the file into \p DotFile.
1689 void generateDotFile(StringRef DotFile);
1690
1691 // Iterator to the nodes. Required by GraphWriter.
1692 using NodeIterator = std::vector<DisplayNode *>::const_iterator;
1693 NodeIterator nodes_begin() const {
1694 assert(NodeGenerationComplete && "Unexpected children iterator creation");
1695 return NodePtrs.cbegin();
1696 }
1697 NodeIterator nodes_end() const {
1698 assert(NodeGenerationComplete && "Unexpected children iterator creation");
1699 return NodePtrs.cend();
1700 }
1701
1702 // Record the index of the entry node. At this point, we can build up
1703 // vectors of pointers that are required by the graph routines.
1704 void setEntryNode(unsigned N) {
1705 // At this point, there will be no new nodes.
1706 assert(!NodeGenerationComplete && "Unexpected node creation");
1707 NodeGenerationComplete = true;
1708 for (auto &N : Nodes)
1709 NodePtrs.emplace_back(&N);
1710
1711 EntryNode = NodePtrs[N];
1712 }
1713
1714 // Create a node.
1715 void createNode(std::string C, StringRef Colour) {
1716 assert(!NodeGenerationComplete && "Unexpected node creation");
1717 Nodes.emplace_back(C, Colour);
1718 }
1719 // Return the node at index \p N to avoid problems with vectors reallocating.
1720 DisplayNode &getNode(unsigned N) {
1721 assert(N < Nodes.size() && "Node is out of bounds");
1722 return Nodes[N];
1723 }
1724 unsigned size() const {
1725 assert(NodeGenerationComplete && "Unexpected children iterator creation");
1726 return Nodes.size();
1727 }
1728
1729 // Return the name of the graph. Required by GraphWriter.
1730 std::string getGraphName() const { return GraphName; }
1731
1732 // Return the string representing the differences for basic block \p Node.
1733 // Required by GraphWriter.
1734 std::string getNodeLabel(const DisplayNode &Node) const {
1735 return Node.getContent();
1736 }
1737
1738 // Return a string with colour information for Dot. Required by GraphWriter.
1739 std::string getNodeAttributes(const DisplayNode &Node) const {
1740 return attribute(Node.getColour());
1741 }
1742
1743 // Return a string with colour information for Dot. Required by GraphWriter.
1744 std::string getEdgeColorAttr(const DisplayNode &From,
1745 const DisplayNode &To) const {
1746 return attribute(From.getEdge(To).getColour());
1747 }
1748
1749 // Get the starting basic block. Required by GraphWriter.
1750 DisplayNode *getEntryNode() const {
1751 assert(NodeGenerationComplete && "Unexpected children iterator creation");
1752 return EntryNode;
1753 }
1754
1755protected:
1756 // Return the string containing the colour to use as a Dot attribute.
1757 std::string attribute(StringRef Colour) const {
1758 return "color=" + Colour.str();
1759 }
1760
1761 bool NodeGenerationComplete = false;
1762 const std::string GraphName;
1763 std::vector<DisplayNode> Nodes;
1764 std::vector<DisplayNode *> NodePtrs;
1765 DisplayNode *EntryNode = nullptr;
1766};
1767
1768void DisplayNode::createEdge(StringRef Value, DisplayNode &Node,
1769 StringRef Colour) {
1770 assert(!AllEdgesCreated && "Expected to be able to still create edges.");
1771 Edges.emplace_back(Value.str(), Node, Colour);
1772 Children.insert(&Node);
1773}
1774
1775void DisplayNode::createEdgeMap() {
1776 // No more edges will be added so we can now use pointers to the edges
1777 // as the vector will not grow and reallocate.
1778 AllEdgesCreated = true;
1779 for (auto &E : Edges)
1780 EdgeMap.insert({&E.getDestinationNode(), &E});
1781}
1782
1783class DotCfgDiffNode;
1784class DotCfgDiff;
1785
1786// A class representing a basic block in the Dot difference graph.
1787class DotCfgDiffNode {
1788public:
1789 DotCfgDiffNode() = delete;
1790
1791 // Create a node in Dot difference graph \p G representing the basic block
1792 // represented by \p BD with colour \p Colour (where it exists).
1793 DotCfgDiffNode(DotCfgDiff &G, unsigned N, const BlockDataT<DCData> &BD,
1794 StringRef Colour)
1795 : Graph(G), N(N), Data{&BD, nullptr}, Colour(Colour) {}
1796 DotCfgDiffNode(const DotCfgDiffNode &DN)
1797 : Graph(DN.Graph), N(DN.N), Data{DN.Data[0], DN.Data[1]},
1798 Colour(DN.Colour), EdgesMap(DN.EdgesMap), Children(DN.Children),
1799 Edges(DN.Edges) {}
1800
1801 unsigned getIndex() const { return N; }
1802
1803 // The label of the basic block
1804 StringRef getLabel() const {
1805 assert(Data[0] && "Expected Data[0] to be set.");
1806 return Data[0]->getLabel();
1807 }
1808 // Return the colour for this block
1809 StringRef getColour() const { return Colour; }
1810 // Change this basic block from being only in before to being common.
1811 // Save the pointer to \p Other.
1812 void setCommon(const BlockDataT<DCData> &Other) {
1813 assert(!Data[1] && "Expected only one block datum");
1814 Data[1] = &Other;
1815 Colour = CommonColour;
1816 }
1817 // Add an edge to \p E of colour {\p Value, \p Colour}.
1818 void addEdge(unsigned E, StringRef Value, StringRef Colour) {
1819 // This is a new edge or it is an edge being made common.
1820 assert((EdgesMap.count(E) == 0 || Colour == CommonColour) &&
1821 "Unexpected edge count and color.");
1822 EdgesMap[E] = {Value.str(), Colour};
1823 }
1824 // Record the children and create edges.
1825 void finalize(DotCfgDiff &G);
1826
1827 // Return the colour of the edge to node \p S.
1828 StringRef getEdgeColour(const unsigned S) const {
1829 assert(EdgesMap.count(S) == 1 && "Expected to find edge.");
1830 return EdgesMap.at(S).second;
1831 }
1832
1833 // Return the string representing the basic block.
1834 std::string getBodyContent() const;
1835
1836 void createDisplayEdges(DotCfgDiffDisplayGraph &Graph, unsigned DisplayNode,
1837 std::map<const unsigned, unsigned> &NodeMap) const;
1838
1839protected:
1840 DotCfgDiff &Graph;
1841 const unsigned N;
1842 const BlockDataT<DCData> *Data[2];
1843 StringRef Colour;
1844 std::map<const unsigned, std::pair<std::string, StringRef>> EdgesMap;
1845 std::vector<unsigned> Children;
1846 std::vector<unsigned> Edges;
1847};
1848
1849// Class representing the difference graph between two functions.
1850class DotCfgDiff {
1851public:
1852 // \p Title is the title given to the graph. \p EntryNodeName is the
1853 // entry node for the function. \p Before and \p After are the before
1854 // after versions of the function, respectively. \p Dir is the directory
1855 // in which to store the results.
1856 DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,
1857 const FuncDataT<DCData> &After);
1858
1859 DotCfgDiff(const DotCfgDiff &) = delete;
1860 DotCfgDiff &operator=(const DotCfgDiff &) = delete;
1861
1862 DotCfgDiffDisplayGraph createDisplayGraph(StringRef Title,
1863 StringRef EntryNodeName);
1864
1865 // Return a string consisting of the labels for the \p Source and \p Sink.
1866 // The combination allows distinguishing changing transitions on the
1867 // same value (ie, a transition went to X before and goes to Y after).
1868 // Required by GraphWriter.
1869 StringRef getEdgeSourceLabel(const unsigned &Source,
1870 const unsigned &Sink) const {
1871 std::string S =
1872 getNode(Source).getLabel().str() + " " + getNode(Sink).getLabel().str();
1873 assert(EdgeLabels.count(S) == 1 && "Expected to find edge label.");
1874 return EdgeLabels.find(S)->getValue();
1875 }
1876
1877 // Return the number of basic blocks (nodes). Required by GraphWriter.
1878 unsigned size() const { return Nodes.size(); }
1879
1880 const DotCfgDiffNode &getNode(unsigned N) const {
1881 assert(N < Nodes.size() && "Unexpected index for node reference");
1882 return Nodes[N];
1883 }
1884
1885protected:
1886 // Return the string surrounded by HTML to make it the appropriate colour.
1887 std::string colourize(std::string S, StringRef Colour) const;
1888
1889 void createNode(StringRef Label, const BlockDataT<DCData> &BD, StringRef C) {
1890 unsigned Pos = Nodes.size();
1891 Nodes.emplace_back(*this, Pos, BD, C);
1892 NodePosition.insert({Label, Pos});
1893 }
1894
1895 // TODO Nodes should probably be a StringMap<DotCfgDiffNode> after the
1896 // display graph is separated out, which would remove the need for
1897 // NodePosition.
1898 std::vector<DotCfgDiffNode> Nodes;
1899 StringMap<unsigned> NodePosition;
1900 const std::string GraphName;
1901
1902 StringMap<std::string> EdgeLabels;
1903};
1904
1905std::string DotCfgDiffNode::getBodyContent() const {
1906 if (Colour == CommonColour) {
1907 assert(Data[1] && "Expected Data[1] to be set.");
1908
1909 StringRef SR[2];
1910 for (unsigned I = 0; I < 2; ++I) {
1911 SR[I] = Data[I]->getBody();
1912 // drop initial '\n' if present
1913 SR[I].consume_front("\n");
1914 // drop predecessors as they can be big and are redundant
1915 SR[I] = SR[I].drop_until([](char C) { return C == '\n'; }).drop_front();
1916 }
1917
1918 SmallString<80> OldLineFormat = formatv(
1919 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", BeforeColour);
1920 SmallString<80> NewLineFormat = formatv(
1921 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", AfterColour);
1922 SmallString<80> UnchangedLineFormat = formatv(
1923 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", CommonColour);
1924 std::string Diff = Data[0]->getLabel().str();
1925 Diff += ":\n<BR align=\"left\"/>" +
1926 doSystemDiff(makeHTMLReady(SR[0]), makeHTMLReady(SR[1]),
1927 OldLineFormat, NewLineFormat, UnchangedLineFormat);
1928
1929 // Diff adds in some empty colour changes which are not valid HTML
1930 // so remove them. Colours are all lowercase alpha characters (as
1931 // listed in https://graphviz.org/pdf/dotguide.pdf).
1932 Regex R("<FONT COLOR=\"\\w+\"></FONT>");
1933 while (true) {
1934 std::string Error;
1935 std::string S = R.sub("", Diff, &Error);
1936 if (Error != "")
1937 return Error;
1938 if (S == Diff)
1939 return Diff;
1940 Diff = S;
1941 }
1942 llvm_unreachable("Should not get here");
1943 }
1944
1945 // Put node out in the appropriate colour.
1946 assert(!Data[1] && "Data[1] is set unexpectedly.");
1947 std::string Body = makeHTMLReady(Data[0]->getBody());
1948 const StringRef BS = Body;
1949 StringRef BS1 = BS;
1950 // Drop leading newline, if present.
1951 if (BS.front() == '\n')
1952 BS1 = BS1.drop_front(1);
1953 // Get label.
1954 StringRef Label = BS1.take_until([](char C) { return C == ':'; });
1955 // drop predecessors as they can be big and are redundant
1956 BS1 = BS1.drop_until([](char C) { return C == '\n'; }).drop_front();
1957
1958 std::string S = "<FONT COLOR=\"" + Colour.str() + "\">" + Label.str() + ":";
1959
1960 // align each line to the left.
1961 while (BS1.size()) {
1962 S.append("<BR align=\"left\"/>");
1963 StringRef Line = BS1.take_until([](char C) { return C == '\n'; });
1964 S.append(Line.str());
1965 BS1 = BS1.drop_front(Line.size() + 1);
1966 }
1967 S.append("<BR align=\"left\"/></FONT>");
1968 return S;
1969}
1970
1971std::string DotCfgDiff::colourize(std::string S, StringRef Colour) const {
1972 if (S.length() == 0)
1973 return S;
1974 return "<FONT COLOR=\"" + Colour.str() + "\">" + S + "</FONT>";
1975}
1976
1977DotCfgDiff::DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before,
1978 const FuncDataT<DCData> &After)
1979 : GraphName(Title.str()) {
1980 StringMap<StringRef> EdgesMap;
1981
1982 // Handle each basic block in the before IR.
1983 for (auto &B : Before.getData()) {
1984 StringRef Label = B.getKey();
1985 const BlockDataT<DCData> &BD = B.getValue();
1986 createNode(Label, BD, BeforeColour);
1987
1988 // Create transitions with names made up of the from block label, the value
1989 // on which the transition is made and the to block label.
1990 for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),
1991 E = BD.getData().end();
1992 Sink != E; ++Sink) {
1993 std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +
1994 BD.getData().getSuccessorLabel(Sink->getKey()).str();
1995 EdgesMap.insert({Key, BeforeColour});
1996 }
1997 }
1998
1999 // Handle each basic block in the after IR
2000 for (auto &A : After.getData()) {
2001 StringRef Label = A.getKey();
2002 const BlockDataT<DCData> &BD = A.getValue();
2003 unsigned C = NodePosition.count(Label);
2004 if (C == 0)
2005 // This only exists in the after IR. Create the node.
2006 createNode(Label, BD, AfterColour);
2007 else {
2008 assert(C == 1 && "Unexpected multiple nodes.");
2009 Nodes[NodePosition[Label]].setCommon(BD);
2010 }
2011 // Add in the edges between the nodes (as common or only in after).
2012 for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(),
2013 E = BD.getData().end();
2014 Sink != E; ++Sink) {
2015 std::string Key = (Label + " " + Sink->getKey().str()).str() + " " +
2016 BD.getData().getSuccessorLabel(Sink->getKey()).str();
2017 unsigned C = EdgesMap.count(Key);
2018 if (C == 0)
2019 EdgesMap.insert({Key, AfterColour});
2020 else {
2021 EdgesMap[Key] = CommonColour;
2022 }
2023 }
2024 }
2025
2026 // Now go through the map of edges and add them to the node.
2027 for (auto &E : EdgesMap) {
2028 // Extract the source, sink and value from the edge key.
2029 StringRef S = E.getKey();
2030 auto SP1 = S.rsplit(' ');
2031 auto &SourceSink = SP1.first;
2032 auto SP2 = SourceSink.split(' ');
2033 StringRef Source = SP2.first;
2034 StringRef Sink = SP2.second;
2035 StringRef Value = SP1.second;
2036
2037 assert(NodePosition.count(Source) == 1 && "Expected to find node.");
2038 DotCfgDiffNode &SourceNode = Nodes[NodePosition[Source]];
2039 assert(NodePosition.count(Sink) == 1 && "Expected to find node.");
2040 unsigned SinkNode = NodePosition[Sink];
2041 StringRef Colour = E.second;
2042
2043 // Look for an edge from Source to Sink
2044 if (EdgeLabels.count(SourceSink) == 0)
2045 EdgeLabels.insert({SourceSink, colourize(Value.str(), Colour)});
2046 else {
2047 StringRef V = EdgeLabels.find(SourceSink)->getValue();
2048 std::string NV = colourize(V.str() + " " + Value.str(), Colour);
2049 Colour = CommonColour;
2050 EdgeLabels[SourceSink] = NV;
2051 }
2052 SourceNode.addEdge(SinkNode, Value, Colour);
2053 }
2054 for (auto &I : Nodes)
2055 I.finalize(*this);
2056}
2057
2058DotCfgDiffDisplayGraph DotCfgDiff::createDisplayGraph(StringRef Title,
2059 StringRef EntryNodeName) {
2060 assert(NodePosition.count(EntryNodeName) == 1 &&
2061 "Expected to find entry block in map.");
2062 unsigned Entry = NodePosition[EntryNodeName];
2063 assert(Entry < Nodes.size() && "Expected to find entry node");
2064 DotCfgDiffDisplayGraph G(Title.str());
2065
2066 std::map<const unsigned, unsigned> NodeMap;
2067
2068 int EntryIndex = -1;
2069 unsigned Index = 0;
2070 for (auto &I : Nodes) {
2071 if (I.getIndex() == Entry)
2072 EntryIndex = Index;
2073 G.createNode(I.getBodyContent(), I.getColour());
2074 NodeMap.insert({I.getIndex(), Index++});
2075 }
2076 assert(EntryIndex >= 0 && "Expected entry node index to be set.");
2077 G.setEntryNode(EntryIndex);
2078
2079 for (auto &I : NodeMap) {
2080 unsigned SourceNode = I.first;
2081 unsigned DisplayNode = I.second;
2082 getNode(SourceNode).createDisplayEdges(G, DisplayNode, NodeMap);
2083 }
2084 return G;
2085}
2086
2087void DotCfgDiffNode::createDisplayEdges(
2088 DotCfgDiffDisplayGraph &DisplayGraph, unsigned DisplayNodeIndex,
2089 std::map<const unsigned, unsigned> &NodeMap) const {
2090
2091 DisplayNode &SourceDisplayNode = DisplayGraph.getNode(DisplayNodeIndex);
2092
2093 for (auto I : Edges) {
2094 unsigned SinkNodeIndex = I;
2095 StringRef Colour = getEdgeColour(SinkNodeIndex);
2096 const DotCfgDiffNode *SinkNode = &Graph.getNode(SinkNodeIndex);
2097
2098 StringRef Label = Graph.getEdgeSourceLabel(getIndex(), SinkNodeIndex);
2099 DisplayNode &SinkDisplayNode = DisplayGraph.getNode(SinkNode->getIndex());
2100 SourceDisplayNode.createEdge(Label, SinkDisplayNode, Colour);
2101 }
2102 SourceDisplayNode.createEdgeMap();
2103}
2104
2105void DotCfgDiffNode::finalize(DotCfgDiff &G) {
2106 for (auto E : EdgesMap) {
2107 Children.emplace_back(E.first);
2108 Edges.emplace_back(E.first);
2109 }
2110}
2111
2112} // namespace
2113
2114namespace llvm {
2115
2116template <> struct GraphTraits<DotCfgDiffDisplayGraph *> {
2117 using NodeRef = const DisplayNode *;
2118 using ChildIteratorType = DisplayNode::ChildIterator;
2119 using nodes_iterator = DotCfgDiffDisplayGraph::NodeIterator;
2120 using EdgeRef = const DisplayEdge *;
2121 using ChildEdgeIterator = DisplayNode::EdgeIterator;
2122
2123 static NodeRef getEntryNode(const DotCfgDiffDisplayGraph *G) {
2124 return G->getEntryNode();
2125 }
2127 return N->children_begin();
2128 }
2129 static ChildIteratorType child_end(NodeRef N) { return N->children_end(); }
2130 static nodes_iterator nodes_begin(const DotCfgDiffDisplayGraph *G) {
2131 return G->nodes_begin();
2132 }
2133 static nodes_iterator nodes_end(const DotCfgDiffDisplayGraph *G) {
2134 return G->nodes_end();
2135 }
2137 return N->edges_begin();
2138 }
2139 static ChildEdgeIterator child_edge_end(NodeRef N) { return N->edges_end(); }
2140 static NodeRef edge_dest(EdgeRef E) { return &E->getDestinationNode(); }
2141 static unsigned size(const DotCfgDiffDisplayGraph *G) { return G->size(); }
2142};
2143
2144template <>
2145struct DOTGraphTraits<DotCfgDiffDisplayGraph *> : public DefaultDOTGraphTraits {
2146 explicit DOTGraphTraits(bool Simple = false)
2148
2149 static bool renderNodesUsingHTML() { return true; }
2150 static std::string getGraphName(const DotCfgDiffDisplayGraph *DiffData) {
2151 return DiffData->getGraphName();
2152 }
2153 static std::string
2154 getGraphProperties(const DotCfgDiffDisplayGraph *DiffData) {
2155 return "\tsize=\"190, 190\";\n";
2156 }
2157 static std::string getNodeLabel(const DisplayNode *Node,
2158 const DotCfgDiffDisplayGraph *DiffData) {
2159 return DiffData->getNodeLabel(*Node);
2160 }
2161 static std::string getNodeAttributes(const DisplayNode *Node,
2162 const DotCfgDiffDisplayGraph *DiffData) {
2163 return DiffData->getNodeAttributes(*Node);
2164 }
2165 static std::string getEdgeSourceLabel(const DisplayNode *From,
2166 DisplayNode::ChildIterator &To) {
2167 return From->getEdgeSourceLabel(**To);
2168 }
2169 static std::string getEdgeAttributes(const DisplayNode *From,
2170 DisplayNode::ChildIterator &To,
2171 const DotCfgDiffDisplayGraph *DiffData) {
2172 return DiffData->getEdgeColorAttr(*From, **To);
2173 }
2174};
2175
2176} // namespace llvm
2177
2178namespace {
2179
2180void DotCfgDiffDisplayGraph::generateDotFile(StringRef DotFile) {
2181 std::error_code EC;
2182 raw_fd_ostream OutStream(DotFile, EC);
2183 if (EC) {
2184 errs() << "Error: " << EC.message() << "\n";
2185 return;
2186 }
2187 WriteGraph(OutStream, this, false);
2188 OutStream.flush();
2189 OutStream.close();
2190}
2191
2192} // namespace
2193
2194namespace llvm {
2195
2197 // Build up transition labels.
2198 const Instruction *Term = B.getTerminator();
2199 if (const BranchInst *Br = dyn_cast<const BranchInst>(Term))
2200 if (Br->isUnconditional())
2201 addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "");
2202 else {
2203 addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "true");
2204 addSuccessorLabel(Br->getSuccessor(1)->getName().str(), "false");
2205 }
2206 else if (const SwitchInst *Sw = dyn_cast<const SwitchInst>(Term)) {
2207 addSuccessorLabel(Sw->case_default()->getCaseSuccessor()->getName().str(),
2208 "default");
2209 for (auto &C : Sw->cases()) {
2210 assert(C.getCaseValue() && "Expected to find case value.");
2211 SmallString<20> Value = formatv("{0}", C.getCaseValue()->getSExtValue());
2212 addSuccessorLabel(C.getCaseSuccessor()->getName().str(), Value);
2213 }
2214 } else
2215 for (const BasicBlock *Succ : successors(&B))
2216 addSuccessorLabel(Succ->getName().str(), "");
2217}
2218
2220 for (const MachineBasicBlock *Succ : successors(&B))
2221 addSuccessorLabel(Succ->getName().str(), "");
2222}
2223
2226
2228 StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider,
2229 bool InModule, unsigned Minor, const FuncDataT<DCData> &Before,
2230 const FuncDataT<DCData> &After) {
2231 assert(HTML && "Expected outstream to be set");
2232 SmallString<8> Extender;
2234 // Handle numbering and file names.
2235 if (InModule) {
2236 Extender = formatv("{0}_{1}", N, Minor);
2237 Number = formatv("{0}.{1}", N, Minor);
2238 } else {
2239 Extender = formatv("{0}", N);
2240 Number = formatv("{0}", N);
2241 }
2242 // Create a temporary file name for the dot file.
2244 sys::fs::createUniquePath("cfgdot-%%%%%%.dot", SV, true);
2245 std::string DotFile = Twine(SV).str();
2246
2247 SmallString<20> PDFFileName = formatv("diff_{0}.pdf", Extender);
2248 SmallString<200> Text;
2249
2250 Text = formatv("{0}.{1}{2}{3}{4}", Number, Prefix, makeHTMLReady(PassID),
2251 Divider, Name);
2252
2253 DotCfgDiff Diff(Text, Before, After);
2254 std::string EntryBlockName = After.getEntryBlockName();
2255 // Use the before entry block if the after entry block was removed.
2256 if (EntryBlockName == "")
2257 EntryBlockName = Before.getEntryBlockName();
2258 assert(EntryBlockName != "" && "Expected to find entry block");
2259
2260 DotCfgDiffDisplayGraph DG = Diff.createDisplayGraph(Text, EntryBlockName);
2261 DG.generateDotFile(DotFile);
2262
2263 *HTML << genHTML(Text, DotFile, PDFFileName);
2264 std::error_code EC = sys::fs::remove(DotFile);
2265 if (EC)
2266 errs() << "Error: " << EC.message() << "\n";
2267}
2268
2270 StringRef PDFFileName) {
2271 SmallString<20> PDFFile = formatv("{0}/{1}", DotCfgDir, PDFFileName);
2272 // Create the PDF file.
2274 if (!DotExe)
2275 return "Unable to find dot executable.";
2276
2277 StringRef Args[] = {DotBinary, "-Tpdf", "-o", PDFFile, DotFile};
2278 int Result = sys::ExecuteAndWait(*DotExe, Args, std::nullopt);
2279 if (Result < 0)
2280 return "Error executing system dot.";
2281
2282 // Create the HTML tag refering to the PDF file.
2284 " <a href=\"{0}\" target=\"_blank\">{1}</a><br/>\n", PDFFileName, Text);
2285 return S.c_str();
2286}
2287
2289 assert(HTML && "Expected outstream to be set");
2290 *HTML << "<button type=\"button\" class=\"collapsible\">0. "
2291 << "Initial IR (by function)</button>\n"
2292 << "<div class=\"content\">\n"
2293 << " <p>\n";
2294 // Create representation of IR
2297 // Now compare it against itself, which will have everything the
2298 // same and will generate the files.
2300 .compare(getModuleForComparison(IR),
2301 [&](bool InModule, unsigned Minor,
2303 const FuncDataT<DCData> &After) -> void {
2304 handleFunctionCompare("", " ", "Initial IR", "", InModule,
2305 Minor, Before, After);
2306 });
2307 *HTML << " </p>\n"
2308 << "</div><br/>\n";
2309 ++N;
2310}
2311
2315}
2316
2318 assert(HTML && "Expected outstream to be set");
2319 SmallString<20> Banner =
2320 formatv(" <a>{0}. Pass {1} on {2} omitted because no change</a><br/>\n",
2321 N, makeHTMLReady(PassID), Name);
2322 *HTML << Banner;
2323 ++N;
2324}
2325
2327 const IRDataT<DCData> &Before,
2328 const IRDataT<DCData> &After, Any IR) {
2329 assert(HTML && "Expected outstream to be set");
2331 .compare(getModuleForComparison(IR),
2332 [&](bool InModule, unsigned Minor,
2334 const FuncDataT<DCData> &After) -> void {
2335 handleFunctionCompare(Name, " Pass ", PassID, " on ", InModule,
2336 Minor, Before, After);
2337 });
2338 *HTML << " </p></div>\n";
2339 ++N;
2340}
2341
2343 assert(HTML && "Expected outstream to be set");
2344 SmallString<20> Banner =
2345 formatv(" <a>{0}. {1} invalidated</a><br/>\n", N, makeHTMLReady(PassID));
2346 *HTML << Banner;
2347 ++N;
2348}
2349
2351 assert(HTML && "Expected outstream to be set");
2352 SmallString<20> Banner =
2353 formatv(" <a>{0}. Pass {1} on {2} filtered out</a><br/>\n", N,
2354 makeHTMLReady(PassID), Name);
2355 *HTML << Banner;
2356 ++N;
2357}
2358
2360 assert(HTML && "Expected outstream to be set");
2361 SmallString<20> Banner = formatv(" <a>{0}. {1} on {2} ignored</a><br/>\n", N,
2362 makeHTMLReady(PassID), Name);
2363 *HTML << Banner;
2364 ++N;
2365}
2366
2368 std::error_code EC;
2369 HTML = std::make_unique<raw_fd_ostream>(DotCfgDir + "/passes.html", EC);
2370 if (EC) {
2371 HTML = nullptr;
2372 return false;
2373 }
2374
2375 *HTML << "<!doctype html>"
2376 << "<html>"
2377 << "<head>"
2378 << "<style>.collapsible { "
2379 << "background-color: #777;"
2380 << " color: white;"
2381 << " cursor: pointer;"
2382 << " padding: 18px;"
2383 << " width: 100%;"
2384 << " border: none;"
2385 << " text-align: left;"
2386 << " outline: none;"
2387 << " font-size: 15px;"
2388 << "} .active, .collapsible:hover {"
2389 << " background-color: #555;"
2390 << "} .content {"
2391 << " padding: 0 18px;"
2392 << " display: none;"
2393 << " overflow: hidden;"
2394 << " background-color: #f1f1f1;"
2395 << "}"
2396 << "</style>"
2397 << "<title>passes.html</title>"
2398 << "</head>\n"
2399 << "<body>";
2400 return true;
2401}
2402
2404 if (!HTML)
2405 return;
2406 *HTML
2407 << "<script>var coll = document.getElementsByClassName(\"collapsible\");"
2408 << "var i;"
2409 << "for (i = 0; i < coll.length; i++) {"
2410 << "coll[i].addEventListener(\"click\", function() {"
2411 << " this.classList.toggle(\"active\");"
2412 << " var content = this.nextElementSibling;"
2413 << " if (content.style.display === \"block\"){"
2414 << " content.style.display = \"none\";"
2415 << " }"
2416 << " else {"
2417 << " content.style.display= \"block\";"
2418 << " }"
2419 << " });"
2420 << " }"
2421 << "</script>"
2422 << "</body>"
2423 << "</html>\n";
2424 HTML->flush();
2425 HTML->close();
2426}
2427
2432 SmallString<128> OutputDir;
2433 sys::fs::expand_tilde(DotCfgDir, OutputDir);
2434 sys::fs::make_absolute(OutputDir);
2435 assert(!OutputDir.empty() && "expected output dir to be non-empty");
2436 DotCfgDir = OutputDir.c_str();
2437 if (initializeHTML()) {
2439 return;
2440 }
2441 dbgs() << "Unable to open output stream for -cfg-dot-changed\n";
2442 }
2443}
2444
2446 LLVMContext &Context, bool DebugLogging, bool VerifyEach,
2447 PrintPassOptions PrintPassOpts)
2448 : PrintPass(DebugLogging, PrintPassOpts),
2449 OptNone(DebugLogging),
2450 OptPassGate(Context),
2451 PrintChangedIR(PrintChanged == ChangePrinter::Verbose),
2452 PrintChangedDiff(PrintChanged == ChangePrinter::DiffVerbose ||
2456 WebsiteChangeReporter(PrintChanged == ChangePrinter::DotCfgVerbose),
2457 Verify(DebugLogging), VerifyEach(VerifyEach) {}
2458
2459PrintCrashIRInstrumentation *PrintCrashIRInstrumentation::CrashReporter =
2460 nullptr;
2461
2463 if (!PrintOnCrashPath.empty()) {
2464 std::error_code EC;
2466 if (EC)
2468 Out << SavedIR;
2469 } else {
2470 dbgs() << SavedIR;
2471 }
2472}
2473
2474void PrintCrashIRInstrumentation::SignalHandler(void *) {
2475 // Called by signal handlers so do not lock here
2476 // Is the PrintCrashIRInstrumentation still alive?
2477 if (!CrashReporter)
2478 return;
2479
2480 assert((PrintOnCrash || !PrintOnCrashPath.empty()) &&
2481 "Did not expect to get here without option set.");
2482 CrashReporter->reportCrashIR();
2483}
2484
2486 if (!CrashReporter)
2487 return;
2488
2489 assert((PrintOnCrash || !PrintOnCrashPath.empty()) &&
2490 "Did not expect to get here without option set.");
2491 CrashReporter = nullptr;
2492}
2493
2496 if ((!PrintOnCrash && PrintOnCrashPath.empty()) || CrashReporter)
2497 return;
2498
2499 sys::AddSignalHandler(SignalHandler, nullptr);
2500 CrashReporter = this;
2501
2503 [&PIC, this](StringRef PassID, Any IR) {
2504 SavedIR.clear();
2506 OS << formatv("*** Dump of {0}IR Before Last Pass {1}",
2507 llvm::forcePrintModuleIR() ? "Module " : "", PassID);
2508 if (!isInteresting(IR, PassID, PIC.getPassNameForClassName(PassID))) {
2509 OS << " Filtered Out ***\n";
2510 return;
2511 }
2512 OS << " Started ***\n";
2513 unwrapAndPrint(OS, IR);
2514 });
2515}
2516
2519 PrintIR.registerCallbacks(PIC);
2520 PrintPass.registerCallbacks(PIC);
2521 TimePasses.registerCallbacks(PIC);
2522 OptNone.registerCallbacks(PIC);
2523 OptPassGate.registerCallbacks(PIC);
2524 PrintChangedIR.registerCallbacks(PIC);
2525 PseudoProbeVerification.registerCallbacks(PIC);
2526 if (VerifyEach)
2527 Verify.registerCallbacks(PIC, MAM);
2528 PrintChangedDiff.registerCallbacks(PIC);
2529 WebsiteChangeReporter.registerCallbacks(PIC);
2530 ChangeTester.registerCallbacks(PIC);
2531 PrintCrashIR.registerCallbacks(PIC);
2532 if (MAM)
2533 PreservedCFGChecker.registerCallbacks(PIC, *MAM);
2534
2535 // TimeProfiling records the pass running time cost.
2536 // Its 'BeforePassCallback' can be appended at the tail of all the
2537 // BeforeCallbacks by calling `registerCallbacks` in the end.
2538 // Its 'AfterPassCallback' is put at the front of all the
2539 // AfterCallbacks by its `registerCallbacks`. This is necessary
2540 // to ensure that other callbacks are not included in the timings.
2541 TimeProfilingPasses.registerCallbacks(PIC);
2542}
2543
2544template class ChangeReporter<std::string>;
2545template class TextChangeReporter<std::string>;
2546
2547template class BlockDataT<EmptyData>;
2548template class FuncDataT<EmptyData>;
2549template class IRDataT<EmptyData>;
2550template class ChangeReporter<IRDataT<EmptyData>>;
2552template class IRComparer<EmptyData>;
2553
2554} // namespace llvm
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
arc branch finalize
This file provides Any, a non-template class modeled in the spirit of std::any.
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
T Content
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1294
static bool isInteresting(const SCEV *S, const Instruction *I, const Loop *L, ScalarEvolution *SE, LoopInfo *LI)
isInteresting - Test whether the given expression is "interesting" when used by the given expression,...
Definition: IVUsers.cpp:56
static void addEdge(SmallVectorImpl< LazyCallGraph::Edge > &Edges, DenseMap< LazyCallGraph::Node *, int > &EdgeIndexMap, LazyCallGraph::Node &N, LazyCallGraph::Edge::Kind EK)
Implements a lazy call graph analysis and related passes for the new pass manager.
Legalize the Machine IR a function s Machine IR
Definition: Legalizer.cpp:81
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
static std::string getNodeLabel(const ValueInfo &VI, GlobalValueSummary *GVS)
Module.h This file contains the declarations for the Module class.
#define P(N)
ppc ctr loops PowerPC CTR Loops Verify
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
bool VerifyEach
PassInstrumentationCallbacks PIC
This file defines the Pass Instrumentation classes that provide instrumentation points into the pass ...
This header defines various interfaces for pass management in LLVM.
static StringRef getName(Value *V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
verify safepoint Safepoint IR Verifier
raw_pwrite_stream & OS
static cl::opt< std::string > BeforeColour("dot-cfg-before-color", cl::desc("Color for dot-cfg before elements"), cl::Hidden, cl::init("red"))
static cl::opt< std::string > IRDumpDirectory("ir-dump-directory", cl::desc("If specified, IR printed using the " "-print-[before|after]{-all} options will be dumped into " "files in this directory rather than written to stderr"), cl::Hidden, cl::value_desc("filename"))
static cl::opt< unsigned > PrintAfterPassNumber("print-after-pass-number", cl::init(0), cl::Hidden, cl::desc("Print IR after the pass with this number as " "reported by print-pass-numbers"))
static cl::opt< std::string > OptBisectPrintIRPath("opt-bisect-print-ir-path", cl::desc("Print IR to path when opt-bisect-limit is reached"), cl::Hidden)
static cl::opt< bool > PrintChangedBefore("print-before-changed", cl::desc("Print before passes that change them"), cl::init(false), cl::Hidden)
static cl::opt< std::string > DotCfgDir("dot-cfg-dir", cl::desc("Generate dot files into specified directory for changed IRs"), cl::Hidden, cl::init("./"))
static cl::opt< bool > VerifyAnalysisInvalidation("verify-analysis-invalidation", cl::Hidden, cl::init(false))
static cl::opt< unsigned > PrintBeforePassNumber("print-before-pass-number", cl::init(0), cl::Hidden, cl::desc("Print IR before the pass with this number as " "reported by print-pass-numbers"))
static cl::opt< std::string > CommonColour("dot-cfg-common-color", cl::desc("Color for dot-cfg common elements"), cl::Hidden, cl::init("black"))
static StringRef getFileSuffix(IRDumpFileSuffixType Type)
static SmallString< 32 > getIRFileDisplayName(Any IR)
static SmallVector< Function *, 1 > GetFunctions(Any IR)
static void printBBName(raw_ostream &out, const BasicBlock *BB)
static cl::opt< std::string > DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"), cl::desc("system dot used by change reporters"))
static bool shouldGenerateData(const Function &F)
static int prepareDumpIRFileDescriptor(const StringRef DumpIRFilename)
static const IRUnitT * unwrapIR(Any IR)
static cl::opt< std::string > AfterColour("dot-cfg-after-color", cl::desc("Color for dot-cfg after elements"), cl::Hidden, cl::init("forestgreen"))
static cl::opt< bool > PrintOnCrash("print-on-crash", cl::desc("Print the last form of the IR before crash (use -print-on-crash-path to dump to a file)"), cl::Hidden)
static cl::opt< bool > PrintPassNumbers("print-pass-numbers", cl::init(false), cl::Hidden, cl::desc("Print pass names and their ordinals"))
static cl::opt< std::string > PrintOnCrashPath("print-on-crash-path", cl::desc("Print the last form of the IR before crash to a file"), cl::Hidden)
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
static const char PassName[]
This templated class represents "all analyses that operate over <a particular IR unit>" (e....
Definition: Analysis.h:49
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:292
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
Definition: PassManager.h:424
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:467
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:405
Definition: Any.h:28
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:569
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:209
const T & getData() const
Conditional or Unconditional Branch instruction.
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
void saveIRBeforePass(Any IR, StringRef PassID, StringRef PassName)
void handleIRAfterPass(Any IR, StringRef PassID, StringRef PassName)
void registerRequiredCallbacks(PassInstrumentationCallbacks &PIC)
void handleInvalidatedPass(StringRef PassID)
void addSuccessorLabel(StringRef Succ, StringRef Label)
DCData(const BasicBlock &B)
std::unique_ptr< raw_fd_ostream > HTML
void handleInvalidated(StringRef PassID) override
void generateIRRepresentation(Any IR, StringRef PassID, IRDataT< DCData > &Output) override
static std::string genHTML(StringRef Text, StringRef DotFile, StringRef PDFFileName)
void handleFunctionCompare(StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider, bool InModule, unsigned Minor, const FuncDataT< DCData > &Before, const FuncDataT< DCData > &After)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void handleIgnored(StringRef PassID, std::string &Name) override
void handleAfter(StringRef PassID, std::string &Name, const IRDataT< DCData > &Before, const IRDataT< DCData > &After, Any) override
void handleFiltered(StringRef PassID, std::string &Name) override
void omitAfter(StringRef PassID, std::string &Name) override
Represents either an error or a value T.
Definition: ErrorOr.h:56
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
~IRChangedPrinter() override
void handleAfter(StringRef PassID, std::string &Name, const std::string &Before, const std::string &After, Any) override
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void generateIRRepresentation(Any IR, StringRef PassID, std::string &Output) override
void handleIgnored(StringRef PassID, std::string &Name) override
void handleAfter(StringRef PassID, std::string &Name, const std::string &Before, const std::string &After, Any) override
void omitAfter(StringRef PassID, std::string &Name) override
void handleInvalidated(StringRef PassID) override
void handleIR(const std::string &IR, StringRef PassID)
void handleInitialIR(Any IR) override
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void handleFiltered(StringRef PassID, std::string &Name) override
static bool generateFunctionData(IRDataT< T > &Data, const FunctionT &F)
static void analyzeIR(Any IR, IRDataT< T > &Data)
void compare(bool CompareModule, std::function< void(bool InModule, unsigned Minor, const FuncDataT< T > &Before, const FuncDataT< T > &After)> CompareFunc)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void handleAfter(StringRef PassID, std::string &Name, const IRDataT< EmptyData > &Before, const IRDataT< EmptyData > &After, Any) override
void generateIRRepresentation(Any IR, StringRef PassID, IRDataT< EmptyData > &Output) override
void handleFunctionCompare(StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider, bool InModule, unsigned Minor, const FuncDataT< EmptyData > &Before, const FuncDataT< EmptyData > &After)
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...
Definition: PassManager.h:563
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
OptPassGate & getOptPassGate() const
Access the object which can disable optional passes and individual optimizations at compile time.
A node in the call graph.
An SCC of the call graph.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:44
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Function & getFunction()
Return the LLVM function that this machine code represents.
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
bool shouldRun(StringRef PassName, Any IR)
Extensions to this class implement mechanisms to disable passes and individual optimizations at compi...
Definition: OptBisect.h:24
virtual bool isEnabled() const
isEnabled() should return true before calling shouldRunPass().
Definition: OptBisect.h:36
virtual bool shouldRunPass(const StringRef PassName, StringRef IRDescription)
IRDescription is a textual description of the IR unit the pass is running over.
Definition: OptBisect.h:30
static void report(const OrderedChangedData &Before, const OrderedChangedData &After, function_ref< void(const T *, const T *)> HandlePair)
std::vector< std::string > & getOrder()
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
void registerAfterPassInvalidatedCallback(CallableT C, bool ToFront=false)
void registerAnalysisInvalidatedCallback(CallableT C)
StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name.
void registerAfterAnalysisCallback(CallableT C, bool ToFront=false)
void registerBeforeNonSkippedPassCallback(CallableT C)
void registerBeforeSkippedPassCallback(CallableT C)
void registerShouldRunOptionalPassCallback(CallableT C)
void registerAfterPassCallback(CallableT C, bool ToFront=false)
Pass interface - Implemented by all 'passes'.
Definition: Pass.h:94
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: Analysis.h:264
void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager &MAM)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
const char * c_str()
Definition: SmallString.h:259
bool empty() const
Definition: SmallVector.h:94
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager *MAM=nullptr)
StandardInstrumentations(LLVMContext &Context, bool DebugLogging, bool VerifyEach=false, PrintPassOptions PrintPassOpts=PrintPassOptions())
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:276
bool insert(MapEntryTy *KeyValue)
insert - Insert the specified key/value pair into the map.
Definition: StringMap.h:308
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:215
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:594
StringRef drop_until(function_ref< bool(char)> F) const
Return a StringRef equal to 'this', but with all characters not satisfying the given predicate droppe...
Definition: StringRef.h:614
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
char front() const
front - Get the first character in the string.
Definition: StringRef.h:140
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:620
StringRef take_until(function_ref< bool(char)> F) const
Return the longest prefix of 'this' such that no character in the prefix satisfies the given predicat...
Definition: StringRef.h:588
std::pair< StringRef, StringRef > rsplit(StringRef Separator) const
Split into two substrings around the last occurrence of a separator string.
Definition: StringRef.h:718
Multiway switch.
void handleInitialIR(Any IR) override
void handleInvalidated(StringRef PassID) override
void omitAfter(StringRef PassID, std::string &Name) override
void handleIgnored(StringRef PassID, std::string &Name) override
void handleFiltered(StringRef PassID, std::string &Name) override
void registerCallbacks(PassInstrumentationCallbacks &PIC)
void registerCallbacks(PassInstrumentationCallbacks &PIC)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void registerCallbacks(PassInstrumentationCallbacks &PIC, ModuleAnalysisManager *MAM)
An efficient, type-erasing, non-owning reference to a callable.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:460
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Key
PAL metadata keys.
@ Entry
Definition: COFF.h:811
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
DiagnosticInfoOptimizationBase::Argument NV
void make_absolute(const Twine &current_directory, SmallVectorImpl< char > &path)
Make path an absolute path.
Definition: Path.cpp:907
std::error_code openFile(const Twine &Name, int &ResultFD, CreationDisposition Disp, FileAccess Access, OpenFlags Flags, unsigned Mode=0666)
Opens a file with the specified creation disposition, access mode, and flags and returns a file descr...
void expand_tilde(const Twine &path, SmallVectorImpl< char > &output)
Expands ~ expressions to the user's home directory.
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:758
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
@ CD_OpenAlways
CD_OpenAlways - When opening a file:
Definition: FileSystem.h:745
void createUniquePath(const Twine &Model, SmallVectorImpl< char > &ResultPath, bool MakeAbsolute)
Create a potentially unique file name but does not create it.
Definition: Path.cpp:797
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:968
StringRef parent_path(StringRef path, Style style=Style::native)
Get parent path.
Definition: Path.cpp:468
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:457
void AddSignalHandler(SignalHandlerCallback FnPtr, void *Cookie)
Add a function to be called when an abort/kill signal is delivered to the process.
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:32
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
ChangePrinter
Definition: PrintPasses.h:18
std::error_code prepareTempFiles(SmallVector< int > &FD, ArrayRef< StringRef > SR, SmallVector< std::string > &FileName)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition: STLExtras.h:1680
bool forcePrintModuleIR()
std::vector< std::string > printAfterPasses()
bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
Definition: Verifier.cpp:7128
auto successors(const MachineBasicBlock *BB)
bool DisplayGraph(StringRef Filename, bool wait=true, GraphProgram::Name program=GraphProgram::DOT)
auto formatv(const char *Fmt, Ts &&...Vals) -> formatv_object< decltype(std::make_tuple(support::detail::build_format_adapter(std::forward< Ts >(Vals))...))>
bool shouldPrintBeforeAll()
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
Definition: GraphWriter.h:359
bool shouldPrintAfterAll()
cl::opt< ChangePrinter > PrintChanged
TimeTraceProfiler * getTimeTraceProfilerInstance()
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
std::vector< std::string > printBeforePasses()
bool shouldPrintBeforeSomePass()
This is a helper to determine whether to print IR before or after a pass.
bool shouldPrintAfterSomePass()
void verifyMachineFunction(const std::string &Banner, const MachineFunction &MF)
IRHash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isFunctionInPrintList(StringRef FunctionName)
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
bool isPassInPrintList(StringRef PassName)
bool isSpecialPass(StringRef PassID, const std::vector< StringRef > &Specials)
void timeTraceProfilerEnd()
Manually end the last time section.
std::error_code cleanUpTempFiles(ArrayRef< std::string > FileName)
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void write_hex(raw_ostream &S, uint64_t N, HexPrintStyle Style, std::optional< size_t > Width=std::nullopt)
std::string doSystemDiff(StringRef Before, StringRef After, StringRef OldLineFormat, StringRef NewLineFormat, StringRef UnchangedLineFormat)
stable_hash stable_hash_combine_string(const StringRef &S)
Definition: StableHashing.h:99
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
std::array< uint32_t, 5 > ModuleHash
160 bits SHA1
uint64_t stable_hash
An opaque object representing a stable hash code.
Definition: StableHashing.h:24
std::string demangle(std::string_view MangledName)
Attempt to demangle a string using different demangling schemes.
Definition: Demangle.cpp:20
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
Definition: LoopInfo.cpp:989
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:7139
TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
#define N
Result run(Function &F, FunctionAnalysisManager &FAM)
Run the analysis pass over a function and produce CFG.
Result run(Function &F, FunctionAnalysisManager &FAM)
Result run(Module &F, ModuleAnalysisManager &FAM)
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition: PassManager.h:92
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: Analysis.h:28
static std::string getEdgeAttributes(const DisplayNode *From, DisplayNode::ChildIterator &To, const DotCfgDiffDisplayGraph *DiffData)
static std::string getGraphName(const DotCfgDiffDisplayGraph *DiffData)
static std::string getEdgeSourceLabel(const DisplayNode *From, DisplayNode::ChildIterator &To)
static std::string getNodeAttributes(const DisplayNode *Node, const DotCfgDiffDisplayGraph *DiffData)
static std::string getNodeLabel(const DisplayNode *Node, const DotCfgDiffDisplayGraph *DiffData)
static std::string getGraphProperties(const DotCfgDiffDisplayGraph *DiffData)
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
static unsigned size(const DotCfgDiffDisplayGraph *G)
static NodeRef getEntryNode(const DotCfgDiffDisplayGraph *G)
DotCfgDiffDisplayGraph::NodeIterator nodes_iterator
static nodes_iterator nodes_begin(const DotCfgDiffDisplayGraph *G)
static ChildEdgeIterator child_edge_begin(NodeRef N)
static nodes_iterator nodes_end(const DotCfgDiffDisplayGraph *G)
std::optional< DenseMap< intptr_t, BBGuard > > BBGuards
static void printDiff(raw_ostream &out, const CFG &Before, const CFG &After)
CFG(const Function *F, bool TrackBBLifetime)
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
DenseMap< const BasicBlock *, DenseMap< const BasicBlock *, unsigned > > Graph
bool SkipAnalyses
Don't print information for analyses.
bool Verbose
Print adaptors and pass managers.
bool Indent
Indent based on hierarchy.