LLVM  10.0.0svn
CFGPrinter.h
Go to the documentation of this file.
1 //===-- CFGPrinter.h - CFG printer external interface -----------*- 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 //
9 // This file defines a 'dot-cfg' analysis pass, which emits the
10 // cfg.<fnname>.dot file for each function in the program, with a graph of the
11 // CFG for that function.
12 //
13 // This file defines external functions that can be called to explicitly
14 // instantiate the CFG printer.
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #ifndef LLVM_ANALYSIS_CFGPRINTER_H
19 #define LLVM_ANALYSIS_CFGPRINTER_H
20 
21 #include "llvm/IR/CFG.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/PassManager.h"
27 
28 namespace llvm {
30  : public PassInfoMixin<CFGViewerPass> {
31 public:
33 };
34 
36  : public PassInfoMixin<CFGOnlyViewerPass> {
37 public:
39 };
40 
42  : public PassInfoMixin<CFGPrinterPass> {
43 public:
45 };
46 
48  : public PassInfoMixin<CFGOnlyPrinterPass> {
49 public:
51 };
52 
53 template<>
55 
57 
58  static std::string getGraphName(const Function *F) {
59  return "CFG for '" + F->getName().str() + "' function";
60  }
61 
62  static std::string getSimpleNodeLabel(const BasicBlock *Node,
63  const Function *) {
64  if (!Node->getName().empty())
65  return Node->getName().str();
66 
67  std::string Str;
68  raw_string_ostream OS(Str);
69 
70  Node->printAsOperand(OS, false);
71  return OS.str();
72  }
73 
74  static std::string getCompleteNodeLabel(const BasicBlock *Node,
75  const Function *) {
76  enum { MaxColumns = 80 };
77  std::string Str;
78  raw_string_ostream OS(Str);
79 
80  if (Node->getName().empty()) {
81  Node->printAsOperand(OS, false);
82  OS << ":";
83  }
84 
85  OS << *Node;
86  std::string OutStr = OS.str();
87  if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
88 
89  // Process string output to make it nicer...
90  unsigned ColNum = 0;
91  unsigned LastSpace = 0;
92  for (unsigned i = 0; i != OutStr.length(); ++i) {
93  if (OutStr[i] == '\n') { // Left justify
94  OutStr[i] = '\\';
95  OutStr.insert(OutStr.begin()+i+1, 'l');
96  ColNum = 0;
97  LastSpace = 0;
98  } else if (OutStr[i] == ';') { // Delete comments!
99  unsigned Idx = OutStr.find('\n', i+1); // Find end of line
100  OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
101  --i;
102  } else if (ColNum == MaxColumns) { // Wrap lines.
103  // Wrap very long names even though we can't find a space.
104  if (!LastSpace)
105  LastSpace = i;
106  OutStr.insert(LastSpace, "\\l...");
107  ColNum = i - LastSpace;
108  LastSpace = 0;
109  i += 3; // The loop will advance 'i' again.
110  }
111  else
112  ++ColNum;
113  if (OutStr[i] == ' ')
114  LastSpace = i;
115  }
116  return OutStr;
117  }
118 
119  std::string getNodeLabel(const BasicBlock *Node,
120  const Function *Graph) {
121  if (isSimple())
122  return getSimpleNodeLabel(Node, Graph);
123  else
124  return getCompleteNodeLabel(Node, Graph);
125  }
126 
127  static std::string getEdgeSourceLabel(const BasicBlock *Node,
129  // Label source of conditional branches with "T" or "F"
130  if (const BranchInst *BI = dyn_cast<BranchInst>(Node->getTerminator()))
131  if (BI->isConditional())
132  return (I == succ_begin(Node)) ? "T" : "F";
133 
134  // Label source of switch edges with the associated value.
135  if (const SwitchInst *SI = dyn_cast<SwitchInst>(Node->getTerminator())) {
136  unsigned SuccNo = I.getSuccessorIndex();
137 
138  if (SuccNo == 0) return "def";
139 
140  std::string Str;
141  raw_string_ostream OS(Str);
142  auto Case = *SwitchInst::ConstCaseIt::fromSuccessorIndex(SI, SuccNo);
143  OS << Case.getCaseValue()->getValue();
144  return OS.str();
145  }
146  return "";
147  }
148 
149  /// Display the raw branch weights from PGO.
151  const Function *F) {
152  const Instruction *TI = Node->getTerminator();
153  if (TI->getNumSuccessors() == 1)
154  return "";
155 
156  MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
157  if (!WeightsNode)
158  return "";
159 
160  MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
161  if (MDName->getString() != "branch_weights")
162  return "";
163 
164  unsigned OpNo = I.getSuccessorIndex() + 1;
165  if (OpNo >= WeightsNode->getNumOperands())
166  return "";
167  ConstantInt *Weight =
168  mdconst::dyn_extract<ConstantInt>(WeightsNode->getOperand(OpNo));
169  if (!Weight)
170  return "";
171 
172  // Prepend a 'W' to indicate that this is a weight rather than the actual
173  // profile count (due to scaling).
174  return ("label=\"W:" + Twine(Weight->getZExtValue()) + "\"").str();
175  }
176 };
177 } // End llvm namespace
178 
179 namespace llvm {
180  class FunctionPass;
183 } // End llvm namespace
184 
185 #endif
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:232
This class represents lattice values for constants.
Definition: AllocatorList.h:23
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: CFGPrinter.cpp:57
static std::string getGraphName(const Function *F)
Definition: CFGPrinter.h:58
FunctionPass * createCFGPrinterLegacyPassPass()
Definition: CFGPrinter.cpp:193
int getSuccessorIndex() const
This is used to interface between code that wants to operate on terminator instructions directly...
Definition: CFG.h:197
Metadata node.
Definition: Metadata.h:863
F(f)
std::string getEdgeAttributes(const BasicBlock *Node, succ_const_iterator I, const Function *F)
Display the raw branch weights from PGO.
Definition: CFGPrinter.h:150
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1068
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
static std::string getCompleteNodeLabel(const BasicBlock *Node, const Function *)
Definition: CFGPrinter.h:74
std::string getNodeLabel(const BasicBlock *Node, const Function *Graph)
Definition: CFGPrinter.h:119
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:102
static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI, unsigned SuccessorIndex)
Initializes case iterator for given SwitchInst and for given successor index.
static bool isSimple(Instruction *I)
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:372
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:244
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
StringRef getString() const
Definition: Metadata.cpp:463
FunctionPass * createCFGOnlyPrinterLegacyPassPass()
Definition: CFGPrinter.cpp:197
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:148
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
Conditional or Unconditional Branch instruction.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:284
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
Definition: AsmWriter.cpp:4356
std::string & str()
Flushes the stream contents to the target string and returns the string&#39;s reference.
Definition: raw_ostream.h:519
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to &#39;dot...
static std::string getSimpleNodeLabel(const BasicBlock *Node, const Function *)
Definition: CFGPrinter.h:62
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
#define I(x, y, z)
Definition: MD5.cpp:58
Multiway switch.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:503
aarch64 promote const
DefaultDOTGraphTraits - This class provides the default implementations of all of the DOTGraphTraits ...
A single uniqued string.
Definition: Metadata.h:603
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1074
static std::string getEdgeSourceLabel(const BasicBlock *Node, succ_const_iterator I)
Definition: CFGPrinter.h:127