DependencyFile.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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. #include "clang/Frontend/Utils.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Frontend/DependencyOutputOptions.h"
  17. #include "clang/Frontend/FrontendDiagnostic.h"
  18. #include "clang/Lex/DirectoryLookup.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/ModuleMap.h"
  21. #include "clang/Lex/PPCallbacks.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Serialization/ASTReader.h"
  24. #include "llvm/ADT/StringSet.h"
  25. #include "llvm/ADT/StringSwitch.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace clang;
  30. namespace {
  31. struct DepCollectorPPCallbacks : public PPCallbacks {
  32. DependencyCollector &DepCollector;
  33. SourceManager &SM;
  34. DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM)
  35. : DepCollector(L), SM(SM) { }
  36. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  37. SrcMgr::CharacteristicKind FileType,
  38. FileID PrevFID) override {
  39. if (Reason != PPCallbacks::EnterFile)
  40. return;
  41. // Dependency generation really does want to go all the way to the
  42. // file entry for a source location to find out what is depended on.
  43. // We do not want #line markers to affect dependency generation!
  44. const FileEntry *FE =
  45. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  46. if (!FE)
  47. return;
  48. StringRef Filename =
  49. llvm::sys::path::remove_leading_dotslash(FE->getName());
  50. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  51. FileType != SrcMgr::C_User,
  52. /*IsModuleFile*/false, /*IsMissing*/false);
  53. }
  54. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  55. StringRef FileName, bool IsAngled,
  56. CharSourceRange FilenameRange, const FileEntry *File,
  57. StringRef SearchPath, StringRef RelativePath,
  58. const Module *Imported) override {
  59. if (!File)
  60. DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
  61. /*IsSystem*/false, /*IsModuleFile*/false,
  62. /*IsMissing*/true);
  63. // Files that actually exist are handled by FileChanged.
  64. }
  65. void EndOfMainFile() override {
  66. DepCollector.finishedMainFile();
  67. }
  68. };
  69. struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
  70. DependencyCollector &DepCollector;
  71. DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
  72. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  73. bool IsSystem) override {
  74. StringRef Filename = Entry.getName();
  75. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  76. /*IsSystem*/IsSystem,
  77. /*IsModuleFile*/false,
  78. /*IsMissing*/false);
  79. }
  80. };
  81. struct DepCollectorASTListener : public ASTReaderListener {
  82. DependencyCollector &DepCollector;
  83. DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
  84. bool needsInputFileVisitation() override { return true; }
  85. bool needsSystemInputFileVisitation() override {
  86. return DepCollector.needSystemDependencies();
  87. }
  88. void visitModuleFile(StringRef Filename,
  89. serialization::ModuleKind Kind) override {
  90. DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
  91. /*IsSystem*/false, /*IsModuleFile*/true,
  92. /*IsMissing*/false);
  93. }
  94. bool visitInputFile(StringRef Filename, bool IsSystem,
  95. bool IsOverridden, bool IsExplicitModule) override {
  96. if (IsOverridden || IsExplicitModule)
  97. return true;
  98. DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
  99. /*IsModuleFile*/false, /*IsMissing*/false);
  100. return true;
  101. }
  102. };
  103. } // end anonymous namespace
  104. void DependencyCollector::maybeAddDependency(StringRef Filename, bool FromModule,
  105. bool IsSystem, bool IsModuleFile,
  106. bool IsMissing) {
  107. if (Seen.insert(Filename).second &&
  108. sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
  109. Dependencies.push_back(Filename);
  110. }
  111. static bool isSpecialFilename(StringRef Filename) {
  112. return llvm::StringSwitch<bool>(Filename)
  113. .Case("<built-in>", true)
  114. .Case("<stdin>", true)
  115. .Default(false);
  116. }
  117. bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
  118. bool IsSystem, bool IsModuleFile,
  119. bool IsMissing) {
  120. return !isSpecialFilename(Filename) &&
  121. (needSystemDependencies() || !IsSystem);
  122. }
  123. DependencyCollector::~DependencyCollector() { }
  124. void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  125. PP.addPPCallbacks(
  126. llvm::make_unique<DepCollectorPPCallbacks>(*this, PP.getSourceManager()));
  127. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  128. llvm::make_unique<DepCollectorMMCallbacks>(*this));
  129. }
  130. void DependencyCollector::attachToASTReader(ASTReader &R) {
  131. R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
  132. }
  133. namespace {
  134. /// Private implementation for DependencyFileGenerator
  135. class DFGImpl : public PPCallbacks {
  136. std::vector<std::string> Files;
  137. llvm::StringSet<> FilesSet;
  138. const Preprocessor *PP;
  139. std::string OutputFile;
  140. std::vector<std::string> Targets;
  141. bool IncludeSystemHeaders;
  142. bool PhonyTarget;
  143. bool AddMissingHeaderDeps;
  144. bool SeenMissingHeader;
  145. bool IncludeModuleFiles;
  146. DependencyOutputFormat OutputFormat;
  147. private:
  148. bool FileMatchesDepCriteria(const char *Filename,
  149. SrcMgr::CharacteristicKind FileType);
  150. void OutputDependencyFile();
  151. public:
  152. DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
  153. : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
  154. IncludeSystemHeaders(Opts.IncludeSystemHeaders),
  155. PhonyTarget(Opts.UsePhonyTargets),
  156. AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
  157. SeenMissingHeader(false),
  158. IncludeModuleFiles(Opts.IncludeModuleFiles),
  159. OutputFormat(Opts.OutputFormat) {
  160. for (auto ExtraDep : Opts.ExtraDeps) {
  161. AddFilename(ExtraDep);
  162. }
  163. }
  164. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  165. SrcMgr::CharacteristicKind FileType,
  166. FileID PrevFID) override;
  167. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  168. StringRef FileName, bool IsAngled,
  169. CharSourceRange FilenameRange, const FileEntry *File,
  170. StringRef SearchPath, StringRef RelativePath,
  171. const Module *Imported) override;
  172. void EndOfMainFile() override {
  173. OutputDependencyFile();
  174. }
  175. void AddFilename(StringRef Filename);
  176. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  177. bool includeModuleFiles() const { return IncludeModuleFiles; }
  178. };
  179. class DFGMMCallback : public ModuleMapCallbacks {
  180. DFGImpl &Parent;
  181. public:
  182. DFGMMCallback(DFGImpl &Parent) : Parent(Parent) {}
  183. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  184. bool IsSystem) override {
  185. if (!IsSystem || Parent.includeSystemHeaders())
  186. Parent.AddFilename(Entry.getName());
  187. }
  188. };
  189. class DFGASTReaderListener : public ASTReaderListener {
  190. DFGImpl &Parent;
  191. public:
  192. DFGASTReaderListener(DFGImpl &Parent)
  193. : Parent(Parent) { }
  194. bool needsInputFileVisitation() override { return true; }
  195. bool needsSystemInputFileVisitation() override {
  196. return Parent.includeSystemHeaders();
  197. }
  198. void visitModuleFile(StringRef Filename,
  199. serialization::ModuleKind Kind) override;
  200. bool visitInputFile(StringRef Filename, bool isSystem,
  201. bool isOverridden, bool isExplicitModule) override;
  202. };
  203. }
  204. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  205. : Impl(Impl) { }
  206. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  207. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  208. if (Opts.Targets.empty()) {
  209. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  210. return nullptr;
  211. }
  212. // Disable the "file not found" diagnostic if the -MG option was given.
  213. if (Opts.AddMissingHeaderDeps)
  214. PP.SetSuppressIncludeNotFoundError(true);
  215. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  216. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callback));
  217. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  218. llvm::make_unique<DFGMMCallback>(*Callback));
  219. return new DependencyFileGenerator(Callback);
  220. }
  221. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  222. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  223. assert(I && "missing implementation");
  224. R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
  225. }
  226. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  227. /// considered as a dependency.
  228. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  229. SrcMgr::CharacteristicKind FileType) {
  230. if (isSpecialFilename(Filename))
  231. return false;
  232. if (IncludeSystemHeaders)
  233. return true;
  234. return FileType == SrcMgr::C_User;
  235. }
  236. void DFGImpl::FileChanged(SourceLocation Loc,
  237. FileChangeReason Reason,
  238. SrcMgr::CharacteristicKind FileType,
  239. FileID PrevFID) {
  240. if (Reason != PPCallbacks::EnterFile)
  241. return;
  242. // Dependency generation really does want to go all the way to the
  243. // file entry for a source location to find out what is depended on.
  244. // We do not want #line markers to affect dependency generation!
  245. SourceManager &SM = PP->getSourceManager();
  246. const FileEntry *FE =
  247. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  248. if (!FE) return;
  249. StringRef Filename = FE->getName();
  250. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  251. return;
  252. AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
  253. }
  254. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  255. const Token &IncludeTok,
  256. StringRef FileName,
  257. bool IsAngled,
  258. CharSourceRange FilenameRange,
  259. const FileEntry *File,
  260. StringRef SearchPath,
  261. StringRef RelativePath,
  262. const Module *Imported) {
  263. if (!File) {
  264. if (AddMissingHeaderDeps)
  265. AddFilename(FileName);
  266. else
  267. SeenMissingHeader = true;
  268. }
  269. }
  270. void DFGImpl::AddFilename(StringRef Filename) {
  271. if (FilesSet.insert(Filename).second)
  272. Files.push_back(Filename);
  273. }
  274. /// Print the filename, with escaping or quoting that accommodates the three
  275. /// most likely tools that use dependency files: GNU Make, BSD Make, and
  276. /// NMake/Jom.
  277. ///
  278. /// BSD Make is the simplest case: It does no escaping at all. This means
  279. /// characters that are normally delimiters, i.e. space and # (the comment
  280. /// character) simply aren't supported in filenames.
  281. ///
  282. /// GNU Make does allow space and # in filenames, but to avoid being treated
  283. /// as a delimiter or comment, these must be escaped with a backslash. Because
  284. /// backslash is itself the escape character, if a backslash appears in a
  285. /// filename, it should be escaped as well. (As a special case, $ is escaped
  286. /// as $$, which is the normal Make way to handle the $ character.)
  287. /// For compatibility with BSD Make and historical practice, if GNU Make
  288. /// un-escapes characters in a filename but doesn't find a match, it will
  289. /// retry with the unmodified original string.
  290. ///
  291. /// GCC tries to accommodate both Make formats by escaping any space or #
  292. /// characters in the original filename, but not escaping backslashes. The
  293. /// apparent intent is so that filenames with backslashes will be handled
  294. /// correctly by BSD Make, and by GNU Make in its fallback mode of using the
  295. /// unmodified original string; filenames with # or space characters aren't
  296. /// supported by BSD Make at all, but will be handled correctly by GNU Make
  297. /// due to the escaping.
  298. ///
  299. /// A corner case that GCC gets only partly right is when the original filename
  300. /// has a backslash immediately followed by space or #. GNU Make would expect
  301. /// this backslash to be escaped; however GCC escapes the original backslash
  302. /// only when followed by space, not #. It will therefore take a dependency
  303. /// from a directive such as
  304. /// #include "a\ b\#c.h"
  305. /// and emit it as
  306. /// a\\\ b\\#c.h
  307. /// which GNU Make will interpret as
  308. /// a\ b\
  309. /// followed by a comment. Failing to find this file, it will fall back to the
  310. /// original string, which probably doesn't exist either; in any case it won't
  311. /// find
  312. /// a\ b\#c.h
  313. /// which is the actual filename specified by the include directive.
  314. ///
  315. /// Clang does what GCC does, rather than what GNU Make expects.
  316. ///
  317. /// NMake/Jom has a different set of scary characters, but wraps filespecs in
  318. /// double-quotes to avoid misinterpreting them; see
  319. /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
  320. /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
  321. /// for Windows file-naming info.
  322. static void PrintFilename(raw_ostream &OS, StringRef Filename,
  323. DependencyOutputFormat OutputFormat) {
  324. if (OutputFormat == DependencyOutputFormat::NMake) {
  325. // Add quotes if needed. These are the characters listed as "special" to
  326. // NMake, that are legal in a Windows filespec, and that could cause
  327. // misinterpretation of the dependency string.
  328. if (Filename.find_first_of(" #${}^!") != StringRef::npos)
  329. OS << '\"' << Filename << '\"';
  330. else
  331. OS << Filename;
  332. return;
  333. }
  334. assert(OutputFormat == DependencyOutputFormat::Make);
  335. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  336. if (Filename[i] == '#') // Handle '#' the broken gcc way.
  337. OS << '\\';
  338. else if (Filename[i] == ' ') { // Handle space correctly.
  339. OS << '\\';
  340. unsigned j = i;
  341. while (j > 0 && Filename[--j] == '\\')
  342. OS << '\\';
  343. } else if (Filename[i] == '$') // $ is escaped by $$.
  344. OS << '$';
  345. OS << Filename[i];
  346. }
  347. }
  348. void DFGImpl::OutputDependencyFile() {
  349. if (SeenMissingHeader) {
  350. llvm::sys::fs::remove(OutputFile);
  351. return;
  352. }
  353. std::error_code EC;
  354. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  355. if (EC) {
  356. PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
  357. << EC.message();
  358. return;
  359. }
  360. // Write out the dependency targets, trying to avoid overly long
  361. // lines when possible. We try our best to emit exactly the same
  362. // dependency file as GCC (4.2), assuming the included files are the
  363. // same.
  364. const unsigned MaxColumns = 75;
  365. unsigned Columns = 0;
  366. for (std::vector<std::string>::iterator
  367. I = Targets.begin(), E = Targets.end(); I != E; ++I) {
  368. unsigned N = I->length();
  369. if (Columns == 0) {
  370. Columns += N;
  371. } else if (Columns + N + 2 > MaxColumns) {
  372. Columns = N + 2;
  373. OS << " \\\n ";
  374. } else {
  375. Columns += N + 1;
  376. OS << ' ';
  377. }
  378. // Targets already quoted as needed.
  379. OS << *I;
  380. }
  381. OS << ':';
  382. Columns += 1;
  383. // Now add each dependency in the order it was seen, but avoiding
  384. // duplicates.
  385. for (std::vector<std::string>::iterator I = Files.begin(),
  386. E = Files.end(); I != E; ++I) {
  387. // Start a new line if this would exceed the column limit. Make
  388. // sure to leave space for a trailing " \" in case we need to
  389. // break the line on the next iteration.
  390. unsigned N = I->length();
  391. if (Columns + (N + 1) + 2 > MaxColumns) {
  392. OS << " \\\n ";
  393. Columns = 2;
  394. }
  395. OS << ' ';
  396. PrintFilename(OS, *I, OutputFormat);
  397. Columns += N + 1;
  398. }
  399. OS << '\n';
  400. // Create phony targets if requested.
  401. if (PhonyTarget && !Files.empty()) {
  402. // Skip the first entry, this is always the input file itself.
  403. for (std::vector<std::string>::iterator I = Files.begin() + 1,
  404. E = Files.end(); I != E; ++I) {
  405. OS << '\n';
  406. PrintFilename(OS, *I, OutputFormat);
  407. OS << ":\n";
  408. }
  409. }
  410. }
  411. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  412. bool IsSystem, bool IsOverridden,
  413. bool IsExplicitModule) {
  414. assert(!IsSystem || needsSystemInputFileVisitation());
  415. if (IsOverridden || IsExplicitModule)
  416. return true;
  417. Parent.AddFilename(Filename);
  418. return true;
  419. }
  420. void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename,
  421. serialization::ModuleKind Kind) {
  422. if (Parent.includeModuleFiles())
  423. Parent.AddFilename(Filename);
  424. }