| 1 | //===- CFGPrinter.cpp - DOT printer for the control flow graph ------------===// |
| 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 | // This file defines a `-dot-cfg` analysis pass, which emits the |
| 10 | // `<prefix>.<fnname>.dot` file for each function in the program, with a graph |
| 11 | // of the CFG for that function. The default value for `<prefix>` is `cfg` but |
| 12 | // can be customized as needed. |
| 13 | // |
| 14 | // The other main feature of this file is that it implements the |
| 15 | // Function::viewCFG method, which is useful for debugging passes which operate |
| 16 | // on the CFG. |
| 17 | // |
| 18 | //===----------------------------------------------------------------------===// |
| 19 | |
| 20 | #include "llvm/Analysis/CFGPrinter.h" |
| 21 | #include "AnalysisOptions.h" |
| 22 | #include "llvm/ADT/PostOrderIterator.h" |
| 23 | #include "llvm/IR/ModuleSlotTracker.h" |
| 24 | #include "llvm/Support/FileSystem.h" |
| 25 | #include "llvm/Support/GraphWriter.h" |
| 26 | |
| 27 | using namespace llvm; |
| 28 | |
| 29 | static void writeCFGToDotFile(const AnalysisOptions &Opts, Function &F, |
| 30 | BlockFrequencyInfo *BFI, |
| 31 | BranchProbabilityInfo *BPI, uint64_t MaxFreq, |
| 32 | bool CFGOnly = false) { |
| 33 | std::string Filename = |
| 34 | (Opts.cfg_dot_filename_prefix + "." + F.getName() + ".dot" ).str(); |
| 35 | errs() << "Writing '" << Filename << "'..." ; |
| 36 | |
| 37 | std::error_code EC; |
| 38 | raw_fd_ostream File(Filename, EC, sys::fs::OF_Text); |
| 39 | |
| 40 | DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq); |
| 41 | CFGInfo.setHeatColors(Opts.cfg_heat_colors); |
| 42 | CFGInfo.setEdgeWeights(Opts.cfg_weights); |
| 43 | CFGInfo.setRawEdgeWeights(Opts.cfg_raw_weights); |
| 44 | |
| 45 | if (!EC) |
| 46 | WriteGraph(O&: File, G: &CFGInfo, ShortNames: CFGOnly); |
| 47 | else |
| 48 | errs() << " error opening file for writing!" ; |
| 49 | errs() << "\n" ; |
| 50 | } |
| 51 | |
| 52 | static void viewCFG(const AnalysisOptions &Opts, Function &F, |
| 53 | const BlockFrequencyInfo *BFI, |
| 54 | const BranchProbabilityInfo *BPI, uint64_t MaxFreq, |
| 55 | bool CFGOnly = false) { |
| 56 | DOTFuncInfo CFGInfo(&F, BFI, BPI, MaxFreq); |
| 57 | CFGInfo.setHeatColors(Opts.cfg_heat_colors); |
| 58 | CFGInfo.setEdgeWeights(Opts.cfg_weights); |
| 59 | CFGInfo.setRawEdgeWeights(Opts.cfg_raw_weights); |
| 60 | |
| 61 | ViewGraph(G: &CFGInfo, Name: "cfg." + F.getName(), ShortNames: CFGOnly); |
| 62 | } |
| 63 | |
| 64 | DOTFuncInfo::DOTFuncInfo(const Function *F, const BlockFrequencyInfo *BFI, |
| 65 | const BranchProbabilityInfo *BPI, uint64_t MaxFreq, |
| 66 | std::optional<NodeIdFormatterTy> NodeIdFormatter) |
| 67 | : F(F), BFI(BFI), BPI(BPI), MaxFreq(MaxFreq), |
| 68 | NodeIdFormatter(NodeIdFormatter) { |
| 69 | ShowHeat = false; |
| 70 | EdgeWeights = !!BPI; // Print EdgeWeights when BPI is available. |
| 71 | RawWeights = !!BFI; // Print RawWeights when BFI is available. |
| 72 | } |
| 73 | |
| 74 | DOTFuncInfo::~DOTFuncInfo() = default; |
| 75 | |
| 76 | ModuleSlotTracker *DOTFuncInfo::getModuleSlotTracker() { |
| 77 | if (!MSTStorage) |
| 78 | MSTStorage = std::make_unique<ModuleSlotTracker>(args: F->getParent()); |
| 79 | return &*MSTStorage; |
| 80 | } |
| 81 | |
| 82 | PreservedAnalyses CFGViewerPass::run(Function &F, FunctionAnalysisManager &AM) { |
| 83 | const AnalysisOptions &Opts = getAnalysisOptions(F); |
| 84 | if (!Opts.cfg_func_name.empty() && !F.getName().contains(Other: Opts.cfg_func_name)) |
| 85 | return PreservedAnalyses::all(); |
| 86 | auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F); |
| 87 | auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F); |
| 88 | viewCFG(Opts, F, BFI, BPI, MaxFreq: getMaxFreq(F, BFI)); |
| 89 | return PreservedAnalyses::all(); |
| 90 | } |
| 91 | |
| 92 | PreservedAnalyses CFGOnlyViewerPass::run(Function &F, |
| 93 | FunctionAnalysisManager &AM) { |
| 94 | const AnalysisOptions &Opts = getAnalysisOptions(F); |
| 95 | if (!Opts.cfg_func_name.empty() && !F.getName().contains(Other: Opts.cfg_func_name)) |
| 96 | return PreservedAnalyses::all(); |
| 97 | auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F); |
| 98 | auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F); |
| 99 | viewCFG(Opts, F, BFI, BPI, MaxFreq: getMaxFreq(F, BFI), /*CFGOnly=*/true); |
| 100 | return PreservedAnalyses::all(); |
| 101 | } |
| 102 | |
| 103 | PreservedAnalyses CFGPrinterPass::run(Function &F, |
| 104 | FunctionAnalysisManager &AM) { |
| 105 | const AnalysisOptions &Opts = getAnalysisOptions(F); |
| 106 | if (!Opts.cfg_func_name.empty() && !F.getName().contains(Other: Opts.cfg_func_name)) |
| 107 | return PreservedAnalyses::all(); |
| 108 | auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F); |
| 109 | auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F); |
| 110 | writeCFGToDotFile(Opts, F, BFI, BPI, MaxFreq: getMaxFreq(F, BFI)); |
| 111 | return PreservedAnalyses::all(); |
| 112 | } |
| 113 | |
| 114 | PreservedAnalyses CFGOnlyPrinterPass::run(Function &F, |
| 115 | FunctionAnalysisManager &AM) { |
| 116 | const AnalysisOptions &Opts = getAnalysisOptions(F); |
| 117 | if (!Opts.cfg_func_name.empty() && !F.getName().contains(Other: Opts.cfg_func_name)) |
| 118 | return PreservedAnalyses::all(); |
| 119 | auto *BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F); |
| 120 | auto *BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F); |
| 121 | writeCFGToDotFile(Opts, F, BFI, BPI, MaxFreq: getMaxFreq(F, BFI), /*CFGOnly=*/true); |
| 122 | return PreservedAnalyses::all(); |
| 123 | } |
| 124 | |
| 125 | /// viewCFG - This function is meant for use from the debugger. You can just |
| 126 | /// say 'call F->viewCFG()' and a ghostview window should pop up from the |
| 127 | /// program, displaying the CFG of the current function. This depends on there |
| 128 | /// being a 'dot' and 'gv' program in your path. |
| 129 | /// |
| 130 | void Function::viewCFG() const { viewCFG(ViewCFGOnly: false, BFI: nullptr, BPI: nullptr); } |
| 131 | |
| 132 | void Function::viewCFG(const char *OutputFileName) const { |
| 133 | viewCFG(ViewCFGOnly: false, BFI: nullptr, BPI: nullptr, OutputFileName); |
| 134 | } |
| 135 | |
| 136 | void Function::viewCFG(bool ViewCFGOnly, const BlockFrequencyInfo *BFI, |
| 137 | const BranchProbabilityInfo *BPI, |
| 138 | const char *OutputFileName) const { |
| 139 | StringRef CFGFuncName = getAnalysisOptions(F: *this).cfg_func_name; |
| 140 | if (!CFGFuncName.empty() && !getName().contains(Other: CFGFuncName)) |
| 141 | return; |
| 142 | DOTFuncInfo CFGInfo(this, BFI, BPI, BFI ? getMaxFreq(F: *this, BFI) : 0); |
| 143 | ViewGraph(G: &CFGInfo, Name: OutputFileName ? OutputFileName : "cfg" + getName(), |
| 144 | ShortNames: ViewCFGOnly); |
| 145 | } |
| 146 | |
| 147 | /// viewCFGOnly - This function is meant for use from the debugger. It works |
| 148 | /// just like viewCFG, but it does not include the contents of basic blocks |
| 149 | /// into the nodes, just the label. If you are only interested in the CFG |
| 150 | /// this can make the graph smaller. |
| 151 | /// |
| 152 | void Function::viewCFGOnly() const { viewCFGOnly(BFI: nullptr, BPI: nullptr); } |
| 153 | |
| 154 | void Function::viewCFGOnly(const char *OutputFileName) const { |
| 155 | viewCFG(ViewCFGOnly: true, BFI: nullptr, BPI: nullptr, OutputFileName); |
| 156 | } |
| 157 | |
| 158 | void Function::viewCFGOnly(const BlockFrequencyInfo *BFI, |
| 159 | const BranchProbabilityInfo *BPI) const { |
| 160 | viewCFG(ViewCFGOnly: true, BFI, BPI); |
| 161 | } |
| 162 | |
| 163 | /// Find all blocks on the paths which terminate with a deoptimize or |
| 164 | /// unreachable (i.e. all blocks which are post-dominated by a deoptimize |
| 165 | /// or unreachable). These paths are hidden if the corresponding cl::opts |
| 166 | /// are enabled. |
| 167 | void DOTGraphTraits<DOTFuncInfo *>::computeDeoptOrUnreachablePaths( |
| 168 | const Function *F) { |
| 169 | const AnalysisOptions &Opts = getAnalysisOptions(F: *F); |
| 170 | auto evaluateBB = [&](const BasicBlock *Node) { |
| 171 | if (succ_empty(BB: Node)) { |
| 172 | const Instruction *TI = Node->getTerminator(); |
| 173 | isOnDeoptOrUnreachablePath[Node] = |
| 174 | (Opts.cfg_hide_unreachable_paths && isa<UnreachableInst>(Val: TI)) || |
| 175 | (Opts.cfg_hide_deoptimize_paths && |
| 176 | Node->getTerminatingDeoptimizeCall()); |
| 177 | return; |
| 178 | } |
| 179 | isOnDeoptOrUnreachablePath[Node] = |
| 180 | llvm::all_of(Range: successors(BB: Node), P: [this](const BasicBlock *BB) { |
| 181 | return isOnDeoptOrUnreachablePath[BB]; |
| 182 | }); |
| 183 | }; |
| 184 | /// The post order traversal iteration is done to know the status of |
| 185 | /// isOnDeoptOrUnreachablePath for all the successors on the current BB. |
| 186 | llvm::for_each(Range: post_order(G: &F->getEntryBlock()), F: evaluateBB); |
| 187 | } |
| 188 | |
| 189 | bool DOTGraphTraits<DOTFuncInfo *>::isNodeHidden(const BasicBlock *Node, |
| 190 | const DOTFuncInfo *CFGInfo) { |
| 191 | const AnalysisOptions &Opts = getAnalysisOptions(F: *CFGInfo->getFunction()); |
| 192 | if (Opts.cfg_hide_cold_paths) |
| 193 | if (auto *BFI = CFGInfo->getBFI()) { |
| 194 | BlockFrequency NodeFreq = BFI->getBlockFreq(BB: Node); |
| 195 | BlockFrequency EntryFreq = BFI->getEntryFreq(); |
| 196 | // Hide blocks with relative frequency below -cfg-hide-cold-paths. |
| 197 | if ((double)NodeFreq.getFrequency() / EntryFreq.getFrequency() < |
| 198 | *Opts.cfg_hide_cold_paths) |
| 199 | return true; |
| 200 | } |
| 201 | if (Opts.cfg_hide_unreachable_paths || Opts.cfg_hide_deoptimize_paths) { |
| 202 | if (!isOnDeoptOrUnreachablePath.contains(Val: Node)) |
| 203 | computeDeoptOrUnreachablePaths(F: Node->getParent()); |
| 204 | return isOnDeoptOrUnreachablePath[Node]; |
| 205 | } |
| 206 | return false; |
| 207 | } |
| 208 | |
| 209 | std::string DOTGraphTraits<DOTFuncInfo *>::getCompleteNodeLabel( |
| 210 | const BasicBlock *Node, DOTFuncInfo *CFGInfo, |
| 211 | function_ref<void(raw_string_ostream &, const BasicBlock &)> |
| 212 | HandleBasicBlock, |
| 213 | function_ref<void(std::string &, unsigned &, unsigned)> HandleComment) { |
| 214 | if (HandleBasicBlock) |
| 215 | return CompleteNodeLabelString(Node, HandleBasicBlock, HandleComment); |
| 216 | |
| 217 | // Default basic block printing |
| 218 | std::optional<ModuleSlotTracker> MSTStorage; |
| 219 | ModuleSlotTracker *MST = nullptr; |
| 220 | |
| 221 | if (CFGInfo) { |
| 222 | MST = CFGInfo->getModuleSlotTracker(); |
| 223 | } else { |
| 224 | MSTStorage.emplace(args: Node->getModule()); |
| 225 | MST = &*MSTStorage; |
| 226 | } |
| 227 | |
| 228 | return CompleteNodeLabelString( |
| 229 | Node, |
| 230 | HandleBasicBlock: function_ref<void(raw_string_ostream &, const BasicBlock &)>( |
| 231 | [MST](raw_string_ostream &OS, const BasicBlock &Node) -> void { |
| 232 | // Prepend label name |
| 233 | Node.printAsOperand(O&: OS, PrintType: false, MST&: *MST); |
| 234 | OS << ":\n" ; |
| 235 | |
| 236 | for (const Instruction &Inst : Node) { |
| 237 | Inst.print(O&: OS, MST&: *MST, /* IsForDebug */ false); |
| 238 | OS << '\n'; |
| 239 | } |
| 240 | }), |
| 241 | HandleComment); |
| 242 | } |
| 243 | |