1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
|
//===- unittests/Support/TimeProfilerTest.cpp -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/VirtualFileSystem.h"
#include <stack>
#include "gtest/gtest.h"
#include <tuple>
using namespace clang;
using namespace llvm;
namespace {
// Should be called before testing.
void setupProfiler() {
timeTraceProfilerInitialize(/*TimeTraceGranularity=*/0, "test",
/*TimeTraceVerbose=*/true);
}
// Should be called after `compileFromString()`.
// Returns profiler's JSON dump.
std::string teardownProfiler() {
SmallVector<char, 1024> SmallVec;
raw_svector_ostream OS(SmallVec);
timeTraceProfilerWrite(OS);
timeTraceProfilerCleanup();
return OS.str().str();
}
// Returns true if code compiles successfully.
// We only parse AST here. This is enough for constexpr evaluation.
bool compileFromString(StringRef Code, StringRef Standard, StringRef File,
llvm::StringMap<std::string> Headers = {}) {
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> FS(
new llvm::vfs::InMemoryFileSystem());
FS->addFile(File, 0, MemoryBuffer::getMemBuffer(Code));
for (const auto &Header : Headers) {
FS->addFile(Header.getKey(), 0,
MemoryBuffer::getMemBuffer(Header.getValue()));
}
llvm::IntrusiveRefCntPtr<FileManager> Files(
new FileManager(FileSystemOptions(), FS));
auto Invocation = std::make_shared<CompilerInvocation>();
std::vector<const char *> Args = {Standard.data(), File.data()};
DiagnosticOptions InvocationDiagOpts;
auto InvocationDiags =
CompilerInstance::createDiagnostics(*FS, InvocationDiagOpts);
CompilerInvocation::CreateFromArgs(*Invocation, Args, *InvocationDiags);
CompilerInstance Compiler(std::move(Invocation));
Compiler.createDiagnostics(Files->getVirtualFileSystem());
Compiler.setFileManager(Files.get());
class TestFrontendAction : public ASTFrontendAction {
private:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override {
return std::make_unique<ASTConsumer>();
}
} Action;
return Compiler.ExecuteAction(Action);
}
std::string GetMetadata(json::Object *Event) {
std::string M;
llvm::raw_string_ostream OS(M);
if (json::Object *Args = Event->getObject("args")) {
if (auto Detail = Args->getString("detail"))
OS << Detail;
// Use only filename to not include os-specific path separators.
if (auto File = Args->getString("file"))
OS << (M.empty() ? "" : ", ") << llvm::sys::path::filename(*File);
if (auto Line = Args->getInteger("line"))
OS << ":" << *Line;
}
return M;
}
// Returns pretty-printed trace graph.
std::string buildTraceGraph(StringRef Json) {
struct EventRecord {
int64_t TimestampBegin;
int64_t TimestampEnd;
std::string Name;
std::string Metadata;
};
std::vector<EventRecord> Events;
// Parse `EventRecord`s from JSON dump.
Expected<json::Value> Root = json::parse(Json);
if (!Root)
return "";
for (json::Value &TraceEventValue :
*Root->getAsObject()->getArray("traceEvents")) {
json::Object *TraceEventObj = TraceEventValue.getAsObject();
int64_t TimestampBegin = TraceEventObj->getInteger("ts").value_or(0);
int64_t TimestampEnd =
TimestampBegin + TraceEventObj->getInteger("dur").value_or(0);
std::string Name = TraceEventObj->getString("name").value_or("").str();
std::string Metadata = GetMetadata(TraceEventObj);
// Source events are asynchronous events and may not perfectly nest the
// synchronous events. Skip testing them.
if (Name == "Source")
continue;
// This is a "summary" event, like "Total PerformPendingInstantiations",
// skip it
if (TimestampBegin == 0)
continue;
Events.emplace_back(
EventRecord{TimestampBegin, TimestampEnd, Name, Metadata});
}
// There can be nested events that are very fast, for example:
// {"name":"EvaluateAsBooleanCondition",... ,"ts":2380,"dur":1}
// {"name":"EvaluateAsRValue",... ,"ts":2380,"dur":1}
// Therefore we should reverse the events list, so that events that have
// started earlier are first in the list.
// Then do a stable sort, we need it for the trace graph.
std::reverse(Events.begin(), Events.end());
llvm::stable_sort(Events, [](const auto &lhs, const auto &rhs) {
return std::make_pair(lhs.TimestampBegin, -lhs.TimestampEnd) <
std::make_pair(rhs.TimestampBegin, -rhs.TimestampEnd);
});
std::stringstream Stream;
// Write a newline for better testing with multiline string literal.
Stream << "\n";
// Keep the current event stack.
std::stack<const EventRecord *> EventStack;
for (const auto &Event : Events) {
// Pop every event in the stack until meeting the parent event.
while (!EventStack.empty()) {
bool InsideCurrentEvent =
Event.TimestampBegin >= EventStack.top()->TimestampBegin &&
Event.TimestampEnd <= EventStack.top()->TimestampEnd;
// Presumably due to timer rounding, PerformPendingInstantiations often
// appear to be within the timer interval of the immediately previous
// event group. We always know these events occur at level 1, not level 2,
// in our tests, so pop an event in that case.
if (InsideCurrentEvent && Event.Name == "PerformPendingInstantiations" &&
EventStack.size() == 2) {
InsideCurrentEvent = false;
}
if (!InsideCurrentEvent)
EventStack.pop();
else
break;
}
EventStack.push(&Event);
// Write indentaion, name, detail, newline.
for (size_t i = 1; i < EventStack.size(); ++i) {
Stream << "| ";
}
Stream.write(Event.Name.data(), Event.Name.size());
if (!Event.Metadata.empty()) {
Stream << " (";
Stream.write(Event.Metadata.data(), Event.Metadata.size());
Stream << ")";
}
Stream << "\n";
}
return Stream.str();
}
} // namespace
TEST(TimeProfilerTest, ConstantEvaluationCxx20) {
std::string Code = R"(
void print(double value);
namespace slow_namespace {
consteval double slow_func() {
double d = 0.0;
for (int i = 0; i < 100; ++i) { // 8th line
d += i; // 9th line
}
return d;
}
} // namespace slow_namespace
void slow_test() {
constexpr auto slow_value = slow_namespace::slow_func(); // 17th line
print(slow_namespace::slow_func()); // 18th line
print(slow_value);
}
int slow_arr[12 + 34 * 56 + // 22nd line
static_cast<int>(slow_namespace::slow_func())]; // 23rd line
constexpr int slow_init_list[] = {1, 1, 2, 3, 5, 8, 13, 21}; // 25th line
)";
setupProfiler();
ASSERT_TRUE(compileFromString(Code, "-std=c++20", "test.cc"));
std::string Json = teardownProfiler();
ASSERT_EQ(R"(
Frontend (test.cc)
| ParseDeclarationOrFunctionDefinition (test.cc:2:1)
| ParseDeclarationOrFunctionDefinition (test.cc:6:1)
| | ParseFunctionDefinition (slow_func)
| | | EvaluateAsRValue (<test.cc:8:21>)
| | | EvaluateForOverflow (<test.cc:8:21, col:25>)
| | | EvaluateForOverflow (<test.cc:8:30, col:32>)
| | | EvaluateAsRValue (<test.cc:9:14>)
| | | EvaluateForOverflow (<test.cc:9:9, col:14>)
| | | isPotentialConstantExpr (slow_namespace::slow_func)
| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)
| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)
| | | EvaluateAsBooleanCondition (<test.cc:8:21, col:25>)
| | | | EvaluateAsRValue (<test.cc:8:21, col:25>)
| ParseDeclarationOrFunctionDefinition (test.cc:16:1)
| | ParseFunctionDefinition (slow_test)
| | | EvaluateAsInitializer (slow_value)
| | | EvaluateAsConstantExpr (<test.cc:17:33, col:59>)
| | | EvaluateAsConstantExpr (<test.cc:18:11, col:37>)
| ParseDeclarationOrFunctionDefinition (test.cc:22:1)
| | EvaluateAsConstantExpr (<test.cc:23:31, col:57>)
| | EvaluateAsRValue (<test.cc:22:14, line:23:58>)
| ParseDeclarationOrFunctionDefinition (test.cc:25:1)
| | EvaluateAsInitializer (slow_init_list)
| PerformPendingInstantiations
)",
buildTraceGraph(Json));
}
TEST(TimeProfilerTest, ClassTemplateInstantiations) {
std::string Code = R"(
template<class T>
struct S
{
void foo() {}
void bar();
};
template struct S<double>; // explicit instantiation of S<double>
void user() {
S<int> a; // implicit instantiation of S<int>
S<float>* b;
b->foo(); // implicit instatiation of S<float> and S<float>::foo()
}
)";
setupProfiler();
ASSERT_TRUE(compileFromString(Code, "-std=c++20", "test.cc"));
std::string Json = teardownProfiler();
ASSERT_EQ(R"(
Frontend (test.cc)
| ParseClass (S)
| InstantiateClass (S<double>, test.cc:9)
| InstantiateFunction (S<double>::foo, test.cc:5)
| ParseDeclarationOrFunctionDefinition (test.cc:11:5)
| | ParseFunctionDefinition (user)
| | | InstantiateClass (S<int>, test.cc:3)
| | | InstantiateClass (S<float>, test.cc:3)
| | | DeferInstantiation (S<float>::foo)
| PerformPendingInstantiations
| | InstantiateFunction (S<float>::foo, test.cc:5)
)",
buildTraceGraph(Json));
}
TEST(TimeProfilerTest, TemplateInstantiations) {
std::string B_H = R"(
template <typename T>
T fooC(T t) {
return T();
}
template <typename T>
constexpr T fooB(T t) {
return fooC(t);
}
#define MacroTemp(x) template <typename T> void foo##x(T) { T(); }
)";
std::string A_H = R"(
#include "b.h"
MacroTemp(MTA)
template <typename T>
void fooA(T t) { fooB(t); fooMTA(t); }
)";
std::string Code = R"(
#include "a.h"
void user() { fooA(0); }
)";
setupProfiler();
ASSERT_TRUE(compileFromString(Code, "-std=c++20", "test.cc",
/*Headers=*/{{"a.h", A_H}, {"b.h", B_H}}));
std::string Json = teardownProfiler();
ASSERT_EQ(R"(
Frontend (test.cc)
| ParseFunctionDefinition (fooC)
| ParseFunctionDefinition (fooB)
| ParseFunctionDefinition (fooMTA)
| ParseFunctionDefinition (fooA)
| ParseDeclarationOrFunctionDefinition (test.cc:3:5)
| | ParseFunctionDefinition (user)
| | | DeferInstantiation (fooA<int>)
| PerformPendingInstantiations
| | InstantiateFunction (fooA<int>, a.h:7)
| | | InstantiateFunction (fooB<int>, b.h:8)
| | | | DeferInstantiation (fooC<int>)
| | | DeferInstantiation (fooMTA<int>)
| | | InstantiateFunction (fooC<int>, b.h:3)
| | | InstantiateFunction (fooMTA<int>, a.h:4)
)",
buildTraceGraph(Json));
}
TEST(TimeProfilerTest, ConstantEvaluationC99) {
std::string Code = R"(
struct {
short quantval[4]; // 3rd line
} value;
)";
setupProfiler();
ASSERT_TRUE(compileFromString(Code, "-std=c99", "test.c"));
std::string Json = teardownProfiler();
ASSERT_EQ(R"(
Frontend (test.c)
| ParseDeclarationOrFunctionDefinition (test.c:2:1)
| | isIntegerConstantExpr (<test.c:3:18>)
| | EvaluateKnownConstIntCheckOverflow (<test.c:3:18>)
| PerformPendingInstantiations
)",
buildTraceGraph(Json));
}
|