1 //===-- Debug.cpp - An easy way to add debug output to your code ----------===//
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 a handy way of adding debugging information to your
10 // code, without it being enabled all of the time, and without having to add
11 // command line options to enable it.
12 //
13 // In particular, just wrap your code with the LLVM_DEBUG() macro, and it will
14 // be enabled automatically if you specify '-debug' on the command-line.
15 // Alternatively, you can also use the SET_DEBUG_TYPE("foo") macro to specify
16 // that your debug code belongs to class "foo".  Then, on the command line, you
17 // can specify '-debug-only=foo' to enable JUST the debug information for the
18 // foo class.
19 //
20 // When compiling without assertions, the -debug-* options and all code in
21 // LLVM_DEBUG() statements disappears, so it does not affect the runtime of the
22 // code.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/Support/circular_raw_ostream.h"
31 #include "llvm/Support/raw_ostream.h"
32 
33 #include "DebugOptions.h"
34 
35 #undef isCurrentDebugType
36 #undef setCurrentDebugType
37 #undef setCurrentDebugTypes
38 
39 using namespace llvm;
40 
41 // Even though LLVM might be built with NDEBUG, define symbols that the code
42 // built without NDEBUG can depend on via the llvm/Support/Debug.h header.
43 namespace llvm {
44 /// Exported boolean set by the -debug option.
45 bool DebugFlag = false;
46 
47 static ManagedStatic<std::vector<std::string>> CurrentDebugType;
48 
49 /// Return true if the specified string is the debug type
50 /// specified on the command line, or if none was specified on the command line
51 /// with the -debug-only=X option.
52 bool isCurrentDebugType(const char *DebugType) {
53   if (CurrentDebugType->empty())
54     return true;
55   // See if DebugType is in list. Note: do not use find() as that forces us to
56   // unnecessarily create an std::string instance.
57   for (auto &d : *CurrentDebugType) {
58     if (d == DebugType)
59       return true;
60   }
61   return false;
62 }
63 
64 void setCurrentDebugType(const char *Type) {
65   setCurrentDebugTypes(&Type, 1);
66 }
67 
68 void setCurrentDebugTypes(const char **Types, unsigned Count) {
69   CurrentDebugType->clear();
70   for (size_t T = 0; T < Count; ++T)
71     CurrentDebugType->push_back(Types[T]);
72 }
73 } // namespace llvm
74 
75 // All Debug.h functionality is a no-op in NDEBUG mode.
76 #ifndef NDEBUG
77 
78 namespace {
79 struct CreateDebug {
80   static void *call() {
81     return new cl::opt<bool, true>("debug", cl::desc("Enable debug output"),
82                                    cl::Hidden, cl::location(DebugFlag));
83   }
84 };
85 
86 // -debug-buffer-size - Buffer the last N characters of debug output
87 //until program termination.
88 struct CreateDebugBufferSize {
89   static void *call() {
90     return new cl::opt<unsigned>(
91         "debug-buffer-size",
92         cl::desc("Buffer the last N characters of debug output "
93                  "until program termination. "
94                  "[default 0 -- immediate print-out]"),
95         cl::Hidden, cl::init(0));
96   }
97 };
98 } // namespace
99 
100 // -debug - Command line option to enable the DEBUG statements in the passes.
101 // This flag may only be enabled in debug builds.
102 static ManagedStatic<cl::opt<bool, true>, CreateDebug> Debug;
103 static ManagedStatic<cl::opt<unsigned>, CreateDebugBufferSize> DebugBufferSize;
104 
105 namespace {
106 
107 struct DebugOnlyOpt {
108   void operator=(const std::string &Val) const {
109     if (Val.empty())
110       return;
111     DebugFlag = true;
112     SmallVector<StringRef,8> dbgTypes;
113     StringRef(Val).split(dbgTypes, ',', -1, false);
114     for (auto dbgType : dbgTypes)
115       CurrentDebugType->push_back(std::string(dbgType));
116   }
117 };
118 } // namespace
119 
120 static DebugOnlyOpt DebugOnlyOptLoc;
121 
122 namespace {
123 struct CreateDebugOnly {
124   static void *call() {
125     return new cl::opt<DebugOnlyOpt, true, cl::parser<std::string>>(
126         "debug-only",
127         cl::desc("Enable a specific type of debug output (comma separated list "
128                  "of types)"),
129         cl::Hidden, cl::value_desc("debug string"),
130         cl::location(DebugOnlyOptLoc), cl::ValueRequired);
131   }
132 };
133 } // namespace
134 
135 static ManagedStatic<cl::opt<DebugOnlyOpt, true, cl::parser<std::string>>,
136                      CreateDebugOnly>
137     DebugOnly;
138 
139 void llvm::initDebugOptions() {
140   *Debug;
141   *DebugBufferSize;
142   *DebugOnly;
143 }
144 
145 // Signal handlers - dump debug output on termination.
146 static void debug_user_sig_handler(void *Cookie) {
147   // This is a bit sneaky.  Since this is under #ifndef NDEBUG, we
148   // know that debug mode is enabled and dbgs() really is a
149   // circular_raw_ostream.  If NDEBUG is defined, then dbgs() ==
150   // errs() but this will never be invoked.
151   llvm::circular_raw_ostream &dbgout =
152       static_cast<circular_raw_ostream &>(llvm::dbgs());
153   dbgout.flushBufferWithBanner();
154 }
155 
156 /// dbgs - Return a circular-buffered debug stream.
157 raw_ostream &llvm::dbgs() {
158   // Do one-time initialization in a thread-safe way.
159   static struct dbgstream {
160     circular_raw_ostream strm;
161 
162     dbgstream()
163         : strm(errs(), "*** Debug Log Output ***\n",
164                (!EnableDebugBuffering || !DebugFlag) ? 0 : *DebugBufferSize) {
165       if (EnableDebugBuffering && DebugFlag && *DebugBufferSize != 0)
166         // TODO: Add a handler for SIGUSER1-type signals so the user can
167         // force a debug dump.
168         sys::AddSignalHandler(&debug_user_sig_handler, nullptr);
169       // Otherwise we've already set the debug stream buffer size to
170       // zero, disabling buffering so it will output directly to errs().
171     }
172   } thestrm;
173 
174   return thestrm.strm;
175 }
176 
177 #else
178 // Avoid "has no symbols" warning.
179 namespace llvm {
180   /// dbgs - Return errs().
181   raw_ostream &dbgs() {
182     return errs();
183   }
184 }
185 void llvm::initDebugOptions() {}
186 #endif
187 
188 /// EnableDebugBuffering - Turn on signal handler installation.
189 ///
190 bool llvm::EnableDebugBuffering = false;
191