1 //===- debug.cpp ----------------------------------------------------------===//
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 is a part of the ORC runtime support library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "debug.h"
14 
15 #include <cassert>
16 #include <cstdio>
17 #include <cstdlib>
18 
19 namespace __orc_rt {
20 
21 #ifndef NDEBUG
22 
23 std::atomic<const char *> DebugTypes;
24 char DebugTypesAll;
25 char DebugTypesNone;
26 
27 /// Sets the DebugState and DebugTypes values -- this function may be called
28 /// concurrently on multiple threads, but will always assign the same values so
29 /// this should be safe.
30 const char *initializeDebug() {
31   if (const char *DT = getenv("ORC_RT_DEBUG")) {
32     // If ORC_RT_DEBUG=1 then log everything.
33     if (strcmp(DT, "1") == 0) {
34       DebugTypes.store(&DebugTypesAll, std::memory_order_relaxed);
35       return &DebugTypesAll;
36     }
37 
38     // If ORC_RT_DEBUG is non-empty then record the string for use in
39     // debugTypeEnabled.
40     if (strcmp(DT, "") != 0) {
41       DebugTypes.store(DT, std::memory_order_relaxed);
42       return DT;
43     }
44   }
45 
46   // If ORT_RT_DEBUG is undefined or defined as empty then log nothing.
47   DebugTypes.store(&DebugTypesNone, std::memory_order_relaxed);
48   return &DebugTypesNone;
49 }
50 
51 bool debugTypeEnabled(const char *Type, const char *Types) {
52   assert(Types && Types != &DebugTypesAll && Types != &DebugTypesNone &&
53          "Invalid Types value");
54   size_t TypeLen = strlen(Type);
55   const char *Start = Types;
56   const char *End = Start;
57 
58   do {
59     if (*End == '\0' || *End == ',') {
60       size_t ItemLen = End - Start;
61       if (ItemLen == TypeLen && memcmp(Type, Start, TypeLen) == 0)
62         return true;
63       if (*End == '\0')
64         return false;
65       Start = End + 1;
66     }
67     ++End;
68   } while (true);
69 }
70 
71 void printdbg(const char *format, ...) {
72   va_list Args;
73   va_start(Args, format);
74   vfprintf(stderr, format, Args);
75   va_end(Args);
76 }
77 
78 #endif // !NDEBUG
79 
80 } // end namespace __orc_rt
81