1 //===- GraphWriter.cpp - Implements GraphWriter support routines ----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements misc. GraphWriter support routines.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/GraphWriter.h"
15 #include "DebugOptions.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/ErrorOr.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/Program.h"
27 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ManagedStatic.h"
35 #include <system_error>
42 struct CreateViewBackground
{
44 return new cl::opt
<bool>("view-background", cl::Hidden
,
45 cl::desc("Execute graph viewer in the background. "
46 "Creates tmp file litter."));
50 static ManagedStatic
<cl::opt
<bool>, CreateViewBackground
> ViewBackground
;
51 void llvm::initGraphWriterOptions() { *ViewBackground
; }
53 void llvm::initGraphWriterOptions() {}
56 std::string
llvm::DOT::EscapeString(const std::string
&Label
) {
57 std::string
Str(Label
);
58 for (unsigned i
= 0; i
!= Str
.length(); ++i
)
61 Str
.insert(Str
.begin()+i
, '\\'); // Escape character...
66 Str
.insert(Str
.begin()+i
, ' '); // Convert to two spaces
71 if (i
+1 != Str
.length())
73 case 'l': continue; // don't disturb \l
74 case '|': case '{': case '}':
75 Str
.erase(Str
.begin()+i
); continue;
82 Str
.insert(Str
.begin()+i
, '\\'); // Escape character...
83 ++i
; // don't infinite loop
89 /// Get a color string for this node number. Simply round-robin selects
90 /// from a reasonable number of colors.
91 StringRef
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
];
100 static std::string
replaceIllegalFilenameChars(std::string Filename
,
101 const char ReplacementChar
) {
102 std::string IllegalChars
=
103 is_style_windows(sys::path::Style::native
) ? "\\/:?\"<>|" : "/";
105 for (char IllegalChar
: IllegalChars
) {
106 std::replace(Filename
.begin(), Filename
.end(), IllegalChar
,
113 std::string
llvm::createGraphFilename(const Twine
&Name
, int &FD
) {
115 SmallString
<128> Filename
;
117 // Windows can't always handle long paths, so limit the length of the name.
118 std::string N
= Name
.str();
122 // Replace illegal characters in graph Filename with '_' if needed
123 std::string CleansedName
= replaceIllegalFilenameChars(N
, '_');
126 sys::fs::createTemporaryFile(CleansedName
, "dot", FD
, Filename
);
128 errs() << "Error: " << EC
.message() << "\n";
132 errs() << "Writing '" << Filename
<< "'... ";
133 return std::string(Filename
);
136 // Execute the graph viewer. Return true if there were errors.
137 static bool ExecGraphViewer(StringRef ExecPath
, std::vector
<StringRef
> &args
,
138 StringRef Filename
, bool wait
,
139 std::string
&ErrMsg
) {
141 if (sys::ExecuteAndWait(ExecPath
, args
, std::nullopt
, {}, 0, 0, &ErrMsg
)) {
142 errs() << "Error: " << ErrMsg
<< "\n";
145 sys::fs::remove(Filename
);
146 errs() << " done. \n";
148 sys::ExecuteNoWait(ExecPath
, args
, std::nullopt
, {}, 0, &ErrMsg
);
149 errs() << "Remember to erase graph file: " << Filename
<< "\n";
156 struct GraphSession
{
157 std::string LogBuffer
;
159 bool TryFindProgram(StringRef Names
, std::string
&ProgramPath
) {
160 raw_string_ostream
Log(LogBuffer
);
161 SmallVector
<StringRef
, 8> parts
;
162 Names
.split(parts
, '|');
163 for (auto Name
: parts
) {
164 if (ErrorOr
<std::string
> P
= sys::findProgramByName(Name
)) {
168 Log
<< " Tried '" << Name
<< "'\n";
174 } // end anonymous namespace
176 static const char *getProgramName(GraphProgram::Name program
) {
178 case GraphProgram::DOT
:
180 case GraphProgram::FDP
:
182 case GraphProgram::NEATO
:
184 case GraphProgram::TWOPI
:
186 case GraphProgram::CIRCO
:
189 llvm_unreachable("bad kind");
192 bool llvm::DisplayGraph(StringRef FilenameRef
, bool wait
,
193 GraphProgram::Name program
) {
194 std::string Filename
= std::string(FilenameRef
);
196 std::string ViewerPath
;
200 wait
&= !*ViewBackground
;
201 if (S
.TryFindProgram("open", ViewerPath
)) {
202 std::vector
<StringRef
> args
;
203 args
.push_back(ViewerPath
);
205 args
.push_back("-W");
206 args
.push_back(Filename
);
207 errs() << "Trying 'open' program... ";
208 if (!ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
))
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
))
222 if (S
.TryFindProgram("Graphviz", ViewerPath
)) {
223 std::vector
<StringRef
> args
;
224 args
.push_back(ViewerPath
);
225 args
.push_back(Filename
);
227 errs() << "Running 'Graphviz' program... ";
228 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
232 if (S
.TryFindProgram("xdot|xdot.py", ViewerPath
)) {
233 std::vector
<StringRef
> args
;
234 args
.push_back(ViewerPath
);
235 args
.push_back(Filename
);
237 args
.push_back("-f");
238 args
.push_back(getProgramName(program
));
240 errs() << "Running 'xdot.py' program... ";
241 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
251 ViewerKind Viewer
= VK_None
;
253 if (!Viewer
&& S
.TryFindProgram("open", ViewerPath
))
256 if (!Viewer
&& S
.TryFindProgram("gv", ViewerPath
))
257 Viewer
= VK_Ghostview
;
258 if (!Viewer
&& S
.TryFindProgram("xdg-open", ViewerPath
))
261 if (!Viewer
&& S
.TryFindProgram("cmd", ViewerPath
)) {
262 Viewer
= VK_CmdStart
;
266 // PostScript or PDF graph generator + PostScript/PDF viewer
267 std::string GeneratorPath
;
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");
274 std::vector
<StringRef
> args
;
275 args
.push_back(GeneratorPath
);
276 if (Viewer
== VK_CmdStart
)
277 args
.push_back("-Tpdf");
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
);
286 errs() << "Running '" << GeneratorPath
<< "' program... ";
288 if (ExecGraphViewer(GeneratorPath
, args
, Filename
, true, ErrMsg
))
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
;
296 args
.push_back(ViewerPath
);
299 args
.push_back("-W");
300 args
.push_back(OutputFilename
);
304 args
.push_back(OutputFilename
);
307 args
.push_back("--spartan");
308 args
.push_back(OutputFilename
);
311 args
.push_back("/S");
312 args
.push_back("/C");
314 (StringRef("start ") + (wait
? "/WAIT " : "") + OutputFilename
).str();
315 args
.push_back(StartArg
);
318 llvm_unreachable("Invalid viewer");
322 return ExecGraphViewer(ViewerPath
, args
, OutputFilename
, wait
, ErrMsg
);
326 if (S
.TryFindProgram("dotty", ViewerPath
)) {
327 std::vector
<StringRef
> args
;
328 args
.push_back(ViewerPath
);
329 args
.push_back(Filename
);
331 // Dotty spawns another app and doesn't wait until it returns
335 errs() << "Running 'dotty' program... ";
336 return ExecGraphViewer(ViewerPath
, args
, Filename
, wait
, ErrMsg
);
339 errs() << "Error: Couldn't find a usable graph viewer program:\n";
340 errs() << S
.LogBuffer
<< "\n";