1 //===--- DependencyFile.cpp - Generate dependency file --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This code generates dependency files.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/Utils.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Frontend/DependencyOutputOptions.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Lex/DirectoryLookup.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Lex/ModuleMap.h"
22 #include "clang/Lex/PPCallbacks.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Serialization/ASTReader.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/raw_ostream.h"
31 using namespace clang;
34 struct DepCollectorPPCallbacks : public PPCallbacks {
35 DependencyCollector &DepCollector;
37 DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM)
38 : DepCollector(L), SM(SM) { }
40 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
41 SrcMgr::CharacteristicKind FileType,
42 FileID PrevFID) override {
43 if (Reason != PPCallbacks::EnterFile)
46 // Dependency generation really does want to go all the way to the
47 // file entry for a source location to find out what is depended on.
48 // We do not want #line markers to affect dependency generation!
50 SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
55 llvm::sys::path::remove_leading_dotslash(FE->getName());
57 DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
59 /*IsModuleFile*/false, /*IsMissing*/false);
62 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
63 StringRef FileName, bool IsAngled,
64 CharSourceRange FilenameRange, const FileEntry *File,
65 StringRef SearchPath, StringRef RelativePath,
66 const Module *Imported,
67 SrcMgr::CharacteristicKind FileType) override {
69 DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
70 /*IsSystem*/false, /*IsModuleFile*/false,
72 // Files that actually exist are handled by FileChanged.
75 void EndOfMainFile() override {
76 DepCollector.finishedMainFile();
80 struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
81 DependencyCollector &DepCollector;
82 DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
84 void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
85 bool IsSystem) override {
86 StringRef Filename = Entry.getName();
87 DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
89 /*IsModuleFile*/false,
94 struct DepCollectorASTListener : public ASTReaderListener {
95 DependencyCollector &DepCollector;
96 DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
97 bool needsInputFileVisitation() override { return true; }
98 bool needsSystemInputFileVisitation() override {
99 return DepCollector.needSystemDependencies();
101 void visitModuleFile(StringRef Filename,
102 serialization::ModuleKind Kind) override {
103 DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
104 /*IsSystem*/false, /*IsModuleFile*/true,
107 bool visitInputFile(StringRef Filename, bool IsSystem,
108 bool IsOverridden, bool IsExplicitModule) override {
109 if (IsOverridden || IsExplicitModule)
112 DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
113 /*IsModuleFile*/false, /*IsMissing*/false);
117 } // end anonymous namespace
119 void DependencyCollector::maybeAddDependency(StringRef Filename, bool FromModule,
120 bool IsSystem, bool IsModuleFile,
122 if (Seen.insert(Filename).second &&
123 sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
124 Dependencies.push_back(Filename);
127 static bool isSpecialFilename(StringRef Filename) {
128 return llvm::StringSwitch<bool>(Filename)
129 .Case("<built-in>", true)
130 .Case("<stdin>", true)
134 bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
135 bool IsSystem, bool IsModuleFile,
137 return !isSpecialFilename(Filename) &&
138 (needSystemDependencies() || !IsSystem);
141 DependencyCollector::~DependencyCollector() { }
142 void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
144 llvm::make_unique<DepCollectorPPCallbacks>(*this, PP.getSourceManager()));
145 PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
146 llvm::make_unique<DepCollectorMMCallbacks>(*this));
148 void DependencyCollector::attachToASTReader(ASTReader &R) {
149 R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
153 /// Private implementation for DependencyFileGenerator
154 class DFGImpl : public PPCallbacks {
155 std::vector<std::string> Files;
156 llvm::StringSet<> FilesSet;
157 const Preprocessor *PP;
158 std::string OutputFile;
159 std::vector<std::string> Targets;
160 bool IncludeSystemHeaders;
162 bool AddMissingHeaderDeps;
163 bool SeenMissingHeader;
164 bool IncludeModuleFiles;
165 DependencyOutputFormat OutputFormat;
166 unsigned InputFileIndex;
169 bool FileMatchesDepCriteria(const char *Filename,
170 SrcMgr::CharacteristicKind FileType);
171 void OutputDependencyFile();
174 DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
175 : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
176 IncludeSystemHeaders(Opts.IncludeSystemHeaders),
177 PhonyTarget(Opts.UsePhonyTargets),
178 AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
179 SeenMissingHeader(false),
180 IncludeModuleFiles(Opts.IncludeModuleFiles),
181 OutputFormat(Opts.OutputFormat),
183 for (const auto &ExtraDep : Opts.ExtraDeps) {
184 if (AddFilename(ExtraDep))
189 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
190 SrcMgr::CharacteristicKind FileType,
191 FileID PrevFID) override;
193 void FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
194 SrcMgr::CharacteristicKind FileType) override;
196 void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
197 StringRef FileName, bool IsAngled,
198 CharSourceRange FilenameRange, const FileEntry *File,
199 StringRef SearchPath, StringRef RelativePath,
200 const Module *Imported,
201 SrcMgr::CharacteristicKind FileType) override;
203 void EndOfMainFile() override {
204 OutputDependencyFile();
207 bool AddFilename(StringRef Filename);
208 bool includeSystemHeaders() const { return IncludeSystemHeaders; }
209 bool includeModuleFiles() const { return IncludeModuleFiles; }
212 class DFGMMCallback : public ModuleMapCallbacks {
215 DFGMMCallback(DFGImpl &Parent) : Parent(Parent) {}
216 void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
217 bool IsSystem) override {
218 if (!IsSystem || Parent.includeSystemHeaders())
219 Parent.AddFilename(Entry.getName());
223 class DFGASTReaderListener : public ASTReaderListener {
226 DFGASTReaderListener(DFGImpl &Parent)
228 bool needsInputFileVisitation() override { return true; }
229 bool needsSystemInputFileVisitation() override {
230 return Parent.includeSystemHeaders();
232 void visitModuleFile(StringRef Filename,
233 serialization::ModuleKind Kind) override;
234 bool visitInputFile(StringRef Filename, bool isSystem,
235 bool isOverridden, bool isExplicitModule) override;
239 DependencyFileGenerator::DependencyFileGenerator(void *Impl)
242 DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
243 clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
245 if (Opts.Targets.empty()) {
246 PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
250 // Disable the "file not found" diagnostic if the -MG option was given.
251 if (Opts.AddMissingHeaderDeps)
252 PP.SetSuppressIncludeNotFoundError(true);
254 DFGImpl *Callback = new DFGImpl(&PP, Opts);
255 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callback));
256 PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
257 llvm::make_unique<DFGMMCallback>(*Callback));
258 return new DependencyFileGenerator(Callback);
261 void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
262 DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
263 assert(I && "missing implementation");
264 R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
267 /// FileMatchesDepCriteria - Determine whether the given Filename should be
268 /// considered as a dependency.
269 bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
270 SrcMgr::CharacteristicKind FileType) {
271 if (isSpecialFilename(Filename))
274 if (IncludeSystemHeaders)
277 return !isSystem(FileType);
280 void DFGImpl::FileChanged(SourceLocation Loc,
281 FileChangeReason Reason,
282 SrcMgr::CharacteristicKind FileType,
284 if (Reason != PPCallbacks::EnterFile)
287 // Dependency generation really does want to go all the way to the
288 // file entry for a source location to find out what is depended on.
289 // We do not want #line markers to affect dependency generation!
290 SourceManager &SM = PP->getSourceManager();
292 const FileEntry *FE =
293 SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
296 StringRef Filename = FE->getName();
297 if (!FileMatchesDepCriteria(Filename.data(), FileType))
300 AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
303 void DFGImpl::FileSkipped(const FileEntry &SkippedFile,
304 const Token &FilenameTok,
305 SrcMgr::CharacteristicKind FileType) {
306 StringRef Filename = SkippedFile.getName();
307 if (!FileMatchesDepCriteria(Filename.data(), FileType))
310 AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
313 void DFGImpl::InclusionDirective(SourceLocation HashLoc,
314 const Token &IncludeTok,
317 CharSourceRange FilenameRange,
318 const FileEntry *File,
319 StringRef SearchPath,
320 StringRef RelativePath,
321 const Module *Imported,
322 SrcMgr::CharacteristicKind FileType) {
324 if (AddMissingHeaderDeps)
325 AddFilename(FileName);
327 SeenMissingHeader = true;
331 bool DFGImpl::AddFilename(StringRef Filename) {
332 if (FilesSet.insert(Filename).second) {
333 Files.push_back(Filename);
339 /// Print the filename, with escaping or quoting that accommodates the three
340 /// most likely tools that use dependency files: GNU Make, BSD Make, and
343 /// BSD Make is the simplest case: It does no escaping at all. This means
344 /// characters that are normally delimiters, i.e. space and # (the comment
345 /// character) simply aren't supported in filenames.
347 /// GNU Make does allow space and # in filenames, but to avoid being treated
348 /// as a delimiter or comment, these must be escaped with a backslash. Because
349 /// backslash is itself the escape character, if a backslash appears in a
350 /// filename, it should be escaped as well. (As a special case, $ is escaped
351 /// as $$, which is the normal Make way to handle the $ character.)
352 /// For compatibility with BSD Make and historical practice, if GNU Make
353 /// un-escapes characters in a filename but doesn't find a match, it will
354 /// retry with the unmodified original string.
356 /// GCC tries to accommodate both Make formats by escaping any space or #
357 /// characters in the original filename, but not escaping backslashes. The
358 /// apparent intent is so that filenames with backslashes will be handled
359 /// correctly by BSD Make, and by GNU Make in its fallback mode of using the
360 /// unmodified original string; filenames with # or space characters aren't
361 /// supported by BSD Make at all, but will be handled correctly by GNU Make
362 /// due to the escaping.
364 /// A corner case that GCC gets only partly right is when the original filename
365 /// has a backslash immediately followed by space or #. GNU Make would expect
366 /// this backslash to be escaped; however GCC escapes the original backslash
367 /// only when followed by space, not #. It will therefore take a dependency
368 /// from a directive such as
369 /// #include "a\ b\#c.h"
372 /// which GNU Make will interpret as
374 /// followed by a comment. Failing to find this file, it will fall back to the
375 /// original string, which probably doesn't exist either; in any case it won't
378 /// which is the actual filename specified by the include directive.
380 /// Clang does what GCC does, rather than what GNU Make expects.
382 /// NMake/Jom has a different set of scary characters, but wraps filespecs in
383 /// double-quotes to avoid misinterpreting them; see
384 /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
385 /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
386 /// for Windows file-naming info.
387 static void PrintFilename(raw_ostream &OS, StringRef Filename,
388 DependencyOutputFormat OutputFormat) {
389 if (OutputFormat == DependencyOutputFormat::NMake) {
390 // Add quotes if needed. These are the characters listed as "special" to
391 // NMake, that are legal in a Windows filespec, and that could cause
392 // misinterpretation of the dependency string.
393 if (Filename.find_first_of(" #${}^!") != StringRef::npos)
394 OS << '\"' << Filename << '\"';
399 assert(OutputFormat == DependencyOutputFormat::Make);
400 for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
401 if (Filename[i] == '#') // Handle '#' the broken gcc way.
403 else if (Filename[i] == ' ') { // Handle space correctly.
406 while (j > 0 && Filename[--j] == '\\')
408 } else if (Filename[i] == '$') // $ is escaped by $$.
414 void DFGImpl::OutputDependencyFile() {
415 if (SeenMissingHeader) {
416 llvm::sys::fs::remove(OutputFile);
421 llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
423 PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
428 // Write out the dependency targets, trying to avoid overly long
429 // lines when possible. We try our best to emit exactly the same
430 // dependency file as GCC (4.2), assuming the included files are the
432 const unsigned MaxColumns = 75;
433 unsigned Columns = 0;
435 for (StringRef Target : Targets) {
436 unsigned N = Target.size();
439 } else if (Columns + N + 2 > MaxColumns) {
446 // Targets already quoted as needed.
453 // Now add each dependency in the order it was seen, but avoiding
455 for (StringRef File : Files) {
456 // Start a new line if this would exceed the column limit. Make
457 // sure to leave space for a trailing " \" in case we need to
458 // break the line on the next iteration.
459 unsigned N = File.size();
460 if (Columns + (N + 1) + 2 > MaxColumns) {
465 PrintFilename(OS, File, OutputFormat);
470 // Create phony targets if requested.
471 if (PhonyTarget && !Files.empty()) {
473 for (auto I = Files.begin(), E = Files.end(); I != E; ++I) {
474 if (Index++ == InputFileIndex)
477 PrintFilename(OS, *I, OutputFormat);
483 bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
484 bool IsSystem, bool IsOverridden,
485 bool IsExplicitModule) {
486 assert(!IsSystem || needsSystemInputFileVisitation());
487 if (IsOverridden || IsExplicitModule)
490 Parent.AddFilename(Filename);
494 void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename,
495 serialization::ModuleKind Kind) {
496 if (Parent.includeModuleFiles())
497 Parent.AddFilename(Filename);