xref: /freebsd/contrib/llvm-project/llvm/lib/IRPrinter/IRPrintingPasses.cpp (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
1 //===--- IRPrintingPasses.cpp - Module and Function printing passes -------===//
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 //
9 // PrintModulePass and PrintFunctionPass implementations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IRPrinter/IRPrintingPasses.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
16 #include "llvm/IR/Function.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/IR/PrintPasses.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace llvm;
24 
25 PrintModulePass::PrintModulePass() : OS(dbgs()) {}
26 PrintModulePass::PrintModulePass(raw_ostream &OS, const std::string &Banner,
27                                  bool ShouldPreserveUseListOrder,
28                                  bool EmitSummaryIndex)
29     : OS(OS), Banner(Banner),
30       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder),
31       EmitSummaryIndex(EmitSummaryIndex) {}
32 
33 PreservedAnalyses PrintModulePass::run(Module &M, ModuleAnalysisManager &AM) {
34   if (llvm::isFunctionInPrintList("*")) {
35     if (!Banner.empty())
36       OS << Banner << "\n";
37     M.print(OS, nullptr, ShouldPreserveUseListOrder);
38   } else {
39     bool BannerPrinted = false;
40     for (const auto &F : M.functions()) {
41       if (llvm::isFunctionInPrintList(F.getName())) {
42         if (!BannerPrinted && !Banner.empty()) {
43           OS << Banner << "\n";
44           BannerPrinted = true;
45         }
46         F.print(OS);
47       }
48     }
49   }
50 
51   ModuleSummaryIndex *Index =
52       EmitSummaryIndex ? &(AM.getResult<ModuleSummaryIndexAnalysis>(M))
53                        : nullptr;
54   if (Index) {
55     if (Index->modulePaths().empty())
56       Index->addModule("", 0);
57     Index->print(OS);
58   }
59 
60   return PreservedAnalyses::all();
61 }
62 
63 PrintFunctionPass::PrintFunctionPass() : OS(dbgs()) {}
64 PrintFunctionPass::PrintFunctionPass(raw_ostream &OS, const std::string &Banner)
65     : OS(OS), Banner(Banner) {}
66 
67 PreservedAnalyses PrintFunctionPass::run(Function &F,
68                                          FunctionAnalysisManager &) {
69   if (isFunctionInPrintList(F.getName())) {
70     if (forcePrintModuleIR())
71       OS << Banner << " (function: " << F.getName() << ")\n" << *F.getParent();
72     else
73       OS << Banner << '\n' << static_cast<Value &>(F);
74   }
75   return PreservedAnalyses::all();
76 }
77