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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
|
//===-- HeaderIncludeGen.cpp - Generate Header Includes -------------------===//
//
// 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/DependencyOutputOptions.h"
#include "clang/Frontend/Utils.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
class HeaderIncludesCallback : public PPCallbacks {
SourceManager &SM;
raw_ostream *OutputFile;
const DependencyOutputOptions &DepOpts;
unsigned CurrentIncludeDepth;
bool HasProcessedPredefines;
bool OwnsOutputFile;
bool ShowAllHeaders;
bool ShowDepth;
bool MSStyle;
public:
HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,
raw_ostream *OutputFile_,
const DependencyOutputOptions &DepOpts,
bool OwnsOutputFile_, bool ShowDepth_, bool MSStyle_)
: SM(PP->getSourceManager()), OutputFile(OutputFile_), DepOpts(DepOpts),
CurrentIncludeDepth(0), HasProcessedPredefines(false),
OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),
ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}
~HeaderIncludesCallback() override {
if (OwnsOutputFile)
delete OutputFile;
}
HeaderIncludesCallback(const HeaderIncludesCallback &) = delete;
HeaderIncludesCallback &operator=(const HeaderIncludesCallback &) = delete;
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override;
void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) override;
private:
bool ShouldShowHeader(SrcMgr::CharacteristicKind HeaderType) {
if (!DepOpts.IncludeSystemHeaders && isSystem(HeaderType))
return false;
// Show the current header if we are (a) past the predefines, or (b) showing
// all headers and in the predefines at a depth past the initial file and
// command line buffers.
return (HasProcessedPredefines ||
(ShowAllHeaders && CurrentIncludeDepth > 2));
}
};
/// A callback for emitting header usage information to a file in JSON. Each
/// line in the file is a JSON object that includes the source file name and
/// the list of headers directly or indirectly included from it. For example:
///
/// {"source":"/tmp/foo.c",
/// "includes":["/usr/include/stdio.h", "/usr/include/stdlib.h"]}
///
/// To reduce the amount of data written to the file, we only record system
/// headers that are directly included from a file that isn't in the system
/// directory.
class HeaderIncludesJSONCallback : public PPCallbacks {
SourceManager &SM;
raw_ostream *OutputFile;
bool OwnsOutputFile;
SmallVector<std::string, 16> IncludedHeaders;
public:
HeaderIncludesJSONCallback(const Preprocessor *PP, raw_ostream *OutputFile_,
bool OwnsOutputFile_)
: SM(PP->getSourceManager()), OutputFile(OutputFile_),
OwnsOutputFile(OwnsOutputFile_) {}
~HeaderIncludesJSONCallback() override {
if (OwnsOutputFile)
delete OutputFile;
}
HeaderIncludesJSONCallback(const HeaderIncludesJSONCallback &) = delete;
HeaderIncludesJSONCallback &
operator=(const HeaderIncludesJSONCallback &) = delete;
void EndOfMainFile() override;
void FileChanged(SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind FileType,
FileID PrevFID) override;
void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) override;
};
/// A callback for emitting direct header and module usage information to a
/// file in JSON. The output format is like HeaderIncludesJSONCallback but has
/// an array of separate entries, one for each non-system source file used in
/// the compilation showing only the direct includes and imports from that file.
class HeaderIncludesDirectPerFileCallback : public PPCallbacks {
SourceManager &SM;
HeaderSearch &HSI;
raw_ostream *OutputFile;
bool OwnsOutputFile;
using DependencyMap = llvm::DenseMap<FileEntryRef, SmallVector<FileEntryRef>>;
DependencyMap Dependencies;
public:
HeaderIncludesDirectPerFileCallback(const Preprocessor *PP,
raw_ostream *OutputFile_,
bool OwnsOutputFile_)
: SM(PP->getSourceManager()), HSI(PP->getHeaderSearchInfo()),
OutputFile(OutputFile_), OwnsOutputFile(OwnsOutputFile_) {}
~HeaderIncludesDirectPerFileCallback() override {
if (OwnsOutputFile)
delete OutputFile;
}
HeaderIncludesDirectPerFileCallback(
const HeaderIncludesDirectPerFileCallback &) = delete;
HeaderIncludesDirectPerFileCallback &
operator=(const HeaderIncludesDirectPerFileCallback &) = delete;
void EndOfMainFile() override;
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange,
OptionalFileEntryRef File, StringRef SearchPath,
StringRef RelativePath, const Module *SuggestedModule,
bool ModuleImported,
SrcMgr::CharacteristicKind FileType) override;
void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path,
const Module *Imported) override;
};
}
static void PrintHeaderInfo(raw_ostream *OutputFile, StringRef Filename,
bool ShowDepth, unsigned CurrentIncludeDepth,
bool MSStyle) {
// Write to a temporary string to avoid unnecessary flushing on errs().
SmallString<512> Pathname(Filename);
if (!MSStyle)
Lexer::Stringify(Pathname);
SmallString<256> Msg;
if (MSStyle)
Msg += "Note: including file:";
if (ShowDepth) {
// The main source file is at depth 1, so skip one dot.
for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
Msg += MSStyle ? ' ' : '.';
if (!MSStyle)
Msg += ' ';
}
Msg += Pathname;
Msg += '\n';
*OutputFile << Msg;
OutputFile->flush();
}
void clang::AttachHeaderIncludeGen(Preprocessor &PP,
const DependencyOutputOptions &DepOpts,
bool ShowAllHeaders, StringRef OutputPath,
bool ShowDepth, bool MSStyle) {
raw_ostream *OutputFile = &llvm::errs();
bool OwnsOutputFile = false;
// Choose output stream, when printing in cl.exe /showIncludes style.
if (MSStyle) {
switch (DepOpts.ShowIncludesDest) {
default:
llvm_unreachable("Invalid destination for /showIncludes output!");
case ShowIncludesDestination::Stderr:
OutputFile = &llvm::errs();
break;
case ShowIncludesDestination::Stdout:
OutputFile = &llvm::outs();
break;
}
}
// Open the output file, if used.
if (!OutputPath.empty()) {
std::error_code EC;
llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
OutputPath.str(), EC,
llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
if (EC) {
PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
<< EC.message();
delete OS;
} else {
OS->SetUnbuffered();
OutputFile = OS;
OwnsOutputFile = true;
}
}
switch (DepOpts.HeaderIncludeFormat) {
case HIFMT_None:
llvm_unreachable("unexpected header format kind");
case HIFMT_Textual: {
assert(DepOpts.HeaderIncludeFiltering == HIFIL_None &&
"header filtering is currently always disabled when output format is"
"textual");
// Print header info for extra headers, pretending they were discovered by
// the regular preprocessor. The primary use case is to support proper
// generation of Make / Ninja file dependencies for implicit includes, such
// as sanitizer ignorelists. It's only important for cl.exe compatibility,
// the GNU way to generate rules is -M / -MM / -MD / -MMD.
for (const auto &Header : DepOpts.ExtraDeps)
PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);
PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(
&PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
MSStyle));
break;
}
case HIFMT_JSON:
switch (DepOpts.HeaderIncludeFiltering) {
default:
llvm_unreachable("Unknown HeaderIncludeFilteringKind enum");
case HIFIL_Only_Direct_System:
PP.addPPCallbacks(std::make_unique<HeaderIncludesJSONCallback>(
&PP, OutputFile, OwnsOutputFile));
break;
case HIFIL_Direct_Per_File:
PP.addPPCallbacks(std::make_unique<HeaderIncludesDirectPerFileCallback>(
&PP, OutputFile, OwnsOutputFile));
break;
}
break;
}
}
void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
FileChangeReason Reason,
SrcMgr::CharacteristicKind NewFileType,
FileID PrevFID) {
// Unless we are exiting a #include, make sure to skip ahead to the line the
// #include directive was at.
PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
if (UserLoc.isInvalid())
return;
// Adjust the current include depth.
if (Reason == PPCallbacks::EnterFile) {
++CurrentIncludeDepth;
} else if (Reason == PPCallbacks::ExitFile) {
if (CurrentIncludeDepth)
--CurrentIncludeDepth;
// We track when we are done with the predefines by watching for the first
// place where we drop back to a nesting depth of 1.
if (CurrentIncludeDepth == 1 && !HasProcessedPredefines)
HasProcessedPredefines = true;
return;
} else {
return;
}
if (!ShouldShowHeader(NewFileType))
return;
unsigned IncludeDepth = CurrentIncludeDepth;
if (!HasProcessedPredefines)
--IncludeDepth; // Ignore indent from <built-in>.
// FIXME: Identify headers in a more robust way than comparing their name to
// "<command line>" and "<built-in>" in a bunch of places.
if (Reason == PPCallbacks::EnterFile &&
UserLoc.getFilename() != StringRef("<command line>")) {
PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,
MSStyle);
}
}
void HeaderIncludesCallback::FileSkipped(const FileEntryRef &SkippedFile, const
Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) {
if (!DepOpts.ShowSkippedHeaderIncludes)
return;
if (!ShouldShowHeader(FileType))
return;
PrintHeaderInfo(OutputFile, SkippedFile.getName(), ShowDepth,
CurrentIncludeDepth + 1, MSStyle);
}
void HeaderIncludesJSONCallback::EndOfMainFile() {
OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getMainFileID());
SmallString<256> MainFile;
if (FE) {
MainFile += FE->getName();
SM.getFileManager().makeAbsolutePath(MainFile);
}
std::string Str;
llvm::raw_string_ostream OS(Str);
llvm::json::OStream JOS(OS);
JOS.object([&] {
JOS.attribute("source", MainFile.c_str());
JOS.attributeArray("includes", [&] {
llvm::StringSet<> SeenHeaders;
for (const std::string &H : IncludedHeaders)
if (SeenHeaders.insert(H).second)
JOS.value(H);
});
});
OS << "\n";
if (OutputFile->get_kind() == raw_ostream::OStreamKind::OK_FDStream) {
llvm::raw_fd_ostream *FDS = static_cast<llvm::raw_fd_ostream *>(OutputFile);
if (auto L = FDS->lock())
*OutputFile << Str;
} else
*OutputFile << Str;
}
/// Determine whether the header file should be recorded. The header file should
/// be recorded only if the header file is a system header and the current file
/// isn't a system header.
static bool shouldRecordNewFile(SrcMgr::CharacteristicKind NewFileType,
SourceLocation PrevLoc, SourceManager &SM) {
return SrcMgr::isSystem(NewFileType) && !SM.isInSystemHeader(PrevLoc);
}
void HeaderIncludesJSONCallback::FileChanged(
SourceLocation Loc, FileChangeReason Reason,
SrcMgr::CharacteristicKind NewFileType, FileID PrevFID) {
if (PrevFID.isInvalid() ||
!shouldRecordNewFile(NewFileType, SM.getLocForStartOfFile(PrevFID), SM))
return;
// Unless we are exiting a #include, make sure to skip ahead to the line the
// #include directive was at.
PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
if (UserLoc.isInvalid())
return;
if (Reason == PPCallbacks::EnterFile &&
UserLoc.getFilename() != StringRef("<command line>"))
IncludedHeaders.push_back(UserLoc.getFilename());
}
void HeaderIncludesJSONCallback::FileSkipped(
const FileEntryRef &SkippedFile, const Token &FilenameTok,
SrcMgr::CharacteristicKind FileType) {
if (!shouldRecordNewFile(FileType, FilenameTok.getLocation(), SM))
return;
IncludedHeaders.push_back(SkippedFile.getName().str());
}
void HeaderIncludesDirectPerFileCallback::EndOfMainFile() {
if (Dependencies.empty())
return;
// Sort the files so that the output does not depend on the DenseMap order.
SmallVector<FileEntryRef> SourceFiles;
for (auto F = Dependencies.begin(), FEnd = Dependencies.end(); F != FEnd;
++F) {
SourceFiles.push_back(F->first);
}
llvm::sort(SourceFiles, [](const FileEntryRef &LHS, const FileEntryRef &RHS) {
return LHS.getUID() < RHS.getUID();
});
std::string Str;
llvm::raw_string_ostream OS(Str);
llvm::json::OStream JOS(OS);
JOS.array([&] {
for (auto S = SourceFiles.begin(), SE = SourceFiles.end(); S != SE; ++S) {
JOS.object([&] {
SmallVector<FileEntryRef> &Deps = Dependencies[*S];
JOS.attribute("source", S->getName().str());
JOS.attributeArray("includes", [&] {
for (unsigned I = 0, N = Deps.size(); I != N; ++I)
JOS.value(Deps[I].getName().str());
});
});
}
});
OS << "\n";
if (OutputFile->get_kind() == raw_ostream::OStreamKind::OK_FDStream) {
llvm::raw_fd_ostream *FDS = static_cast<llvm::raw_fd_ostream *>(OutputFile);
if (auto L = FDS->lock())
*OutputFile << Str;
} else
*OutputFile << Str;
}
void HeaderIncludesDirectPerFileCallback::InclusionDirective(
SourceLocation HashLoc, const Token &IncludeTok, StringRef FileName,
bool IsAngled, CharSourceRange FilenameRange, OptionalFileEntryRef File,
StringRef SearchPath, StringRef RelativePath, const Module *SuggestedModule,
bool ModuleImported, SrcMgr::CharacteristicKind FileType) {
if (!File)
return;
SourceLocation Loc = SM.getExpansionLoc(HashLoc);
if (SM.isInSystemHeader(Loc))
return;
OptionalFileEntryRef FromFile = SM.getFileEntryRefForID(SM.getFileID(Loc));
if (!FromFile)
return;
Dependencies[*FromFile].push_back(*File);
}
void HeaderIncludesDirectPerFileCallback::moduleImport(SourceLocation ImportLoc,
ModuleIdPath Path,
const Module *Imported) {
if (!Imported)
return;
SourceLocation Loc = SM.getExpansionLoc(ImportLoc);
if (SM.isInSystemHeader(Loc))
return;
OptionalFileEntryRef FromFile = SM.getFileEntryRefForID(SM.getFileID(Loc));
if (!FromFile)
return;
OptionalFileEntryRef ModuleMapFile =
HSI.getModuleMap().getModuleMapFileForUniquing(Imported);
if (!ModuleMapFile)
return;
Dependencies[*FromFile].push_back(*ModuleMapFile);
}
|