LLVM 20.0.0git
GraphWriter.cpp
Go to the documentation of this file.
1//===- GraphWriter.cpp - Implements GraphWriter support routines ----------===//
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 implements misc. GraphWriter support routines.
10//
11//===----------------------------------------------------------------------===//
12
14
15#include "DebugOptions.h"
16
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Config/config.h"
25#include "llvm/Support/Path.h"
28
29#ifdef __APPLE__
32#endif
33
34#include <string>
35#include <system_error>
36#include <vector>
37
38using namespace llvm;
39
40#ifdef __APPLE__
41namespace {
42struct CreateViewBackground {
43 static void *call() {
44 return new cl::opt<bool>("view-background", cl::Hidden,
45 cl::desc("Execute graph viewer in the background. "
46 "Creates tmp file litter."));
47 }
48};
49} // namespace
50static ManagedStatic<cl::opt<bool>, CreateViewBackground> ViewBackground;
51void llvm::initGraphWriterOptions() { *ViewBackground; }
52#else
54#endif
55
56std::string llvm::DOT::EscapeString(const std::string &Label) {
57 std::string Str(Label);
58 for (unsigned i = 0; i != Str.length(); ++i)
59 switch (Str[i]) {
60 case '\n':
61 Str.insert(Str.begin()+i, '\\'); // Escape character...
62 ++i;
63 Str[i] = 'n';
64 break;
65 case '\t':
66 Str.insert(Str.begin()+i, ' '); // Convert to two spaces
67 ++i;
68 Str[i] = ' ';
69 break;
70 case '\\':
71 if (i+1 != Str.length())
72 switch (Str[i+1]) {
73 case 'l': continue; // don't disturb \l
74 case '|': case '{': case '}':
75 Str.erase(Str.begin()+i); continue;
76 default: break;
77 }
78 [[fallthrough]];
79 case '{': case '}':
80 case '<': case '>':
81 case '|': case '"':
82 Str.insert(Str.begin()+i, '\\'); // Escape character...
83 ++i; // don't infinite loop
84 break;
85 }
86 return Str;
87}
88
89/// Get a color string for this node number. Simply round-robin selects
90/// from a reasonable number of colors.
91StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
92 static const int NumColors = 20;
93 static const char* Colors[NumColors] = {
94 "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
95 "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
96 "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
97 return Colors[ColorNumber % NumColors];
98}
99
100static std::string replaceIllegalFilenameChars(std::string Filename,
101 const char ReplacementChar) {
102 std::string IllegalChars =
103 is_style_windows(sys::path::Style::native) ? "\\/:?\"<>|" : "/";
104
105 for (char IllegalChar : IllegalChars) {
106 std::replace(Filename.begin(), Filename.end(), IllegalChar,
107 ReplacementChar);
108 }
109
110 return Filename;
111}
112
113std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
114 FD = -1;
115 SmallString<128> Filename;
116
117 // Windows can't always handle long paths, so limit the length of the name.
118 std::string N = Name.str();
119 if (N.size() > 140)
120 N.resize(140);
121
122 // Replace illegal characters in graph Filename with '_' if needed
123 std::string CleansedName = replaceIllegalFilenameChars(N, '_');
124
125 std::error_code EC =
126 sys::fs::createTemporaryFile(CleansedName, "dot", FD, Filename);
127 if (EC) {
128 errs() << "Error: " << EC.message() << "\n";
129 return "";
130 }
131
132 errs() << "Writing '" << Filename << "'... ";
133 return std::string(Filename);
134}
135
136// Execute the graph viewer. Return true if there were errors.
137static bool ExecGraphViewer(StringRef ExecPath, std::vector<StringRef> &args,
138 StringRef Filename, bool wait,
139 std::string &ErrMsg) {
140 if (wait) {
141 if (sys::ExecuteAndWait(ExecPath, args, std::nullopt, {}, 0, 0, &ErrMsg)) {
142 errs() << "Error: " << ErrMsg << "\n";
143 return true;
144 }
145 sys::fs::remove(Filename);
146 errs() << " done. \n";
147 } else {
148 sys::ExecuteNoWait(ExecPath, args, std::nullopt, {}, 0, &ErrMsg);
149 errs() << "Remember to erase graph file: " << Filename << "\n";
150 }
151 return false;
152}
153
154namespace {
155
156struct GraphSession {
157 std::string LogBuffer;
158
159 bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
160 raw_string_ostream Log(LogBuffer);
162 Names.split(parts, '|');
163 for (auto Name : parts) {
165 ProgramPath = *P;
166 return true;
167 }
168 Log << " Tried '" << Name << "'\n";
169 }
170 return false;
171 }
172};
173
174} // end anonymous namespace
175
176static const char *getProgramName(GraphProgram::Name program) {
177 switch (program) {
179 return "dot";
181 return "fdp";
183 return "neato";
185 return "twopi";
187 return "circo";
188 }
189 llvm_unreachable("bad kind");
190}
191
192bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
193 GraphProgram::Name program) {
194 std::string Filename = std::string(FilenameRef);
195 std::string ErrMsg;
196 std::string ViewerPath;
197 GraphSession S;
198
199#ifdef __APPLE__
200 wait &= !*ViewBackground;
201 if (S.TryFindProgram("open", ViewerPath)) {
202 std::vector<StringRef> args;
203 args.push_back(ViewerPath);
204 if (wait)
205 args.push_back("-W");
206 args.push_back(Filename);
207 errs() << "Trying 'open' program... ";
208 if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
209 return false;
210 }
211#endif
212 if (S.TryFindProgram("xdg-open", ViewerPath)) {
213 std::vector<StringRef> args;
214 args.push_back(ViewerPath);
215 args.push_back(Filename);
216 errs() << "Trying 'xdg-open' program... ";
217 if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
218 return false;
219 }
220
221 // Graphviz
222 if (S.TryFindProgram("Graphviz", ViewerPath)) {
223 std::vector<StringRef> args;
224 args.push_back(ViewerPath);
225 args.push_back(Filename);
226
227 errs() << "Running 'Graphviz' program... ";
228 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
229 }
230
231 // xdot
232 if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
233 std::vector<StringRef> args;
234 args.push_back(ViewerPath);
235 args.push_back(Filename);
236
237 args.push_back("-f");
238 args.push_back(getProgramName(program));
239
240 errs() << "Running 'xdot.py' program... ";
241 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
242 }
243
244 enum ViewerKind {
245 VK_None,
246 VK_OSXOpen,
247 VK_XDGOpen,
248 VK_Ghostview,
249 VK_CmdStart
250 };
251 ViewerKind Viewer = VK_None;
252#ifdef __APPLE__
253 if (!Viewer && S.TryFindProgram("open", ViewerPath))
254 Viewer = VK_OSXOpen;
255#endif
256 if (!Viewer && S.TryFindProgram("gv", ViewerPath))
257 Viewer = VK_Ghostview;
258 if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath))
259 Viewer = VK_XDGOpen;
260#ifdef _WIN32
261 if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) {
262 Viewer = VK_CmdStart;
263 }
264#endif
265
266 // PostScript or PDF graph generator + PostScript/PDF viewer
267 std::string GeneratorPath;
268 if (Viewer &&
269 (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
270 S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
271 std::string OutputFilename =
272 Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps");
273
274 std::vector<StringRef> args;
275 args.push_back(GeneratorPath);
276 if (Viewer == VK_CmdStart)
277 args.push_back("-Tpdf");
278 else
279 args.push_back("-Tps");
280 args.push_back("-Nfontname=Courier");
281 args.push_back("-Gsize=7.5,10");
282 args.push_back(Filename);
283 args.push_back("-o");
284 args.push_back(OutputFilename);
285
286 errs() << "Running '" << GeneratorPath << "' program... ";
287
288 if (ExecGraphViewer(GeneratorPath, args, Filename, true, ErrMsg))
289 return true;
290
291 // The lifetime of StartArg must include the call of ExecGraphViewer
292 // because the args are passed as vector of char*.
293 std::string StartArg;
294
295 args.clear();
296 args.push_back(ViewerPath);
297 switch (Viewer) {
298 case VK_OSXOpen:
299 args.push_back("-W");
300 args.push_back(OutputFilename);
301 break;
302 case VK_XDGOpen:
303 wait = false;
304 args.push_back(OutputFilename);
305 break;
306 case VK_Ghostview:
307 args.push_back("--spartan");
308 args.push_back(OutputFilename);
309 break;
310 case VK_CmdStart:
311 args.push_back("/S");
312 args.push_back("/C");
313 StartArg =
314 (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str();
315 args.push_back(StartArg);
316 break;
317 case VK_None:
318 llvm_unreachable("Invalid viewer");
319 }
320
321 ErrMsg.clear();
322 return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg);
323 }
324
325 // dotty
326 if (S.TryFindProgram("dotty", ViewerPath)) {
327 std::vector<StringRef> args;
328 args.push_back(ViewerPath);
329 args.push_back(Filename);
330
331// Dotty spawns another app and doesn't wait until it returns
332#ifdef _WIN32
333 wait = false;
334#endif
335 errs() << "Running 'dotty' program... ";
336 return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
337 }
338
339 errs() << "Error: Couldn't find a usable graph viewer program:\n";
340 errs() << S.LogBuffer << "\n";
341 return true;
342}
std::string Name
Provides ErrorOr<T> smart pointer.
static std::string replaceIllegalFilenameChars(std::string Filename, const char ReplacementChar)
static bool ExecGraphViewer(StringRef ExecPath, std::vector< StringRef > &args, StringRef Filename, bool wait, std::string &ErrMsg)
static const char * getProgramName(GraphProgram::Name program)
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
nvptx lower args
#define P(N)
This file defines the SmallString class.
This file defines the SmallVector class.
Represents either an error or a value T.
Definition: ErrorOr.h:56
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:83
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:700
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::string EscapeString(const std::string &Label)
Definition: GraphWriter.cpp:56
StringRef getColorString(unsigned NodeNumber)
Get a color string for this node number.
Definition: GraphWriter.cpp:91
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition: Path.cpp:863
ProcessInfo ExecuteNoWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, BitVector *AffinityMask=nullptr, bool DetachProcess=false)
Similar to ExecuteAndWait, but returns immediately.
Definition: Program.cpp:57
int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition: Program.cpp:32
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool DisplayGraph(StringRef Filename, bool wait=true, GraphProgram::Name program=GraphProgram::DOT)
std::string createGraphFilename(const Twine &Name, int &FD)
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void initGraphWriterOptions()
Definition: GraphWriter.cpp:53
#define N