1 //===- Standard pass instrumentations handling ----------------*- C++ -*--===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// 10 /// This file defines IR-printing pass instrumentation callbacks as well as 11 /// StandardInstrumentations class that manages standard pass instrumentations. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Passes/StandardInstrumentations.h" 16 #include "llvm/ADT/Any.h" 17 #include "llvm/ADT/Optional.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/Analysis/CallGraphSCCPass.h" 20 #include "llvm/Analysis/LazyCallGraph.h" 21 #include "llvm/Analysis/LoopInfo.h" 22 #include "llvm/IR/Function.h" 23 #include "llvm/IR/LegacyPassManager.h" 24 #include "llvm/IR/Module.h" 25 #include "llvm/IR/PassInstrumentation.h" 26 #include "llvm/IR/PassManager.h" 27 #include "llvm/IR/PrintPasses.h" 28 #include "llvm/IR/Verifier.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/FormatVariadic.h" 32 #include "llvm/Support/GraphWriter.h" 33 #include "llvm/Support/MemoryBuffer.h" 34 #include "llvm/Support/Program.h" 35 #include "llvm/Support/Regex.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <unordered_map> 38 #include <unordered_set> 39 #include <utility> 40 #include <vector> 41 42 using namespace llvm; 43 44 cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG( 45 "verify-cfg-preserved", cl::Hidden, 46 #ifdef NDEBUG 47 cl::init(false) 48 #else 49 cl::init(true) 50 #endif 51 ); 52 53 // An option that prints out the IR after passes, similar to 54 // -print-after-all except that it only prints the IR after passes that 55 // change the IR. Those passes that do not make changes to the IR are 56 // reported as not making any changes. In addition, the initial IR is 57 // also reported. Other hidden options affect the output from this 58 // option. -filter-passes will limit the output to the named passes 59 // that actually change the IR and other passes are reported as filtered out. 60 // The specified passes will either be reported as making no changes (with 61 // no IR reported) or the changed IR will be reported. Also, the 62 // -filter-print-funcs and -print-module-scope options will do similar 63 // filtering based on function name, reporting changed IRs as functions(or 64 // modules if -print-module-scope is specified) for a particular function 65 // or indicating that the IR has been filtered out. The extra options 66 // can be combined, allowing only changed IRs for certain passes on certain 67 // functions to be reported in different formats, with the rest being 68 // reported as filtered out. The -print-before-changed option will print 69 // the IR as it was before each pass that changed it. The optional 70 // value of quiet will only report when the IR changes, suppressing 71 // all other messages, including the initial IR. The values "diff" and 72 // "diff-quiet" will present the changes in a form similar to a patch, in 73 // either verbose or quiet mode, respectively. The lines that are removed 74 // and added are prefixed with '-' and '+', respectively. The 75 // -filter-print-funcs and -filter-passes can be used to filter the output. 76 // This reporter relies on the linux diff utility to do comparisons and 77 // insert the prefixes. For systems that do not have the necessary 78 // facilities, the error message will be shown in place of the expected output. 79 // 80 enum class ChangePrinter { 81 NoChangePrinter, 82 PrintChangedVerbose, 83 PrintChangedQuiet, 84 PrintChangedDiffVerbose, 85 PrintChangedDiffQuiet, 86 PrintChangedColourDiffVerbose, 87 PrintChangedColourDiffQuiet, 88 PrintChangedDotCfgVerbose, 89 PrintChangedDotCfgQuiet 90 }; 91 static cl::opt<ChangePrinter> PrintChanged( 92 "print-changed", cl::desc("Print changed IRs"), cl::Hidden, 93 cl::ValueOptional, cl::init(ChangePrinter::NoChangePrinter), 94 cl::values( 95 clEnumValN(ChangePrinter::PrintChangedQuiet, "quiet", 96 "Run in quiet mode"), 97 clEnumValN(ChangePrinter::PrintChangedDiffVerbose, "diff", 98 "Display patch-like changes"), 99 clEnumValN(ChangePrinter::PrintChangedDiffQuiet, "diff-quiet", 100 "Display patch-like changes in quiet mode"), 101 clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose, "cdiff", 102 "Display patch-like changes with color"), 103 clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet, "cdiff-quiet", 104 "Display patch-like changes in quiet mode with color"), 105 clEnumValN(ChangePrinter::PrintChangedDotCfgVerbose, "dot-cfg", 106 "Create a website with graphical changes"), 107 clEnumValN(ChangePrinter::PrintChangedDotCfgQuiet, "dot-cfg-quiet", 108 "Create a website with graphical changes in quiet mode"), 109 // Sentinel value for unspecified option. 110 clEnumValN(ChangePrinter::PrintChangedVerbose, "", ""))); 111 112 // An option that supports the -print-changed option. See 113 // the description for -print-changed for an explanation of the use 114 // of this option. Note that this option has no effect without -print-changed. 115 static cl::list<std::string> 116 PrintPassesList("filter-passes", cl::value_desc("pass names"), 117 cl::desc("Only consider IR changes for passes whose names " 118 "match for the print-changed option"), 119 cl::CommaSeparated, cl::Hidden); 120 // An option that supports the -print-changed option. See 121 // the description for -print-changed for an explanation of the use 122 // of this option. Note that this option has no effect without -print-changed. 123 static cl::opt<bool> 124 PrintChangedBefore("print-before-changed", 125 cl::desc("Print before passes that change them"), 126 cl::init(false), cl::Hidden); 127 128 // An option for specifying the diff used by print-changed=[diff | diff-quiet] 129 static cl::opt<std::string> 130 DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"), 131 cl::desc("system diff used by change reporters")); 132 133 // An option for specifying the dot used by 134 // print-changed=[dot-cfg | dot-cfg-quiet] 135 static cl::opt<std::string> 136 DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"), 137 cl::desc("system dot used by change reporters")); 138 139 // An option that determines the colour used for elements that are only 140 // in the before part. Must be a colour named in appendix J of 141 // https://graphviz.org/pdf/dotguide.pdf 142 cl::opt<std::string> 143 BeforeColour("dot-cfg-before-color", 144 cl::desc("Color for dot-cfg before elements."), cl::Hidden, 145 cl::init("red")); 146 // An option that determines the colour used for elements that are only 147 // in the after part. Must be a colour named in appendix J of 148 // https://graphviz.org/pdf/dotguide.pdf 149 cl::opt<std::string> AfterColour("dot-cfg-after-color", 150 cl::desc("Color for dot-cfg after elements."), 151 cl::Hidden, cl::init("forestgreen")); 152 // An option that determines the colour used for elements that are in both 153 // the before and after parts. Must be a colour named in appendix J of 154 // https://graphviz.org/pdf/dotguide.pdf 155 cl::opt<std::string> 156 CommonColour("dot-cfg-common-color", 157 cl::desc("Color for dot-cfg common elements."), cl::Hidden, 158 cl::init("black")); 159 160 // An option that determines where the generated website file (named 161 // passes.html) and the associated pdf files (named diff_*.pdf) are saved. 162 static cl::opt<std::string> DotCfgDir( 163 "dot-cfg-dir", 164 cl::desc("Generate dot files into specified directory for changed IRs"), 165 cl::Hidden, cl::init("./")); 166 167 namespace { 168 169 // Perform a system based diff between \p Before and \p After, using 170 // \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat 171 // to control the formatting of the output. Return an error message 172 // for any failures instead of the diff. 173 std::string doSystemDiff(StringRef Before, StringRef After, 174 StringRef OldLineFormat, StringRef NewLineFormat, 175 StringRef UnchangedLineFormat) { 176 StringRef SR[2]{Before, After}; 177 // Store the 2 bodies into temporary files and call diff on them 178 // to get the body of the node. 179 const unsigned NumFiles = 3; 180 static std::string FileName[NumFiles]; 181 static int FD[NumFiles]{-1, -1, -1}; 182 for (unsigned I = 0; I < NumFiles; ++I) { 183 if (FD[I] == -1) { 184 SmallVector<char, 200> SV; 185 std::error_code EC = 186 sys::fs::createTemporaryFile("tmpdiff", "txt", FD[I], SV); 187 if (EC) 188 return "Unable to create temporary file."; 189 FileName[I] = Twine(SV).str(); 190 } 191 // The third file is used as the result of the diff. 192 if (I == NumFiles - 1) 193 break; 194 195 std::error_code EC = sys::fs::openFileForWrite(FileName[I], FD[I]); 196 if (EC) 197 return "Unable to open temporary file for writing."; 198 199 raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true); 200 if (FD[I] == -1) 201 return "Error opening file for writing."; 202 OutStream << SR[I]; 203 } 204 205 static ErrorOr<std::string> DiffExe = sys::findProgramByName(DiffBinary); 206 if (!DiffExe) 207 return "Unable to find diff executable."; 208 209 SmallString<128> OLF = formatv("--old-line-format={0}", OldLineFormat); 210 SmallString<128> NLF = formatv("--new-line-format={0}", NewLineFormat); 211 SmallString<128> ULF = 212 formatv("--unchanged-line-format={0}", UnchangedLineFormat); 213 214 StringRef Args[] = {DiffBinary, "-w", "-d", OLF, 215 NLF, ULF, FileName[0], FileName[1]}; 216 Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None}; 217 int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects); 218 if (Result < 0) 219 return "Error executing system diff."; 220 std::string Diff; 221 auto B = MemoryBuffer::getFile(FileName[2]); 222 if (B && *B) 223 Diff = (*B)->getBuffer().str(); 224 else 225 return "Unable to read result."; 226 227 // Clean up. 228 for (unsigned I = 0; I < NumFiles; ++I) { 229 std::error_code EC = sys::fs::remove(FileName[I]); 230 if (EC) 231 return "Unable to remove temporary file."; 232 } 233 return Diff; 234 } 235 236 /// Extract Module out of \p IR unit. May return nullptr if \p IR does not match 237 /// certain global filters. Will never return nullptr if \p Force is true. 238 const Module *unwrapModule(Any IR, bool Force = false) { 239 if (any_isa<const Module *>(IR)) 240 return any_cast<const Module *>(IR); 241 242 if (any_isa<const Function *>(IR)) { 243 const Function *F = any_cast<const Function *>(IR); 244 if (!Force && !isFunctionInPrintList(F->getName())) 245 return nullptr; 246 247 return F->getParent(); 248 } 249 250 if (any_isa<const LazyCallGraph::SCC *>(IR)) { 251 const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR); 252 for (const LazyCallGraph::Node &N : *C) { 253 const Function &F = N.getFunction(); 254 if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) { 255 return F.getParent(); 256 } 257 } 258 assert(!Force && "Expected a module"); 259 return nullptr; 260 } 261 262 if (any_isa<const Loop *>(IR)) { 263 const Loop *L = any_cast<const Loop *>(IR); 264 const Function *F = L->getHeader()->getParent(); 265 if (!Force && !isFunctionInPrintList(F->getName())) 266 return nullptr; 267 return F->getParent(); 268 } 269 270 llvm_unreachable("Unknown IR unit"); 271 } 272 273 void printIR(raw_ostream &OS, const Function *F) { 274 if (!isFunctionInPrintList(F->getName())) 275 return; 276 OS << *F; 277 } 278 279 void printIR(raw_ostream &OS, const Module *M) { 280 if (isFunctionInPrintList("*") || forcePrintModuleIR()) { 281 M->print(OS, nullptr); 282 } else { 283 for (const auto &F : M->functions()) { 284 printIR(OS, &F); 285 } 286 } 287 } 288 289 void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) { 290 for (const LazyCallGraph::Node &N : *C) { 291 const Function &F = N.getFunction(); 292 if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) { 293 F.print(OS); 294 } 295 } 296 } 297 298 void printIR(raw_ostream &OS, const Loop *L) { 299 const Function *F = L->getHeader()->getParent(); 300 if (!isFunctionInPrintList(F->getName())) 301 return; 302 printLoop(const_cast<Loop &>(*L), OS); 303 } 304 305 std::string getIRName(Any IR) { 306 if (any_isa<const Module *>(IR)) 307 return "[module]"; 308 309 if (any_isa<const Function *>(IR)) { 310 const Function *F = any_cast<const Function *>(IR); 311 return F->getName().str(); 312 } 313 314 if (any_isa<const LazyCallGraph::SCC *>(IR)) { 315 const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR); 316 return C->getName(); 317 } 318 319 if (any_isa<const Loop *>(IR)) { 320 const Loop *L = any_cast<const Loop *>(IR); 321 std::string S; 322 raw_string_ostream OS(S); 323 L->print(OS, /*Verbose*/ false, /*PrintNested*/ false); 324 return OS.str(); 325 } 326 327 llvm_unreachable("Unknown wrapped IR type"); 328 } 329 330 bool moduleContainsFilterPrintFunc(const Module &M) { 331 return any_of(M.functions(), 332 [](const Function &F) { 333 return isFunctionInPrintList(F.getName()); 334 }) || 335 isFunctionInPrintList("*"); 336 } 337 338 bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) { 339 return any_of(C, 340 [](const LazyCallGraph::Node &N) { 341 return isFunctionInPrintList(N.getName()); 342 }) || 343 isFunctionInPrintList("*"); 344 } 345 346 bool shouldPrintIR(Any IR) { 347 if (any_isa<const Module *>(IR)) { 348 const Module *M = any_cast<const Module *>(IR); 349 return moduleContainsFilterPrintFunc(*M); 350 } 351 352 if (any_isa<const Function *>(IR)) { 353 const Function *F = any_cast<const Function *>(IR); 354 return isFunctionInPrintList(F->getName()); 355 } 356 357 if (any_isa<const LazyCallGraph::SCC *>(IR)) { 358 const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR); 359 return sccContainsFilterPrintFunc(*C); 360 } 361 362 if (any_isa<const Loop *>(IR)) { 363 const Loop *L = any_cast<const Loop *>(IR); 364 return isFunctionInPrintList(L->getHeader()->getParent()->getName()); 365 } 366 llvm_unreachable("Unknown wrapped IR type"); 367 } 368 369 /// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into 370 /// llvm::Any and does actual print job. 371 void unwrapAndPrint(raw_ostream &OS, Any IR) { 372 if (!shouldPrintIR(IR)) 373 return; 374 375 if (forcePrintModuleIR()) { 376 auto *M = unwrapModule(IR); 377 assert(M && "should have unwrapped module"); 378 printIR(OS, M); 379 return; 380 } 381 382 if (any_isa<const Module *>(IR)) { 383 const Module *M = any_cast<const Module *>(IR); 384 printIR(OS, M); 385 return; 386 } 387 388 if (any_isa<const Function *>(IR)) { 389 const Function *F = any_cast<const Function *>(IR); 390 printIR(OS, F); 391 return; 392 } 393 394 if (any_isa<const LazyCallGraph::SCC *>(IR)) { 395 const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR); 396 printIR(OS, C); 397 return; 398 } 399 400 if (any_isa<const Loop *>(IR)) { 401 const Loop *L = any_cast<const Loop *>(IR); 402 printIR(OS, L); 403 return; 404 } 405 llvm_unreachable("Unknown wrapped IR type"); 406 } 407 408 // Return true when this is a pass for which changes should be ignored 409 bool isIgnored(StringRef PassID) { 410 return isSpecialPass(PassID, 411 {"PassManager", "PassAdaptor", "AnalysisManagerProxy", 412 "DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass"}); 413 } 414 415 std::string makeHTMLReady(StringRef SR) { 416 std::string S; 417 while (true) { 418 StringRef Clean = 419 SR.take_until([](char C) { return C == '<' || C == '>'; }); 420 S.append(Clean.str()); 421 SR = SR.drop_front(Clean.size()); 422 if (SR.size() == 0) 423 return S; 424 S.append(SR[0] == '<' ? "<" : ">"); 425 SR = SR.drop_front(); 426 } 427 llvm_unreachable("problems converting string to HTML"); 428 } 429 430 // Return the module when that is the appropriate level of comparison for \p IR. 431 const Module *getModuleForComparison(Any IR) { 432 if (any_isa<const Module *>(IR)) 433 return any_cast<const Module *>(IR); 434 if (any_isa<const LazyCallGraph::SCC *>(IR)) 435 return any_cast<const LazyCallGraph::SCC *>(IR) 436 ->begin() 437 ->getFunction() 438 .getParent(); 439 return nullptr; 440 } 441 442 } // namespace 443 444 template <typename T> ChangeReporter<T>::~ChangeReporter<T>() { 445 assert(BeforeStack.empty() && "Problem with Change Printer stack."); 446 } 447 448 template <typename T> 449 bool ChangeReporter<T>::isInterestingFunction(const Function &F) { 450 return isFunctionInPrintList(F.getName()); 451 } 452 453 template <typename T> 454 bool ChangeReporter<T>::isInterestingPass(StringRef PassID) { 455 if (isIgnored(PassID)) 456 return false; 457 458 static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(), 459 PrintPassesList.end()); 460 return PrintPassNames.empty() || PrintPassNames.count(PassID.str()); 461 } 462 463 // Return true when this is a pass on IR for which printing 464 // of changes is desired. 465 template <typename T> 466 bool ChangeReporter<T>::isInteresting(Any IR, StringRef PassID) { 467 if (!isInterestingPass(PassID)) 468 return false; 469 if (any_isa<const Function *>(IR)) 470 return isInterestingFunction(*any_cast<const Function *>(IR)); 471 return true; 472 } 473 474 template <typename T> 475 void ChangeReporter<T>::saveIRBeforePass(Any IR, StringRef PassID) { 476 // Always need to place something on the stack because invalidated passes 477 // are not given the IR so it cannot be determined whether the pass was for 478 // something that was filtered out. 479 BeforeStack.emplace_back(); 480 481 if (!isInteresting(IR, PassID)) 482 return; 483 // Is this the initial IR? 484 if (InitialIR) { 485 InitialIR = false; 486 if (VerboseMode) 487 handleInitialIR(IR); 488 } 489 490 // Save the IR representation on the stack. 491 T &Data = BeforeStack.back(); 492 generateIRRepresentation(IR, PassID, Data); 493 } 494 495 template <typename T> 496 void ChangeReporter<T>::handleIRAfterPass(Any IR, StringRef PassID) { 497 assert(!BeforeStack.empty() && "Unexpected empty stack encountered."); 498 499 std::string Name = getIRName(IR); 500 501 if (isIgnored(PassID)) { 502 if (VerboseMode) 503 handleIgnored(PassID, Name); 504 } else if (!isInteresting(IR, PassID)) { 505 if (VerboseMode) 506 handleFiltered(PassID, Name); 507 } else { 508 // Get the before rep from the stack 509 T &Before = BeforeStack.back(); 510 // Create the after rep 511 T After; 512 generateIRRepresentation(IR, PassID, After); 513 514 // Was there a change in IR? 515 if (Before == After) { 516 if (VerboseMode) 517 omitAfter(PassID, Name); 518 } else 519 handleAfter(PassID, Name, Before, After, IR); 520 } 521 BeforeStack.pop_back(); 522 } 523 524 template <typename T> 525 void ChangeReporter<T>::handleInvalidatedPass(StringRef PassID) { 526 assert(!BeforeStack.empty() && "Unexpected empty stack encountered."); 527 528 // Always flag it as invalidated as we cannot determine when 529 // a pass for a filtered function is invalidated since we do not 530 // get the IR in the call. Also, the output is just alternate 531 // forms of the banner anyway. 532 if (VerboseMode) 533 handleInvalidated(PassID); 534 BeforeStack.pop_back(); 535 } 536 537 template <typename T> 538 void ChangeReporter<T>::registerRequiredCallbacks( 539 PassInstrumentationCallbacks &PIC) { 540 PIC.registerBeforeNonSkippedPassCallback( 541 [this](StringRef P, Any IR) { saveIRBeforePass(IR, P); }); 542 543 PIC.registerAfterPassCallback( 544 [this](StringRef P, Any IR, const PreservedAnalyses &) { 545 handleIRAfterPass(IR, P); 546 }); 547 PIC.registerAfterPassInvalidatedCallback( 548 [this](StringRef P, const PreservedAnalyses &) { 549 handleInvalidatedPass(P); 550 }); 551 } 552 553 template <typename T> 554 TextChangeReporter<T>::TextChangeReporter(bool Verbose) 555 : ChangeReporter<T>(Verbose), Out(dbgs()) {} 556 557 template <typename T> void TextChangeReporter<T>::handleInitialIR(Any IR) { 558 // Always print the module. 559 // Unwrap and print directly to avoid filtering problems in general routines. 560 auto *M = unwrapModule(IR, /*Force=*/true); 561 assert(M && "Expected module to be unwrapped when forced."); 562 Out << "*** IR Dump At Start ***\n"; 563 M->print(Out, nullptr); 564 } 565 566 template <typename T> 567 void TextChangeReporter<T>::omitAfter(StringRef PassID, std::string &Name) { 568 Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n", 569 PassID, Name); 570 } 571 572 template <typename T> 573 void TextChangeReporter<T>::handleInvalidated(StringRef PassID) { 574 Out << formatv("*** IR Pass {0} invalidated ***\n", PassID); 575 } 576 577 template <typename T> 578 void TextChangeReporter<T>::handleFiltered(StringRef PassID, 579 std::string &Name) { 580 SmallString<20> Banner = 581 formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name); 582 Out << Banner; 583 } 584 585 template <typename T> 586 void TextChangeReporter<T>::handleIgnored(StringRef PassID, std::string &Name) { 587 Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name); 588 } 589 590 IRChangedPrinter::~IRChangedPrinter() {} 591 592 void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) { 593 if (PrintChanged == ChangePrinter::PrintChangedVerbose || 594 PrintChanged == ChangePrinter::PrintChangedQuiet) 595 TextChangeReporter<std::string>::registerRequiredCallbacks(PIC); 596 } 597 598 void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID, 599 std::string &Output) { 600 raw_string_ostream OS(Output); 601 unwrapAndPrint(OS, IR); 602 OS.str(); 603 } 604 605 void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name, 606 const std::string &Before, 607 const std::string &After, Any) { 608 // Report the IR before the changes when requested. 609 if (PrintChangedBefore) 610 Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n" 611 << Before; 612 613 // We might not get anything to print if we only want to print a specific 614 // function but it gets deleted. 615 if (After.empty()) { 616 Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n"; 617 return; 618 } 619 620 Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After; 621 } 622 623 template <typename T> 624 void OrderedChangedData<T>::report( 625 const OrderedChangedData &Before, const OrderedChangedData &After, 626 function_ref<void(const T *, const T *)> HandlePair) { 627 const auto &BFD = Before.getData(); 628 const auto &AFD = After.getData(); 629 std::vector<std::string>::const_iterator BI = Before.getOrder().begin(); 630 std::vector<std::string>::const_iterator BE = Before.getOrder().end(); 631 std::vector<std::string>::const_iterator AI = After.getOrder().begin(); 632 std::vector<std::string>::const_iterator AE = After.getOrder().end(); 633 634 auto HandlePotentiallyRemovedData = [&](std::string S) { 635 // The order in LLVM may have changed so check if still exists. 636 if (!AFD.count(S)) { 637 // This has been removed. 638 HandlePair(&BFD.find(*BI)->getValue(), nullptr); 639 } 640 }; 641 auto HandleNewData = [&](std::vector<const T *> &Q) { 642 // Print out any queued up new sections 643 for (const T *NBI : Q) 644 HandlePair(nullptr, NBI); 645 Q.clear(); 646 }; 647 648 // Print out the data in the after order, with before ones interspersed 649 // appropriately (ie, somewhere near where they were in the before list). 650 // Start at the beginning of both lists. Loop through the 651 // after list. If an element is common, then advance in the before list 652 // reporting the removed ones until the common one is reached. Report any 653 // queued up new ones and then report the common one. If an element is not 654 // common, then enqueue it for reporting. When the after list is exhausted, 655 // loop through the before list, reporting any removed ones. Finally, 656 // report the rest of the enqueued new ones. 657 std::vector<const T *> NewDataQueue; 658 while (AI != AE) { 659 if (!BFD.count(*AI)) { 660 // This section is new so place it in the queue. This will cause it 661 // to be reported after deleted sections. 662 NewDataQueue.emplace_back(&AFD.find(*AI)->getValue()); 663 ++AI; 664 continue; 665 } 666 // This section is in both; advance and print out any before-only 667 // until we get to it. 668 while (*BI != *AI) { 669 HandlePotentiallyRemovedData(*BI); 670 ++BI; 671 } 672 // Report any new sections that were queued up and waiting. 673 HandleNewData(NewDataQueue); 674 675 const T &AData = AFD.find(*AI)->getValue(); 676 const T &BData = BFD.find(*AI)->getValue(); 677 HandlePair(&BData, &AData); 678 ++BI; 679 ++AI; 680 } 681 682 // Check any remaining before sections to see if they have been removed 683 while (BI != BE) { 684 HandlePotentiallyRemovedData(*BI); 685 ++BI; 686 } 687 688 HandleNewData(NewDataQueue); 689 } 690 691 template <typename T> 692 void IRComparer<T>::compare( 693 bool CompareModule, 694 std::function<void(bool InModule, unsigned Minor, 695 const FuncDataT<T> &Before, const FuncDataT<T> &After)> 696 CompareFunc) { 697 if (!CompareModule) { 698 // Just handle the single function. 699 assert(Before.getData().size() == 1 && After.getData().size() == 1 && 700 "Expected only one function."); 701 CompareFunc(false, 0, Before.getData().begin()->getValue(), 702 After.getData().begin()->getValue()); 703 return; 704 } 705 706 unsigned Minor = 0; 707 FuncDataT<T> Missing(""); 708 IRDataT<T>::report(Before, After, 709 [&](const FuncDataT<T> *B, const FuncDataT<T> *A) { 710 assert((B || A) && "Both functions cannot be missing."); 711 if (!B) 712 B = &Missing; 713 else if (!A) 714 A = &Missing; 715 CompareFunc(true, Minor++, *B, *A); 716 }); 717 } 718 719 template <typename T> void IRComparer<T>::analyzeIR(Any IR, IRDataT<T> &Data) { 720 if (const Module *M = getModuleForComparison(IR)) { 721 // Create data for each existing/interesting function in the module. 722 for (const Function &F : *M) 723 generateFunctionData(Data, F); 724 return; 725 } 726 727 const Function *F = nullptr; 728 if (any_isa<const Function *>(IR)) 729 F = any_cast<const Function *>(IR); 730 else { 731 assert(any_isa<const Loop *>(IR) && "Unknown IR unit."); 732 const Loop *L = any_cast<const Loop *>(IR); 733 F = L->getHeader()->getParent(); 734 } 735 assert(F && "Unknown IR unit."); 736 generateFunctionData(Data, *F); 737 } 738 739 template <typename T> 740 bool IRComparer<T>::generateFunctionData(IRDataT<T> &Data, const Function &F) { 741 if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) { 742 FuncDataT<T> FD(F.getEntryBlock().getName().str()); 743 for (const auto &B : F) { 744 FD.getOrder().emplace_back(B.getName()); 745 FD.getData().insert({B.getName(), B}); 746 } 747 Data.getOrder().emplace_back(F.getName()); 748 Data.getData().insert({F.getName(), FD}); 749 return true; 750 } 751 return false; 752 } 753 754 PrintIRInstrumentation::~PrintIRInstrumentation() { 755 assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit"); 756 } 757 758 void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) { 759 const Module *M = unwrapModule(IR); 760 ModuleDescStack.emplace_back(M, getIRName(IR), PassID); 761 } 762 763 PrintIRInstrumentation::PrintModuleDesc 764 PrintIRInstrumentation::popModuleDesc(StringRef PassID) { 765 assert(!ModuleDescStack.empty() && "empty ModuleDescStack"); 766 PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val(); 767 assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack"); 768 return ModuleDesc; 769 } 770 771 void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) { 772 if (isIgnored(PassID)) 773 return; 774 775 // Saving Module for AfterPassInvalidated operations. 776 // Note: here we rely on a fact that we do not change modules while 777 // traversing the pipeline, so the latest captured module is good 778 // for all print operations that has not happen yet. 779 if (shouldPrintAfterPass(PassID)) 780 pushModuleDesc(PassID, IR); 781 782 if (!shouldPrintBeforePass(PassID)) 783 return; 784 785 if (!shouldPrintIR(IR)) 786 return; 787 788 dbgs() << "*** IR Dump Before " << PassID << " on " << getIRName(IR) 789 << " ***\n"; 790 unwrapAndPrint(dbgs(), IR); 791 } 792 793 void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) { 794 if (isIgnored(PassID)) 795 return; 796 797 if (!shouldPrintAfterPass(PassID)) 798 return; 799 800 const Module *M; 801 std::string IRName; 802 StringRef StoredPassID; 803 std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID); 804 assert(StoredPassID == PassID && "mismatched PassID"); 805 806 if (!shouldPrintIR(IR)) 807 return; 808 809 dbgs() << "*** IR Dump After " << PassID << " on " << IRName << " ***\n"; 810 unwrapAndPrint(dbgs(), IR); 811 } 812 813 void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) { 814 StringRef PassName = PIC->getPassNameForClassName(PassID); 815 if (!shouldPrintAfterPass(PassName)) 816 return; 817 818 if (isIgnored(PassID)) 819 return; 820 821 const Module *M; 822 std::string IRName; 823 StringRef StoredPassID; 824 std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID); 825 assert(StoredPassID == PassID && "mismatched PassID"); 826 // Additional filtering (e.g. -filter-print-func) can lead to module 827 // printing being skipped. 828 if (!M) 829 return; 830 831 SmallString<20> Banner = 832 formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID, IRName); 833 dbgs() << Banner << "\n"; 834 printIR(dbgs(), M); 835 } 836 837 bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) { 838 if (shouldPrintBeforeAll()) 839 return true; 840 841 StringRef PassName = PIC->getPassNameForClassName(PassID); 842 return is_contained(printBeforePasses(), PassName); 843 } 844 845 bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) { 846 if (shouldPrintAfterAll()) 847 return true; 848 849 StringRef PassName = PIC->getPassNameForClassName(PassID); 850 return is_contained(printAfterPasses(), PassName); 851 } 852 853 void PrintIRInstrumentation::registerCallbacks( 854 PassInstrumentationCallbacks &PIC) { 855 this->PIC = &PIC; 856 857 // BeforePass callback is not just for printing, it also saves a Module 858 // for later use in AfterPassInvalidated. 859 if (shouldPrintBeforeSomePass() || shouldPrintAfterSomePass()) 860 PIC.registerBeforeNonSkippedPassCallback( 861 [this](StringRef P, Any IR) { this->printBeforePass(P, IR); }); 862 863 if (shouldPrintAfterSomePass()) { 864 PIC.registerAfterPassCallback( 865 [this](StringRef P, Any IR, const PreservedAnalyses &) { 866 this->printAfterPass(P, IR); 867 }); 868 PIC.registerAfterPassInvalidatedCallback( 869 [this](StringRef P, const PreservedAnalyses &) { 870 this->printAfterPassInvalidated(P); 871 }); 872 } 873 } 874 875 void OptNoneInstrumentation::registerCallbacks( 876 PassInstrumentationCallbacks &PIC) { 877 PIC.registerShouldRunOptionalPassCallback( 878 [this](StringRef P, Any IR) { return this->shouldRun(P, IR); }); 879 } 880 881 bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) { 882 const Function *F = nullptr; 883 if (any_isa<const Function *>(IR)) { 884 F = any_cast<const Function *>(IR); 885 } else if (any_isa<const Loop *>(IR)) { 886 F = any_cast<const Loop *>(IR)->getHeader()->getParent(); 887 } 888 bool ShouldRun = !(F && F->hasOptNone()); 889 if (!ShouldRun && DebugLogging) { 890 errs() << "Skipping pass " << PassID << " on " << F->getName() 891 << " due to optnone attribute\n"; 892 } 893 return ShouldRun; 894 } 895 896 void OptBisectInstrumentation::registerCallbacks( 897 PassInstrumentationCallbacks &PIC) { 898 if (!OptBisector->isEnabled()) 899 return; 900 PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) { 901 return isIgnored(PassID) || OptBisector->checkPass(PassID, getIRName(IR)); 902 }); 903 } 904 905 raw_ostream &PrintPassInstrumentation::print() { 906 if (Opts.Indent) { 907 assert(Indent >= 0); 908 dbgs().indent(Indent); 909 } 910 return dbgs(); 911 } 912 913 void PrintPassInstrumentation::registerCallbacks( 914 PassInstrumentationCallbacks &PIC) { 915 if (!Enabled) 916 return; 917 918 std::vector<StringRef> SpecialPasses; 919 if (!Opts.Verbose) { 920 SpecialPasses.emplace_back("PassManager"); 921 SpecialPasses.emplace_back("PassAdaptor"); 922 } 923 924 PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID, 925 Any IR) { 926 assert(!isSpecialPass(PassID, SpecialPasses) && 927 "Unexpectedly skipping special pass"); 928 929 print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n"; 930 }); 931 PIC.registerBeforeNonSkippedPassCallback([this, SpecialPasses]( 932 StringRef PassID, Any IR) { 933 if (isSpecialPass(PassID, SpecialPasses)) 934 return; 935 936 print() << "Running pass: " << PassID << " on " << getIRName(IR) << "\n"; 937 Indent += 2; 938 }); 939 PIC.registerAfterPassCallback( 940 [this, SpecialPasses](StringRef PassID, Any IR, 941 const PreservedAnalyses &) { 942 if (isSpecialPass(PassID, SpecialPasses)) 943 return; 944 945 Indent -= 2; 946 }); 947 PIC.registerAfterPassInvalidatedCallback( 948 [this, SpecialPasses](StringRef PassID, Any IR) { 949 if (isSpecialPass(PassID, SpecialPasses)) 950 return; 951 952 Indent -= 2; 953 }); 954 955 if (!Opts.SkipAnalyses) { 956 PIC.registerBeforeAnalysisCallback([this](StringRef PassID, Any IR) { 957 print() << "Running analysis: " << PassID << " on " << getIRName(IR) 958 << "\n"; 959 Indent += 2; 960 }); 961 PIC.registerAfterAnalysisCallback( 962 [this](StringRef PassID, Any IR) { Indent -= 2; }); 963 PIC.registerAnalysisInvalidatedCallback([this](StringRef PassID, Any IR) { 964 print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR) 965 << "\n"; 966 }); 967 PIC.registerAnalysesClearedCallback([this](StringRef IRName) { 968 print() << "Clearing all analysis results for: " << IRName << "\n"; 969 }); 970 } 971 } 972 973 PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F, 974 bool TrackBBLifetime) { 975 if (TrackBBLifetime) 976 BBGuards = DenseMap<intptr_t, BBGuard>(F->size()); 977 for (const auto &BB : *F) { 978 if (BBGuards) 979 BBGuards->try_emplace(intptr_t(&BB), &BB); 980 for (auto *Succ : successors(&BB)) { 981 Graph[&BB][Succ]++; 982 if (BBGuards) 983 BBGuards->try_emplace(intptr_t(Succ), Succ); 984 } 985 } 986 } 987 988 static void printBBName(raw_ostream &out, const BasicBlock *BB) { 989 if (BB->hasName()) { 990 out << BB->getName() << "<" << BB << ">"; 991 return; 992 } 993 994 if (!BB->getParent()) { 995 out << "unnamed_removed<" << BB << ">"; 996 return; 997 } 998 999 if (BB->isEntryBlock()) { 1000 out << "entry" 1001 << "<" << BB << ">"; 1002 return; 1003 } 1004 1005 unsigned FuncOrderBlockNum = 0; 1006 for (auto &FuncBB : *BB->getParent()) { 1007 if (&FuncBB == BB) 1008 break; 1009 FuncOrderBlockNum++; 1010 } 1011 out << "unnamed_" << FuncOrderBlockNum << "<" << BB << ">"; 1012 } 1013 1014 void PreservedCFGCheckerInstrumentation::CFG::printDiff(raw_ostream &out, 1015 const CFG &Before, 1016 const CFG &After) { 1017 assert(!After.isPoisoned()); 1018 if (Before.isPoisoned()) { 1019 out << "Some blocks were deleted\n"; 1020 return; 1021 } 1022 1023 // Find and print graph differences. 1024 if (Before.Graph.size() != After.Graph.size()) 1025 out << "Different number of non-leaf basic blocks: before=" 1026 << Before.Graph.size() << ", after=" << After.Graph.size() << "\n"; 1027 1028 for (auto &BB : Before.Graph) { 1029 auto BA = After.Graph.find(BB.first); 1030 if (BA == After.Graph.end()) { 1031 out << "Non-leaf block "; 1032 printBBName(out, BB.first); 1033 out << " is removed (" << BB.second.size() << " successors)\n"; 1034 } 1035 } 1036 1037 for (auto &BA : After.Graph) { 1038 auto BB = Before.Graph.find(BA.first); 1039 if (BB == Before.Graph.end()) { 1040 out << "Non-leaf block "; 1041 printBBName(out, BA.first); 1042 out << " is added (" << BA.second.size() << " successors)\n"; 1043 continue; 1044 } 1045 1046 if (BB->second == BA.second) 1047 continue; 1048 1049 out << "Different successors of block "; 1050 printBBName(out, BA.first); 1051 out << " (unordered):\n"; 1052 out << "- before (" << BB->second.size() << "): "; 1053 for (auto &SuccB : BB->second) { 1054 printBBName(out, SuccB.first); 1055 if (SuccB.second != 1) 1056 out << "(" << SuccB.second << "), "; 1057 else 1058 out << ", "; 1059 } 1060 out << "\n"; 1061 out << "- after (" << BA.second.size() << "): "; 1062 for (auto &SuccA : BA.second) { 1063 printBBName(out, SuccA.first); 1064 if (SuccA.second != 1) 1065 out << "(" << SuccA.second << "), "; 1066 else 1067 out << ", "; 1068 } 1069 out << "\n"; 1070 } 1071 } 1072 1073 // PreservedCFGCheckerInstrumentation uses PreservedCFGCheckerAnalysis to check 1074 // passes, that reported they kept CFG analyses up-to-date, did not actually 1075 // change CFG. This check is done as follows. Before every functional pass in 1076 // BeforeNonSkippedPassCallback a CFG snapshot (an instance of 1077 // PreservedCFGCheckerInstrumentation::CFG) is requested from 1078 // FunctionAnalysisManager as a result of PreservedCFGCheckerAnalysis. When the 1079 // functional pass finishes and reports that CFGAnalyses or AllAnalyses are 1080 // up-to-date then the cached result of PreservedCFGCheckerAnalysis (if 1081 // available) is checked to be equal to a freshly created CFG snapshot. 1082 struct PreservedCFGCheckerAnalysis 1083 : public AnalysisInfoMixin<PreservedCFGCheckerAnalysis> { 1084 friend AnalysisInfoMixin<PreservedCFGCheckerAnalysis>; 1085 1086 static AnalysisKey Key; 1087 1088 public: 1089 /// Provide the result type for this analysis pass. 1090 using Result = PreservedCFGCheckerInstrumentation::CFG; 1091 1092 /// Run the analysis pass over a function and produce CFG. 1093 Result run(Function &F, FunctionAnalysisManager &FAM) { 1094 return Result(&F, /* TrackBBLifetime */ true); 1095 } 1096 }; 1097 1098 AnalysisKey PreservedCFGCheckerAnalysis::Key; 1099 1100 bool PreservedCFGCheckerInstrumentation::CFG::invalidate( 1101 Function &F, const PreservedAnalyses &PA, 1102 FunctionAnalysisManager::Invalidator &) { 1103 auto PAC = PA.getChecker<PreservedCFGCheckerAnalysis>(); 1104 return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() || 1105 PAC.preservedSet<CFGAnalyses>()); 1106 } 1107 1108 void PreservedCFGCheckerInstrumentation::registerCallbacks( 1109 PassInstrumentationCallbacks &PIC, FunctionAnalysisManager &FAM) { 1110 if (!VerifyPreservedCFG) 1111 return; 1112 1113 FAM.registerPass([&] { return PreservedCFGCheckerAnalysis(); }); 1114 1115 auto checkCFG = [](StringRef Pass, StringRef FuncName, const CFG &GraphBefore, 1116 const CFG &GraphAfter) { 1117 if (GraphAfter == GraphBefore) 1118 return; 1119 1120 dbgs() << "Error: " << Pass 1121 << " does not invalidate CFG analyses but CFG changes detected in " 1122 "function @" 1123 << FuncName << ":\n"; 1124 CFG::printDiff(dbgs(), GraphBefore, GraphAfter); 1125 report_fatal_error(Twine("CFG unexpectedly changed by ", Pass)); 1126 }; 1127 1128 PIC.registerBeforeNonSkippedPassCallback([this, &FAM](StringRef P, Any IR) { 1129 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS 1130 assert(&PassStack.emplace_back(P)); 1131 #endif 1132 (void)this; 1133 if (!any_isa<const Function *>(IR)) 1134 return; 1135 1136 const auto *F = any_cast<const Function *>(IR); 1137 // Make sure a fresh CFG snapshot is available before the pass. 1138 FAM.getResult<PreservedCFGCheckerAnalysis>(*const_cast<Function *>(F)); 1139 }); 1140 1141 PIC.registerAfterPassInvalidatedCallback( 1142 [this](StringRef P, const PreservedAnalyses &PassPA) { 1143 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS 1144 assert(PassStack.pop_back_val() == P && 1145 "Before and After callbacks must correspond"); 1146 #endif 1147 (void)this; 1148 }); 1149 1150 PIC.registerAfterPassCallback([this, &FAM, 1151 checkCFG](StringRef P, Any IR, 1152 const PreservedAnalyses &PassPA) { 1153 #ifdef LLVM_ENABLE_ABI_BREAKING_CHECKS 1154 assert(PassStack.pop_back_val() == P && 1155 "Before and After callbacks must correspond"); 1156 #endif 1157 (void)this; 1158 1159 if (!any_isa<const Function *>(IR)) 1160 return; 1161 1162 if (!PassPA.allAnalysesInSetPreserved<CFGAnalyses>() && 1163 !PassPA.allAnalysesInSetPreserved<AllAnalysesOn<Function>>()) 1164 return; 1165 1166 const auto *F = any_cast<const Function *>(IR); 1167 if (auto *GraphBefore = FAM.getCachedResult<PreservedCFGCheckerAnalysis>( 1168 *const_cast<Function *>(F))) 1169 checkCFG(P, F->getName(), *GraphBefore, 1170 CFG(F, /* TrackBBLifetime */ false)); 1171 }); 1172 } 1173 1174 void VerifyInstrumentation::registerCallbacks( 1175 PassInstrumentationCallbacks &PIC) { 1176 PIC.registerAfterPassCallback( 1177 [this](StringRef P, Any IR, const PreservedAnalyses &PassPA) { 1178 if (isIgnored(P) || P == "VerifierPass") 1179 return; 1180 if (any_isa<const Function *>(IR) || any_isa<const Loop *>(IR)) { 1181 const Function *F; 1182 if (any_isa<const Loop *>(IR)) 1183 F = any_cast<const Loop *>(IR)->getHeader()->getParent(); 1184 else 1185 F = any_cast<const Function *>(IR); 1186 if (DebugLogging) 1187 dbgs() << "Verifying function " << F->getName() << "\n"; 1188 1189 if (verifyFunction(*F)) 1190 report_fatal_error("Broken function found, compilation aborted!"); 1191 } else if (any_isa<const Module *>(IR) || 1192 any_isa<const LazyCallGraph::SCC *>(IR)) { 1193 const Module *M; 1194 if (any_isa<const LazyCallGraph::SCC *>(IR)) 1195 M = any_cast<const LazyCallGraph::SCC *>(IR) 1196 ->begin() 1197 ->getFunction() 1198 .getParent(); 1199 else 1200 M = any_cast<const Module *>(IR); 1201 if (DebugLogging) 1202 dbgs() << "Verifying module " << M->getName() << "\n"; 1203 1204 if (verifyModule(*M)) 1205 report_fatal_error("Broken module found, compilation aborted!"); 1206 } 1207 }); 1208 } 1209 1210 InLineChangePrinter::~InLineChangePrinter() {} 1211 1212 void InLineChangePrinter::generateIRRepresentation(Any IR, StringRef PassID, 1213 IRDataT<EmptyData> &D) { 1214 IRComparer<EmptyData>::analyzeIR(IR, D); 1215 } 1216 1217 void InLineChangePrinter::handleAfter(StringRef PassID, std::string &Name, 1218 const IRDataT<EmptyData> &Before, 1219 const IRDataT<EmptyData> &After, Any IR) { 1220 SmallString<20> Banner = 1221 formatv("*** IR Dump After {0} on {1} ***\n", PassID, Name); 1222 Out << Banner; 1223 IRComparer<EmptyData>(Before, After) 1224 .compare(getModuleForComparison(IR), 1225 [&](bool InModule, unsigned Minor, 1226 const FuncDataT<EmptyData> &Before, 1227 const FuncDataT<EmptyData> &After) -> void { 1228 handleFunctionCompare(Name, "", PassID, " on ", InModule, 1229 Minor, Before, After); 1230 }); 1231 Out << "\n"; 1232 } 1233 1234 void InLineChangePrinter::handleFunctionCompare( 1235 StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider, 1236 bool InModule, unsigned Minor, const FuncDataT<EmptyData> &Before, 1237 const FuncDataT<EmptyData> &After) { 1238 // Print a banner when this is being shown in the context of a module 1239 if (InModule) 1240 Out << "\n*** IR for function " << Name << " ***\n"; 1241 1242 FuncDataT<EmptyData>::report( 1243 Before, After, 1244 [&](const BlockDataT<EmptyData> *B, const BlockDataT<EmptyData> *A) { 1245 StringRef BStr = B ? B->getBody() : "\n"; 1246 StringRef AStr = A ? A->getBody() : "\n"; 1247 const std::string Removed = 1248 UseColour ? "\033[31m-%l\033[0m\n" : "-%l\n"; 1249 const std::string Added = UseColour ? "\033[32m+%l\033[0m\n" : "+%l\n"; 1250 const std::string NoChange = " %l\n"; 1251 Out << doSystemDiff(BStr, AStr, Removed, Added, NoChange); 1252 }); 1253 } 1254 1255 void InLineChangePrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) { 1256 if (PrintChanged == ChangePrinter::PrintChangedDiffVerbose || 1257 PrintChanged == ChangePrinter::PrintChangedDiffQuiet || 1258 PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose || 1259 PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet) 1260 TextChangeReporter<IRDataT<EmptyData>>::registerRequiredCallbacks(PIC); 1261 } 1262 1263 namespace { 1264 1265 enum IRChangeDiffType { InBefore, InAfter, IsCommon, NumIRChangeDiffTypes }; 1266 1267 // Describe where a given element exists. 1268 std::string Colours[NumIRChangeDiffTypes]; 1269 1270 class DisplayNode; 1271 class DotCfgDiffDisplayGraph; 1272 1273 // Base class for a node or edge in the dot-cfg-changes graph. 1274 class DisplayElement { 1275 public: 1276 // Is this in before, after, or both? 1277 IRChangeDiffType getType() const { return Type; } 1278 1279 protected: 1280 DisplayElement(IRChangeDiffType T) : Type(T) {} 1281 const IRChangeDiffType Type; 1282 }; 1283 1284 // An edge representing a transition between basic blocks in the 1285 // dot-cfg-changes graph. 1286 class DisplayEdge : public DisplayElement { 1287 public: 1288 DisplayEdge(std::string V, DisplayNode &Node, IRChangeDiffType T) 1289 : DisplayElement(T), Value(V), Node(Node) {} 1290 // The value on which the transition is made. 1291 std::string getValue() const { return Value; } 1292 // The node (representing a basic block) reached by this transition. 1293 const DisplayNode &getDestinationNode() const { return Node; } 1294 1295 protected: 1296 std::string Value; 1297 const DisplayNode &Node; 1298 }; 1299 1300 // A node in the dot-cfg-changes graph which represents a basic block. 1301 class DisplayNode : public DisplayElement { 1302 public: 1303 // \p C is the content for the node, \p T indicates the colour for the 1304 // outline of the node 1305 DisplayNode(std::string C, IRChangeDiffType T) 1306 : DisplayElement(T), Content(C) {} 1307 1308 // Iterator to the child nodes. Required by GraphWriter. 1309 using ChildIterator = std::unordered_set<DisplayNode *>::const_iterator; 1310 ChildIterator children_begin() const { return Children.cbegin(); } 1311 ChildIterator children_end() const { return Children.cend(); } 1312 1313 // Iterator for the edges. Required by GraphWriter. 1314 using EdgeIterator = std::vector<DisplayEdge *>::const_iterator; 1315 EdgeIterator edges_begin() const { return EdgePtrs.cbegin(); } 1316 EdgeIterator edges_end() const { return EdgePtrs.cend(); } 1317 1318 // Create an edge to \p Node on value \p V, with type \p T. 1319 void createEdge(StringRef V, DisplayNode &Node, IRChangeDiffType T); 1320 1321 // Return the content of this node. 1322 std::string getContent() const { return Content; } 1323 1324 // Return the type of the edge to node \p S. 1325 const DisplayEdge &getEdge(const DisplayNode &To) const { 1326 assert(EdgeMap.find(&To) != EdgeMap.end() && "Expected to find edge."); 1327 return *EdgeMap.find(&To)->second; 1328 } 1329 1330 // Return the value for the transition to basic block \p S. 1331 // Required by GraphWriter. 1332 std::string getEdgeSourceLabel(const DisplayNode &Sink) const { 1333 return getEdge(Sink).getValue(); 1334 } 1335 1336 void createEdgeMap(); 1337 1338 protected: 1339 const std::string Content; 1340 1341 // Place to collect all of the edges. Once they are all in the vector, 1342 // the vector will not reallocate so then we can use pointers to them, 1343 // which are required by the graph writing routines. 1344 std::vector<DisplayEdge> Edges; 1345 1346 std::vector<DisplayEdge *> EdgePtrs; 1347 std::unordered_set<DisplayNode *> Children; 1348 std::unordered_map<const DisplayNode *, const DisplayEdge *> EdgeMap; 1349 1350 // Safeguard adding of edges. 1351 bool AllEdgesCreated = false; 1352 }; 1353 1354 // Class representing a difference display (corresponds to a pdf file). 1355 class DotCfgDiffDisplayGraph { 1356 public: 1357 DotCfgDiffDisplayGraph(std::string Name) : GraphName(Name) {} 1358 1359 // Generate the file into \p DotFile. 1360 void generateDotFile(StringRef DotFile); 1361 1362 // Iterator to the nodes. Required by GraphWriter. 1363 using NodeIterator = std::vector<DisplayNode *>::const_iterator; 1364 NodeIterator nodes_begin() const { 1365 assert(NodeGenerationComplete && "Unexpected children iterator creation"); 1366 return NodePtrs.cbegin(); 1367 } 1368 NodeIterator nodes_end() const { 1369 assert(NodeGenerationComplete && "Unexpected children iterator creation"); 1370 return NodePtrs.cend(); 1371 } 1372 1373 // Record the index of the entry node. At this point, we can build up 1374 // vectors of pointers that are required by the graph routines. 1375 void setEntryNode(unsigned N) { 1376 // At this point, there will be no new nodes. 1377 assert(!NodeGenerationComplete && "Unexpected node creation"); 1378 NodeGenerationComplete = true; 1379 for (auto &N : Nodes) 1380 NodePtrs.emplace_back(&N); 1381 1382 EntryNode = NodePtrs[N]; 1383 } 1384 1385 // Create a node. 1386 void createNode(std::string C, IRChangeDiffType T) { 1387 assert(!NodeGenerationComplete && "Unexpected node creation"); 1388 Nodes.emplace_back(C, T); 1389 } 1390 // Return the node at index \p N to avoid problems with vectors reallocating. 1391 DisplayNode &getNode(unsigned N) { 1392 assert(N < Nodes.size() && "Node is out of bounds"); 1393 return Nodes[N]; 1394 } 1395 unsigned size() const { 1396 assert(NodeGenerationComplete && "Unexpected children iterator creation"); 1397 return Nodes.size(); 1398 } 1399 1400 // Return the name of the graph. Required by GraphWriter. 1401 std::string getGraphName() const { return GraphName; } 1402 1403 // Return the string representing the differences for basic block \p Node. 1404 // Required by GraphWriter. 1405 std::string getNodeLabel(const DisplayNode &Node) const { 1406 return Node.getContent(); 1407 } 1408 1409 // Return a string with colour information for Dot. Required by GraphWriter. 1410 std::string getNodeAttributes(const DisplayNode &Node) const { 1411 return attribute(Node.getType()); 1412 } 1413 1414 // Return a string with colour information for Dot. Required by GraphWriter. 1415 std::string getEdgeColorAttr(const DisplayNode &From, 1416 const DisplayNode &To) const { 1417 return attribute(From.getEdge(To).getType()); 1418 } 1419 1420 // Get the starting basic block. Required by GraphWriter. 1421 DisplayNode *getEntryNode() const { 1422 assert(NodeGenerationComplete && "Unexpected children iterator creation"); 1423 return EntryNode; 1424 } 1425 1426 protected: 1427 // Return the string containing the colour to use as a Dot attribute. 1428 std::string attribute(IRChangeDiffType T) const; 1429 1430 bool NodeGenerationComplete = false; 1431 const std::string GraphName; 1432 std::vector<DisplayNode> Nodes; 1433 std::vector<DisplayNode *> NodePtrs; 1434 DisplayNode *EntryNode = nullptr; 1435 }; 1436 1437 void DisplayNode::createEdge(StringRef V, DisplayNode &Node, 1438 IRChangeDiffType T) { 1439 assert(!AllEdgesCreated && "Expected to be able to still create edges."); 1440 Edges.emplace_back(V.str(), Node, T); 1441 Children.insert(&Node); 1442 } 1443 1444 void DisplayNode::createEdgeMap() { 1445 // No more edges will be added so we can now use pointers to the edges 1446 // as the vector will not grow and reallocate. 1447 AllEdgesCreated = true; 1448 for (auto &E : Edges) 1449 EdgeMap.insert({&E.getDestinationNode(), &E}); 1450 } 1451 1452 class DotCfgDiffNode; 1453 class DotCfgDiff; 1454 1455 // A class representing a basic block in the Dot difference graph. 1456 class DotCfgDiffNode { 1457 public: 1458 DotCfgDiffNode() = delete; 1459 1460 // Create a node in Dot difference graph \p G representing the basic block 1461 // represented by \p BD with type \p T (where it exists). 1462 DotCfgDiffNode(DotCfgDiff &G, unsigned N, const BlockDataT<DCData> &BD, 1463 IRChangeDiffType T) 1464 : Graph(G), N(N), Data{&BD, nullptr}, Type(T) {} 1465 DotCfgDiffNode(const DotCfgDiffNode &DN) 1466 : Graph(DN.Graph), N(DN.N), Data{DN.Data[0], DN.Data[1]}, Type(DN.Type), 1467 EdgesMap(DN.EdgesMap), Children(DN.Children), Edges(DN.Edges) {} 1468 1469 unsigned getIndex() const { return N; } 1470 1471 // The label of the basic block 1472 StringRef getLabel() const { 1473 assert(Data[0] && "Expected Data[0] to be set."); 1474 return Data[0]->getLabel(); 1475 } 1476 // Return where this block exists. 1477 IRChangeDiffType getType() const { return Type; } 1478 // Change this basic block from being only in before to being common. 1479 // Save the pointer to \p Other. 1480 void setCommon(const BlockDataT<DCData> &Other) { 1481 assert(!Data[1] && "Expected only one block datum"); 1482 Data[1] = &Other; 1483 Type = IsCommon; 1484 } 1485 // Add an edge to \p E of type {\p Value, \p T}. 1486 void addEdge(unsigned E, StringRef Value, IRChangeDiffType T) { 1487 // This is a new edge or it is an edge being made common. 1488 assert((EdgesMap.count(E) == 0 || T == IsCommon) && 1489 "Unexpected edge count and type."); 1490 EdgesMap[E] = {Value.str(), T}; 1491 } 1492 // Record the children and create edges. 1493 void finalize(DotCfgDiff &G); 1494 1495 // Return the type of the edge to node \p S. 1496 std::pair<std::string, IRChangeDiffType> getEdge(const unsigned S) const { 1497 assert(EdgesMap.count(S) == 1 && "Expected to find edge."); 1498 return EdgesMap.at(S); 1499 } 1500 1501 // Return the string representing the basic block. 1502 std::string getBodyContent() const; 1503 1504 void createDisplayEdges(DotCfgDiffDisplayGraph &Graph, unsigned DisplayNode, 1505 std::map<const unsigned, unsigned> &NodeMap) const; 1506 1507 protected: 1508 DotCfgDiff &Graph; 1509 const unsigned N; 1510 const BlockDataT<DCData> *Data[2]; 1511 IRChangeDiffType Type; 1512 std::map<const unsigned, std::pair<std::string, IRChangeDiffType>> EdgesMap; 1513 std::vector<unsigned> Children; 1514 std::vector<unsigned> Edges; 1515 }; 1516 1517 // Class representing the difference graph between two functions. 1518 class DotCfgDiff { 1519 public: 1520 // \p Title is the title given to the graph. \p EntryNodeName is the 1521 // entry node for the function. \p Before and \p After are the before 1522 // after versions of the function, respectively. \p Dir is the directory 1523 // in which to store the results. 1524 DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before, 1525 const FuncDataT<DCData> &After); 1526 1527 DotCfgDiff(const DotCfgDiff &) = delete; 1528 DotCfgDiff &operator=(const DotCfgDiff &) = delete; 1529 1530 DotCfgDiffDisplayGraph createDisplayGraph(StringRef Title, 1531 StringRef EntryNodeName); 1532 1533 // Return a string consisting of the labels for the \p Source and \p Sink. 1534 // The combination allows distinguishing changing transitions on the 1535 // same value (ie, a transition went to X before and goes to Y after). 1536 // Required by GraphWriter. 1537 StringRef getEdgeSourceLabel(const unsigned &Source, 1538 const unsigned &Sink) const { 1539 std::string S = 1540 getNode(Source).getLabel().str() + " " + getNode(Sink).getLabel().str(); 1541 assert(EdgeLabels.count(S) == 1 && "Expected to find edge label."); 1542 return EdgeLabels.find(S)->getValue(); 1543 } 1544 1545 // Return the number of basic blocks (nodes). Required by GraphWriter. 1546 unsigned size() const { return Nodes.size(); } 1547 1548 const DotCfgDiffNode &getNode(unsigned N) const { 1549 assert(N < Nodes.size() && "Unexpected index for node reference"); 1550 return Nodes[N]; 1551 } 1552 1553 protected: 1554 // Return the string surrounded by HTML to make it the appropriate colour. 1555 std::string colourize(std::string S, IRChangeDiffType T) const; 1556 1557 void createNode(StringRef Label, const BlockDataT<DCData> &BD, 1558 IRChangeDiffType T) { 1559 unsigned Pos = Nodes.size(); 1560 Nodes.emplace_back(*this, Pos, BD, T); 1561 NodePosition.insert({Label, Pos}); 1562 } 1563 1564 // TODO Nodes should probably be a StringMap<DotCfgDiffNode> after the 1565 // display graph is separated out, which would remove the need for 1566 // NodePosition. 1567 std::vector<DotCfgDiffNode> Nodes; 1568 StringMap<unsigned> NodePosition; 1569 const std::string GraphName; 1570 1571 StringMap<std::string> EdgeLabels; 1572 }; 1573 1574 std::string DotCfgDiffNode::getBodyContent() const { 1575 if (Type == IsCommon) { 1576 assert(Data[1] && "Expected Data[1] to be set."); 1577 1578 StringRef SR[2]; 1579 for (unsigned I = 0; I < 2; ++I) { 1580 SR[I] = Data[I]->getBody(); 1581 // drop initial '\n' if present 1582 if (SR[I][0] == '\n') 1583 SR[I] = SR[I].drop_front(); 1584 // drop predecessors as they can be big and are redundant 1585 SR[I] = SR[I].drop_until([](char C) { return C == '\n'; }).drop_front(); 1586 } 1587 1588 SmallString<80> OldLineFormat = formatv( 1589 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", Colours[InBefore]); 1590 SmallString<80> NewLineFormat = formatv( 1591 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", Colours[InAfter]); 1592 SmallString<80> UnchangedLineFormat = formatv( 1593 "<FONT COLOR=\"{0}\">%l</FONT><BR align=\"left\"/>", Colours[IsCommon]); 1594 std::string Diff = Data[0]->getLabel().str(); 1595 Diff += ":\n<BR align=\"left\"/>" + 1596 doSystemDiff(makeHTMLReady(SR[0]), makeHTMLReady(SR[1]), 1597 OldLineFormat, NewLineFormat, UnchangedLineFormat); 1598 1599 // Diff adds in some empty colour changes which are not valid HTML 1600 // so remove them. Colours are all lowercase alpha characters (as 1601 // listed in https://graphviz.org/pdf/dotguide.pdf). 1602 Regex R("<FONT COLOR=\"\\w+\"></FONT>"); 1603 while (true) { 1604 std::string Error; 1605 std::string S = R.sub("", Diff, &Error); 1606 if (Error != "") 1607 return Error; 1608 if (S == Diff) 1609 return Diff; 1610 Diff = S; 1611 } 1612 llvm_unreachable("Should not get here"); 1613 } 1614 1615 // Put node out in the appropriate colour. 1616 assert(!Data[1] && "Data[1] is set unexpectedly."); 1617 std::string Body = makeHTMLReady(Data[0]->getBody()); 1618 const StringRef BS = Body; 1619 StringRef BS1 = BS; 1620 // Drop leading newline, if present. 1621 if (BS.front() == '\n') 1622 BS1 = BS1.drop_front(1); 1623 // Get label. 1624 StringRef Label = BS1.take_until([](char C) { return C == ':'; }); 1625 // drop predecessors as they can be big and are redundant 1626 BS1 = BS1.drop_until([](char C) { return C == '\n'; }).drop_front(); 1627 1628 std::string S = "<FONT COLOR=\"" + Colours[Type] + "\">" + Label.str() + ":"; 1629 1630 // align each line to the left. 1631 while (BS1.size()) { 1632 S.append("<BR align=\"left\"/>"); 1633 StringRef Line = BS1.take_until([](char C) { return C == '\n'; }); 1634 S.append(Line.str()); 1635 BS1 = BS1.drop_front(Line.size() + 1); 1636 } 1637 S.append("<BR align=\"left\"/></FONT>"); 1638 return S; 1639 } 1640 1641 std::string DotCfgDiff::colourize(std::string S, IRChangeDiffType T) const { 1642 if (S.length() == 0) 1643 return S; 1644 return "<FONT COLOR=\"" + Colours[T] + "\">" + S + "</FONT>"; 1645 } 1646 1647 std::string DotCfgDiffDisplayGraph::attribute(IRChangeDiffType T) const { 1648 return "color=" + Colours[T]; 1649 } 1650 1651 DotCfgDiff::DotCfgDiff(StringRef Title, const FuncDataT<DCData> &Before, 1652 const FuncDataT<DCData> &After) 1653 : GraphName(Title.str()) { 1654 StringMap<IRChangeDiffType> EdgesMap; 1655 1656 // Handle each basic block in the before IR. 1657 for (auto &B : Before.getData()) { 1658 StringRef Label = B.getKey(); 1659 const BlockDataT<DCData> &BD = B.getValue(); 1660 createNode(Label, BD, InBefore); 1661 1662 // Create transitions with names made up of the from block label, the value 1663 // on which the transition is made and the to block label. 1664 for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(), 1665 E = BD.getData().end(); 1666 Sink != E; ++Sink) { 1667 std::string Key = (Label + " " + Sink->getKey().str()).str() + " " + 1668 BD.getData().getSuccessorLabel(Sink->getKey()).str(); 1669 EdgesMap.insert({Key, InBefore}); 1670 } 1671 } 1672 1673 // Handle each basic block in the after IR 1674 for (auto &A : After.getData()) { 1675 StringRef Label = A.getKey(); 1676 const BlockDataT<DCData> &BD = A.getValue(); 1677 unsigned C = NodePosition.count(Label); 1678 if (C == 0) 1679 // This only exists in the after IR. Create the node. 1680 createNode(Label, BD, InAfter); 1681 else { 1682 assert(C == 1 && "Unexpected multiple nodes."); 1683 Nodes[NodePosition[Label]].setCommon(BD); 1684 } 1685 // Add in the edges between the nodes (as common or only in after). 1686 for (StringMap<std::string>::const_iterator Sink = BD.getData().begin(), 1687 E = BD.getData().end(); 1688 Sink != E; ++Sink) { 1689 std::string Key = (Label + " " + Sink->getKey().str()).str() + " " + 1690 BD.getData().getSuccessorLabel(Sink->getKey()).str(); 1691 unsigned C = EdgesMap.count(Key); 1692 if (C == 0) 1693 EdgesMap.insert({Key, InAfter}); 1694 else { 1695 EdgesMap[Key] = IsCommon; 1696 } 1697 } 1698 } 1699 1700 // Now go through the map of edges and add them to the node. 1701 for (auto &E : EdgesMap) { 1702 // Extract the source, sink and value from the edge key. 1703 StringRef S = E.getKey(); 1704 auto SP1 = S.rsplit(' '); 1705 auto &SourceSink = SP1.first; 1706 auto SP2 = SourceSink.split(' '); 1707 StringRef Source = SP2.first; 1708 StringRef Sink = SP2.second; 1709 StringRef Value = SP1.second; 1710 1711 assert(NodePosition.count(Source) == 1 && "Expected to find node."); 1712 DotCfgDiffNode &SourceNode = Nodes[NodePosition[Source]]; 1713 assert(NodePosition.count(Sink) == 1 && "Expected to find node."); 1714 unsigned SinkNode = NodePosition[Sink]; 1715 IRChangeDiffType T = E.second; 1716 1717 // Look for an edge from Source to Sink 1718 if (EdgeLabels.count(SourceSink) == 0) 1719 EdgeLabels.insert({SourceSink, colourize(Value.str(), T)}); 1720 else { 1721 StringRef V = EdgeLabels.find(SourceSink)->getValue(); 1722 std::string NV = colourize(V.str() + " " + Value.str(), T); 1723 T = IsCommon; 1724 EdgeLabels[SourceSink] = NV; 1725 } 1726 SourceNode.addEdge(SinkNode, Value, T); 1727 } 1728 for (auto &I : Nodes) 1729 I.finalize(*this); 1730 } 1731 1732 DotCfgDiffDisplayGraph DotCfgDiff::createDisplayGraph(StringRef Title, 1733 StringRef EntryNodeName) { 1734 assert(NodePosition.count(EntryNodeName) == 1 && 1735 "Expected to find entry block in map."); 1736 unsigned Entry = NodePosition[EntryNodeName]; 1737 assert(Entry < Nodes.size() && "Expected to find entry node"); 1738 DotCfgDiffDisplayGraph G(Title.str()); 1739 1740 std::map<const unsigned, unsigned> NodeMap; 1741 1742 int EntryIndex = -1; 1743 unsigned Index = 0; 1744 for (auto &I : Nodes) { 1745 if (I.getIndex() == Entry) 1746 EntryIndex = Index; 1747 G.createNode(I.getBodyContent(), I.getType()); 1748 NodeMap.insert({I.getIndex(), Index++}); 1749 } 1750 assert(EntryIndex >= 0 && "Expected entry node index to be set."); 1751 G.setEntryNode(EntryIndex); 1752 1753 for (auto &I : NodeMap) { 1754 unsigned SourceNode = I.first; 1755 unsigned DisplayNode = I.second; 1756 getNode(SourceNode).createDisplayEdges(G, DisplayNode, NodeMap); 1757 } 1758 return G; 1759 } 1760 1761 void DotCfgDiffNode::createDisplayEdges( 1762 DotCfgDiffDisplayGraph &DisplayGraph, unsigned DisplayNodeIndex, 1763 std::map<const unsigned, unsigned> &NodeMap) const { 1764 1765 DisplayNode &SourceDisplayNode = DisplayGraph.getNode(DisplayNodeIndex); 1766 1767 for (auto I : Edges) { 1768 unsigned SinkNodeIndex = I; 1769 IRChangeDiffType Type = getEdge(SinkNodeIndex).second; 1770 const DotCfgDiffNode *SinkNode = &Graph.getNode(SinkNodeIndex); 1771 1772 StringRef Label = Graph.getEdgeSourceLabel(getIndex(), SinkNodeIndex); 1773 DisplayNode &SinkDisplayNode = DisplayGraph.getNode(SinkNode->getIndex()); 1774 SourceDisplayNode.createEdge(Label, SinkDisplayNode, Type); 1775 } 1776 SourceDisplayNode.createEdgeMap(); 1777 } 1778 1779 void DotCfgDiffNode::finalize(DotCfgDiff &G) { 1780 for (auto E : EdgesMap) { 1781 Children.emplace_back(E.first); 1782 Edges.emplace_back(E.first); 1783 } 1784 } 1785 1786 } // namespace 1787 1788 namespace llvm { 1789 1790 template <> struct GraphTraits<DotCfgDiffDisplayGraph *> { 1791 using NodeRef = const DisplayNode *; 1792 using ChildIteratorType = DisplayNode::ChildIterator; 1793 using nodes_iterator = DotCfgDiffDisplayGraph::NodeIterator; 1794 using EdgeRef = const DisplayEdge *; 1795 using ChildEdgeIterator = DisplayNode::EdgeIterator; 1796 1797 static NodeRef getEntryNode(const DotCfgDiffDisplayGraph *G) { 1798 return G->getEntryNode(); 1799 } 1800 static ChildIteratorType child_begin(NodeRef N) { 1801 return N->children_begin(); 1802 } 1803 static ChildIteratorType child_end(NodeRef N) { return N->children_end(); } 1804 static nodes_iterator nodes_begin(const DotCfgDiffDisplayGraph *G) { 1805 return G->nodes_begin(); 1806 } 1807 static nodes_iterator nodes_end(const DotCfgDiffDisplayGraph *G) { 1808 return G->nodes_end(); 1809 } 1810 static ChildEdgeIterator child_edge_begin(NodeRef N) { 1811 return N->edges_begin(); 1812 } 1813 static ChildEdgeIterator child_edge_end(NodeRef N) { return N->edges_end(); } 1814 static NodeRef edge_dest(EdgeRef E) { return &E->getDestinationNode(); } 1815 static unsigned size(const DotCfgDiffDisplayGraph *G) { return G->size(); } 1816 }; 1817 1818 template <> 1819 struct DOTGraphTraits<DotCfgDiffDisplayGraph *> : public DefaultDOTGraphTraits { 1820 explicit DOTGraphTraits(bool Simple = false) 1821 : DefaultDOTGraphTraits(Simple) {} 1822 1823 static bool renderNodesUsingHTML() { return true; } 1824 static std::string getGraphName(const DotCfgDiffDisplayGraph *DiffData) { 1825 return DiffData->getGraphName(); 1826 } 1827 static std::string 1828 getGraphProperties(const DotCfgDiffDisplayGraph *DiffData) { 1829 return "\tsize=\"190, 190\";\n"; 1830 } 1831 static std::string getNodeLabel(const DisplayNode *Node, 1832 const DotCfgDiffDisplayGraph *DiffData) { 1833 return DiffData->getNodeLabel(*Node); 1834 } 1835 static std::string getNodeAttributes(const DisplayNode *Node, 1836 const DotCfgDiffDisplayGraph *DiffData) { 1837 return DiffData->getNodeAttributes(*Node); 1838 } 1839 static std::string getEdgeSourceLabel(const DisplayNode *From, 1840 DisplayNode::ChildIterator &To) { 1841 return From->getEdgeSourceLabel(**To); 1842 } 1843 static std::string getEdgeAttributes(const DisplayNode *From, 1844 DisplayNode::ChildIterator &To, 1845 const DotCfgDiffDisplayGraph *DiffData) { 1846 return DiffData->getEdgeColorAttr(*From, **To); 1847 } 1848 }; 1849 1850 } // namespace llvm 1851 1852 namespace { 1853 1854 void DotCfgDiffDisplayGraph::generateDotFile(StringRef DotFile) { 1855 std::error_code EC; 1856 raw_fd_ostream OutStream(DotFile, EC); 1857 if (EC) { 1858 errs() << "Error: " << EC.message() << "\n"; 1859 return; 1860 } 1861 WriteGraph(OutStream, this, false); 1862 OutStream.flush(); 1863 OutStream.close(); 1864 } 1865 1866 } // namespace 1867 1868 namespace llvm { 1869 1870 DCData::DCData(const BasicBlock &B) { 1871 // Build up transition labels. 1872 const Instruction *Term = B.getTerminator(); 1873 if (const BranchInst *Br = dyn_cast<const BranchInst>(Term)) 1874 if (Br->isUnconditional()) 1875 addSuccessorLabel(Br->getSuccessor(0)->getName().str(), ""); 1876 else { 1877 addSuccessorLabel(Br->getSuccessor(0)->getName().str(), "true"); 1878 addSuccessorLabel(Br->getSuccessor(1)->getName().str(), "false"); 1879 } 1880 else if (const SwitchInst *Sw = dyn_cast<const SwitchInst>(Term)) { 1881 addSuccessorLabel(Sw->case_default()->getCaseSuccessor()->getName().str(), 1882 "default"); 1883 for (auto &C : Sw->cases()) { 1884 assert(C.getCaseValue() && "Expected to find case value."); 1885 SmallString<20> Value = formatv("{0}", C.getCaseValue()->getSExtValue()); 1886 addSuccessorLabel(C.getCaseSuccessor()->getName().str(), Value); 1887 } 1888 } else 1889 for (const_succ_iterator I = succ_begin(&B), E = succ_end(&B); I != E; ++I) 1890 addSuccessorLabel((*I)->getName().str(), ""); 1891 } 1892 1893 DotCfgChangeReporter::DotCfgChangeReporter(bool Verbose) 1894 : ChangeReporter<IRDataT<DCData>>(Verbose) { 1895 // Set up the colours based on the hidden options. 1896 Colours[InBefore] = BeforeColour; 1897 Colours[InAfter] = AfterColour; 1898 Colours[IsCommon] = CommonColour; 1899 } 1900 1901 void DotCfgChangeReporter::handleFunctionCompare( 1902 StringRef Name, StringRef Prefix, StringRef PassID, StringRef Divider, 1903 bool InModule, unsigned Minor, const FuncDataT<DCData> &Before, 1904 const FuncDataT<DCData> &After) { 1905 assert(HTML && "Expected outstream to be set"); 1906 SmallString<8> Extender; 1907 SmallString<8> Number; 1908 // Handle numbering and file names. 1909 if (InModule) { 1910 Extender = formatv("{0}_{1}", N, Minor); 1911 Number = formatv("{0}.{1}", N, Minor); 1912 } else { 1913 Extender = formatv("{0}", N); 1914 Number = formatv("{0}", N); 1915 } 1916 // Create a temporary file name for the dot file. 1917 SmallVector<char, 128> SV; 1918 sys::fs::createUniquePath("cfgdot-%%%%%%.dot", SV, true); 1919 std::string DotFile = Twine(SV).str(); 1920 1921 SmallString<20> PDFFileName = formatv("diff_{0}.pdf", Extender); 1922 SmallString<200> Text; 1923 1924 Text = formatv("{0}.{1}{2}{3}{4}", Number, Prefix, makeHTMLReady(PassID), 1925 Divider, Name); 1926 1927 DotCfgDiff Diff(Text, Before, After); 1928 std::string EntryBlockName = After.getEntryBlockName(); 1929 // Use the before entry block if the after entry block was removed. 1930 if (EntryBlockName == "") 1931 EntryBlockName = Before.getEntryBlockName(); 1932 assert(EntryBlockName != "" && "Expected to find entry block"); 1933 1934 DotCfgDiffDisplayGraph DG = Diff.createDisplayGraph(Text, EntryBlockName); 1935 DG.generateDotFile(DotFile); 1936 1937 *HTML << genHTML(Text, DotFile, PDFFileName); 1938 std::error_code EC = sys::fs::remove(DotFile); 1939 if (EC) 1940 errs() << "Error: " << EC.message() << "\n"; 1941 } 1942 1943 std::string DotCfgChangeReporter::genHTML(StringRef Text, StringRef DotFile, 1944 StringRef PDFFileName) { 1945 SmallString<20> PDFFile = formatv("{0}/{1}", DotCfgDir, PDFFileName); 1946 // Create the PDF file. 1947 static ErrorOr<std::string> DotExe = sys::findProgramByName(DotBinary); 1948 if (!DotExe) 1949 return "Unable to find dot executable."; 1950 1951 StringRef Args[] = {DotBinary, "-Tpdf", "-o", PDFFile, DotFile}; 1952 int Result = sys::ExecuteAndWait(*DotExe, Args, None); 1953 if (Result < 0) 1954 return "Error executing system dot."; 1955 1956 // Create the HTML tag refering to the PDF file. 1957 SmallString<200> S = formatv( 1958 " <a href=\"{0}\" target=\"_blank\">{1}</a><br/>\n", PDFFileName, Text); 1959 return S.c_str(); 1960 } 1961 1962 void DotCfgChangeReporter::handleInitialIR(Any IR) { 1963 assert(HTML && "Expected outstream to be set"); 1964 *HTML << "<button type=\"button\" class=\"collapsible\">0. " 1965 << "Initial IR (by function)</button>\n" 1966 << "<div class=\"content\">\n" 1967 << " <p>\n"; 1968 // Create representation of IR 1969 IRDataT<DCData> Data; 1970 IRComparer<DCData>::analyzeIR(IR, Data); 1971 // Now compare it against itself, which will have everything the 1972 // same and will generate the files. 1973 IRComparer<DCData>(Data, Data) 1974 .compare(getModuleForComparison(IR), 1975 [&](bool InModule, unsigned Minor, 1976 const FuncDataT<DCData> &Before, 1977 const FuncDataT<DCData> &After) -> void { 1978 handleFunctionCompare("", " ", "Initial IR", "", InModule, 1979 Minor, Before, After); 1980 }); 1981 *HTML << " </p>\n" 1982 << "</div><br/>\n"; 1983 ++N; 1984 } 1985 1986 void DotCfgChangeReporter::generateIRRepresentation(Any IR, StringRef PassID, 1987 IRDataT<DCData> &Data) { 1988 IRComparer<DCData>::analyzeIR(IR, Data); 1989 } 1990 1991 void DotCfgChangeReporter::omitAfter(StringRef PassID, std::string &Name) { 1992 assert(HTML && "Expected outstream to be set"); 1993 SmallString<20> Banner = 1994 formatv(" <a>{0}. Pass {1} on {2} omitted because no change</a><br/>\n", 1995 N, makeHTMLReady(PassID), Name); 1996 *HTML << Banner; 1997 ++N; 1998 } 1999 2000 void DotCfgChangeReporter::handleAfter(StringRef PassID, std::string &Name, 2001 const IRDataT<DCData> &Before, 2002 const IRDataT<DCData> &After, Any IR) { 2003 assert(HTML && "Expected outstream to be set"); 2004 IRComparer<DCData>(Before, After) 2005 .compare(getModuleForComparison(IR), 2006 [&](bool InModule, unsigned Minor, 2007 const FuncDataT<DCData> &Before, 2008 const FuncDataT<DCData> &After) -> void { 2009 handleFunctionCompare(Name, " Pass ", PassID, " on ", InModule, 2010 Minor, Before, After); 2011 }); 2012 *HTML << " </p></div>\n"; 2013 ++N; 2014 } 2015 2016 void DotCfgChangeReporter::handleInvalidated(StringRef PassID) { 2017 assert(HTML && "Expected outstream to be set"); 2018 SmallString<20> Banner = 2019 formatv(" <a>{0}. {1} invalidated</a><br/>\n", N, makeHTMLReady(PassID)); 2020 *HTML << Banner; 2021 ++N; 2022 } 2023 2024 void DotCfgChangeReporter::handleFiltered(StringRef PassID, std::string &Name) { 2025 assert(HTML && "Expected outstream to be set"); 2026 SmallString<20> Banner = 2027 formatv(" <a>{0}. Pass {1} on {2} filtered out</a><br/>\n", N, 2028 makeHTMLReady(PassID), Name); 2029 *HTML << Banner; 2030 ++N; 2031 } 2032 2033 void DotCfgChangeReporter::handleIgnored(StringRef PassID, std::string &Name) { 2034 assert(HTML && "Expected outstream to be set"); 2035 SmallString<20> Banner = formatv(" <a>{0}. {1} on {2} ignored</a><br/>\n", N, 2036 makeHTMLReady(PassID), Name); 2037 *HTML << Banner; 2038 ++N; 2039 } 2040 2041 bool DotCfgChangeReporter::initializeHTML() { 2042 std::error_code EC; 2043 HTML = std::make_unique<raw_fd_ostream>(DotCfgDir + "/passes.html", EC); 2044 if (EC) { 2045 HTML = nullptr; 2046 return false; 2047 } 2048 2049 *HTML << "<!doctype html>" 2050 << "<html>" 2051 << "<head>" 2052 << "<style>.collapsible { " 2053 << "background-color: #777;" 2054 << " color: white;" 2055 << " cursor: pointer;" 2056 << " padding: 18px;" 2057 << " width: 100%;" 2058 << " border: none;" 2059 << " text-align: left;" 2060 << " outline: none;" 2061 << " font-size: 15px;" 2062 << "} .active, .collapsible:hover {" 2063 << " background-color: #555;" 2064 << "} .content {" 2065 << " padding: 0 18px;" 2066 << " display: none;" 2067 << " overflow: hidden;" 2068 << " background-color: #f1f1f1;" 2069 << "}" 2070 << "</style>" 2071 << "<title>passes.html</title>" 2072 << "</head>\n" 2073 << "<body>"; 2074 return true; 2075 } 2076 2077 DotCfgChangeReporter::~DotCfgChangeReporter() { 2078 if (!HTML) 2079 return; 2080 *HTML 2081 << "<script>var coll = document.getElementsByClassName(\"collapsible\");" 2082 << "var i;" 2083 << "for (i = 0; i < coll.length; i++) {" 2084 << "coll[i].addEventListener(\"click\", function() {" 2085 << " this.classList.toggle(\"active\");" 2086 << " var content = this.nextElementSibling;" 2087 << " if (content.style.display === \"block\"){" 2088 << " content.style.display = \"none\";" 2089 << " }" 2090 << " else {" 2091 << " content.style.display= \"block\";" 2092 << " }" 2093 << " });" 2094 << " }" 2095 << "</script>" 2096 << "</body>" 2097 << "</html>\n"; 2098 HTML->flush(); 2099 HTML->close(); 2100 } 2101 2102 void DotCfgChangeReporter::registerCallbacks( 2103 PassInstrumentationCallbacks &PIC) { 2104 if ((PrintChanged == ChangePrinter::PrintChangedDotCfgVerbose || 2105 PrintChanged == ChangePrinter::PrintChangedDotCfgQuiet)) { 2106 SmallString<128> OutputDir; 2107 sys::fs::expand_tilde(DotCfgDir, OutputDir); 2108 sys::fs::make_absolute(OutputDir); 2109 assert(!OutputDir.empty() && "expected output dir to be non-empty"); 2110 DotCfgDir = OutputDir.c_str(); 2111 if (initializeHTML()) { 2112 ChangeReporter<IRDataT<DCData>>::registerRequiredCallbacks(PIC); 2113 return; 2114 } 2115 dbgs() << "Unable to open output stream for -cfg-dot-changed\n"; 2116 } 2117 } 2118 2119 StandardInstrumentations::StandardInstrumentations( 2120 bool DebugLogging, bool VerifyEach, PrintPassOptions PrintPassOpts) 2121 : PrintPass(DebugLogging, PrintPassOpts), OptNone(DebugLogging), 2122 PrintChangedIR(PrintChanged == ChangePrinter::PrintChangedVerbose), 2123 PrintChangedDiff( 2124 PrintChanged == ChangePrinter::PrintChangedDiffVerbose || 2125 PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose, 2126 PrintChanged == ChangePrinter::PrintChangedColourDiffVerbose || 2127 PrintChanged == ChangePrinter::PrintChangedColourDiffQuiet), 2128 WebsiteChangeReporter(PrintChanged == 2129 ChangePrinter::PrintChangedDotCfgVerbose), 2130 Verify(DebugLogging), VerifyEach(VerifyEach) {} 2131 2132 void StandardInstrumentations::registerCallbacks( 2133 PassInstrumentationCallbacks &PIC, FunctionAnalysisManager *FAM) { 2134 PrintIR.registerCallbacks(PIC); 2135 PrintPass.registerCallbacks(PIC); 2136 TimePasses.registerCallbacks(PIC); 2137 OptNone.registerCallbacks(PIC); 2138 OptBisect.registerCallbacks(PIC); 2139 if (FAM) 2140 PreservedCFGChecker.registerCallbacks(PIC, *FAM); 2141 PrintChangedIR.registerCallbacks(PIC); 2142 PseudoProbeVerification.registerCallbacks(PIC); 2143 if (VerifyEach) 2144 Verify.registerCallbacks(PIC); 2145 PrintChangedDiff.registerCallbacks(PIC); 2146 WebsiteChangeReporter.registerCallbacks(PIC); 2147 } 2148 2149 template class ChangeReporter<std::string>; 2150 template class TextChangeReporter<std::string>; 2151 2152 template class BlockDataT<EmptyData>; 2153 template class FuncDataT<EmptyData>; 2154 template class IRDataT<EmptyData>; 2155 template class ChangeReporter<IRDataT<EmptyData>>; 2156 template class TextChangeReporter<IRDataT<EmptyData>>; 2157 template class IRComparer<EmptyData>; 2158 2159 } // namespace llvm 2160