DependencyFile.cpp revision 249423
1//===--- DependencyFile.cpp - Generate dependency file --------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This code generates dependency files.
11//
12//===----------------------------------------------------------------------===//
13
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/PPCallbacks.h"
22#include "clang/Lex/Preprocessor.h"
23#include "llvm/ADT/StringSet.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/raw_ostream.h"
26
27using namespace clang;
28
29namespace {
30class DependencyFileCallback : public PPCallbacks {
31  std::vector<std::string> Files;
32  llvm::StringSet<> FilesSet;
33  const Preprocessor *PP;
34  std::string OutputFile;
35  std::vector<std::string> Targets;
36  bool IncludeSystemHeaders;
37  bool PhonyTarget;
38  bool AddMissingHeaderDeps;
39  bool SeenMissingHeader;
40private:
41  bool FileMatchesDepCriteria(const char *Filename,
42                              SrcMgr::CharacteristicKind FileType);
43  void AddFilename(StringRef Filename);
44  void OutputDependencyFile();
45
46public:
47  DependencyFileCallback(const Preprocessor *_PP,
48                         const DependencyOutputOptions &Opts)
49    : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
50      IncludeSystemHeaders(Opts.IncludeSystemHeaders),
51      PhonyTarget(Opts.UsePhonyTargets),
52      AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
53      SeenMissingHeader(false) {}
54
55  virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
56                           SrcMgr::CharacteristicKind FileType,
57                           FileID PrevFID);
58  virtual void InclusionDirective(SourceLocation HashLoc,
59                                  const Token &IncludeTok,
60                                  StringRef FileName,
61                                  bool IsAngled,
62                                  CharSourceRange FilenameRange,
63                                  const FileEntry *File,
64                                  StringRef SearchPath,
65                                  StringRef RelativePath,
66                                  const Module *Imported);
67
68  virtual void EndOfMainFile() {
69    OutputDependencyFile();
70  }
71};
72}
73
74void clang::AttachDependencyFileGen(Preprocessor &PP,
75                                    const DependencyOutputOptions &Opts) {
76  if (Opts.Targets.empty()) {
77    PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
78    return;
79  }
80
81  // Disable the "file not found" diagnostic if the -MG option was given.
82  if (Opts.AddMissingHeaderDeps)
83    PP.SetSuppressIncludeNotFoundError(true);
84
85  PP.addPPCallbacks(new DependencyFileCallback(&PP, Opts));
86}
87
88/// FileMatchesDepCriteria - Determine whether the given Filename should be
89/// considered as a dependency.
90bool DependencyFileCallback::FileMatchesDepCriteria(const char *Filename,
91                                          SrcMgr::CharacteristicKind FileType) {
92  if (strcmp("<built-in>", Filename) == 0)
93    return false;
94
95  if (IncludeSystemHeaders)
96    return true;
97
98  return FileType == SrcMgr::C_User;
99}
100
101void DependencyFileCallback::FileChanged(SourceLocation Loc,
102                                         FileChangeReason Reason,
103                                         SrcMgr::CharacteristicKind FileType,
104                                         FileID PrevFID) {
105  if (Reason != PPCallbacks::EnterFile)
106    return;
107
108  // Dependency generation really does want to go all the way to the
109  // file entry for a source location to find out what is depended on.
110  // We do not want #line markers to affect dependency generation!
111  SourceManager &SM = PP->getSourceManager();
112
113  const FileEntry *FE =
114    SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
115  if (FE == 0) return;
116
117  StringRef Filename = FE->getName();
118  if (!FileMatchesDepCriteria(Filename.data(), FileType))
119    return;
120
121  // Remove leading "./" (or ".//" or "././" etc.)
122  while (Filename.size() > 2 && Filename[0] == '.' &&
123         llvm::sys::path::is_separator(Filename[1])) {
124    Filename = Filename.substr(1);
125    while (llvm::sys::path::is_separator(Filename[0]))
126      Filename = Filename.substr(1);
127  }
128
129  AddFilename(Filename);
130}
131
132void DependencyFileCallback::InclusionDirective(SourceLocation HashLoc,
133                                                const Token &IncludeTok,
134                                                StringRef FileName,
135                                                bool IsAngled,
136                                                CharSourceRange FilenameRange,
137                                                const FileEntry *File,
138                                                StringRef SearchPath,
139                                                StringRef RelativePath,
140                                                const Module *Imported) {
141  if (!File) {
142    if (AddMissingHeaderDeps)
143      AddFilename(FileName);
144    else
145      SeenMissingHeader = true;
146  }
147}
148
149void DependencyFileCallback::AddFilename(StringRef Filename) {
150  if (FilesSet.insert(Filename))
151    Files.push_back(Filename);
152}
153
154/// PrintFilename - GCC escapes spaces, # and $, but apparently not ' or " or
155/// other scary characters.
156static void PrintFilename(raw_ostream &OS, StringRef Filename) {
157  for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
158    if (Filename[i] == ' ' || Filename[i] == '#')
159      OS << '\\';
160    else if (Filename[i] == '$') // $ is escaped by $$.
161      OS << '$';
162    OS << Filename[i];
163  }
164}
165
166void DependencyFileCallback::OutputDependencyFile() {
167  if (SeenMissingHeader) {
168    llvm::sys::Path(OutputFile).eraseFromDisk();
169    return;
170  }
171
172  std::string Err;
173  llvm::raw_fd_ostream OS(OutputFile.c_str(), Err);
174  if (!Err.empty()) {
175    PP->getDiagnostics().Report(diag::err_fe_error_opening)
176      << OutputFile << Err;
177    return;
178  }
179
180  // Write out the dependency targets, trying to avoid overly long
181  // lines when possible. We try our best to emit exactly the same
182  // dependency file as GCC (4.2), assuming the included files are the
183  // same.
184  const unsigned MaxColumns = 75;
185  unsigned Columns = 0;
186
187  for (std::vector<std::string>::iterator
188         I = Targets.begin(), E = Targets.end(); I != E; ++I) {
189    unsigned N = I->length();
190    if (Columns == 0) {
191      Columns += N;
192    } else if (Columns + N + 2 > MaxColumns) {
193      Columns = N + 2;
194      OS << " \\\n  ";
195    } else {
196      Columns += N + 1;
197      OS << ' ';
198    }
199    // Targets already quoted as needed.
200    OS << *I;
201  }
202
203  OS << ':';
204  Columns += 1;
205
206  // Now add each dependency in the order it was seen, but avoiding
207  // duplicates.
208  for (std::vector<std::string>::iterator I = Files.begin(),
209         E = Files.end(); I != E; ++I) {
210    // Start a new line if this would exceed the column limit. Make
211    // sure to leave space for a trailing " \" in case we need to
212    // break the line on the next iteration.
213    unsigned N = I->length();
214    if (Columns + (N + 1) + 2 > MaxColumns) {
215      OS << " \\\n ";
216      Columns = 2;
217    }
218    OS << ' ';
219    PrintFilename(OS, *I);
220    Columns += N + 1;
221  }
222  OS << '\n';
223
224  // Create phony targets if requested.
225  if (PhonyTarget && !Files.empty()) {
226    // Skip the first entry, this is always the input file itself.
227    for (std::vector<std::string>::iterator I = Files.begin() + 1,
228           E = Files.end(); I != E; ++I) {
229      OS << '\n';
230      PrintFilename(OS, *I);
231      OS << ":\n";
232    }
233  }
234}
235
236