DependencyFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. isSystem(FileType),
  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 (const 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 FileSkipped(const FileEntry &SkippedFile, const Token &FilenameTok,
  168. SrcMgr::CharacteristicKind FileType) override;
  169. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  170. StringRef FileName, bool IsAngled,
  171. CharSourceRange FilenameRange, const FileEntry *File,
  172. StringRef SearchPath, StringRef RelativePath,
  173. const Module *Imported) override;
  174. void EndOfMainFile() override {
  175. OutputDependencyFile();
  176. }
  177. void AddFilename(StringRef Filename);
  178. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  179. bool includeModuleFiles() const { return IncludeModuleFiles; }
  180. };
  181. class DFGMMCallback : public ModuleMapCallbacks {
  182. DFGImpl &Parent;
  183. public:
  184. DFGMMCallback(DFGImpl &Parent) : Parent(Parent) {}
  185. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  186. bool IsSystem) override {
  187. if (!IsSystem || Parent.includeSystemHeaders())
  188. Parent.AddFilename(Entry.getName());
  189. }
  190. };
  191. class DFGASTReaderListener : public ASTReaderListener {
  192. DFGImpl &Parent;
  193. public:
  194. DFGASTReaderListener(DFGImpl &Parent)
  195. : Parent(Parent) { }
  196. bool needsInputFileVisitation() override { return true; }
  197. bool needsSystemInputFileVisitation() override {
  198. return Parent.includeSystemHeaders();
  199. }
  200. void visitModuleFile(StringRef Filename,
  201. serialization::ModuleKind Kind) override;
  202. bool visitInputFile(StringRef Filename, bool isSystem,
  203. bool isOverridden, bool isExplicitModule) override;
  204. };
  205. }
  206. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  207. : Impl(Impl) { }
  208. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  209. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  210. if (Opts.Targets.empty()) {
  211. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  212. return nullptr;
  213. }
  214. // Disable the "file not found" diagnostic if the -MG option was given.
  215. if (Opts.AddMissingHeaderDeps)
  216. PP.SetSuppressIncludeNotFoundError(true);
  217. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  218. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callback));
  219. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  220. llvm::make_unique<DFGMMCallback>(*Callback));
  221. return new DependencyFileGenerator(Callback);
  222. }
  223. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  224. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  225. assert(I && "missing implementation");
  226. R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
  227. }
  228. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  229. /// considered as a dependency.
  230. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  231. SrcMgr::CharacteristicKind FileType) {
  232. if (isSpecialFilename(Filename))
  233. return false;
  234. if (IncludeSystemHeaders)
  235. return true;
  236. return !isSystem(FileType);
  237. }
  238. void DFGImpl::FileChanged(SourceLocation Loc,
  239. FileChangeReason Reason,
  240. SrcMgr::CharacteristicKind FileType,
  241. FileID PrevFID) {
  242. if (Reason != PPCallbacks::EnterFile)
  243. return;
  244. // Dependency generation really does want to go all the way to the
  245. // file entry for a source location to find out what is depended on.
  246. // We do not want #line markers to affect dependency generation!
  247. SourceManager &SM = PP->getSourceManager();
  248. const FileEntry *FE =
  249. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  250. if (!FE) return;
  251. StringRef Filename = FE->getName();
  252. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  253. return;
  254. AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
  255. }
  256. void DFGImpl::FileSkipped(const FileEntry &SkippedFile,
  257. const Token &FilenameTok,
  258. SrcMgr::CharacteristicKind FileType) {
  259. StringRef Filename = SkippedFile.getName();
  260. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  261. return;
  262. AddFilename(llvm::sys::path::remove_leading_dotslash(Filename));
  263. }
  264. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  265. const Token &IncludeTok,
  266. StringRef FileName,
  267. bool IsAngled,
  268. CharSourceRange FilenameRange,
  269. const FileEntry *File,
  270. StringRef SearchPath,
  271. StringRef RelativePath,
  272. const Module *Imported) {
  273. if (!File) {
  274. if (AddMissingHeaderDeps)
  275. AddFilename(FileName);
  276. else
  277. SeenMissingHeader = true;
  278. }
  279. }
  280. void DFGImpl::AddFilename(StringRef Filename) {
  281. if (FilesSet.insert(Filename).second)
  282. Files.push_back(Filename);
  283. }
  284. /// Print the filename, with escaping or quoting that accommodates the three
  285. /// most likely tools that use dependency files: GNU Make, BSD Make, and
  286. /// NMake/Jom.
  287. ///
  288. /// BSD Make is the simplest case: It does no escaping at all. This means
  289. /// characters that are normally delimiters, i.e. space and # (the comment
  290. /// character) simply aren't supported in filenames.
  291. ///
  292. /// GNU Make does allow space and # in filenames, but to avoid being treated
  293. /// as a delimiter or comment, these must be escaped with a backslash. Because
  294. /// backslash is itself the escape character, if a backslash appears in a
  295. /// filename, it should be escaped as well. (As a special case, $ is escaped
  296. /// as $$, which is the normal Make way to handle the $ character.)
  297. /// For compatibility with BSD Make and historical practice, if GNU Make
  298. /// un-escapes characters in a filename but doesn't find a match, it will
  299. /// retry with the unmodified original string.
  300. ///
  301. /// GCC tries to accommodate both Make formats by escaping any space or #
  302. /// characters in the original filename, but not escaping backslashes. The
  303. /// apparent intent is so that filenames with backslashes will be handled
  304. /// correctly by BSD Make, and by GNU Make in its fallback mode of using the
  305. /// unmodified original string; filenames with # or space characters aren't
  306. /// supported by BSD Make at all, but will be handled correctly by GNU Make
  307. /// due to the escaping.
  308. ///
  309. /// A corner case that GCC gets only partly right is when the original filename
  310. /// has a backslash immediately followed by space or #. GNU Make would expect
  311. /// this backslash to be escaped; however GCC escapes the original backslash
  312. /// only when followed by space, not #. It will therefore take a dependency
  313. /// from a directive such as
  314. /// #include "a\ b\#c.h"
  315. /// and emit it as
  316. /// a\\\ b\\#c.h
  317. /// which GNU Make will interpret as
  318. /// a\ b\
  319. /// followed by a comment. Failing to find this file, it will fall back to the
  320. /// original string, which probably doesn't exist either; in any case it won't
  321. /// find
  322. /// a\ b\#c.h
  323. /// which is the actual filename specified by the include directive.
  324. ///
  325. /// Clang does what GCC does, rather than what GNU Make expects.
  326. ///
  327. /// NMake/Jom has a different set of scary characters, but wraps filespecs in
  328. /// double-quotes to avoid misinterpreting them; see
  329. /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
  330. /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
  331. /// for Windows file-naming info.
  332. static void PrintFilename(raw_ostream &OS, StringRef Filename,
  333. DependencyOutputFormat OutputFormat) {
  334. if (OutputFormat == DependencyOutputFormat::NMake) {
  335. // Add quotes if needed. These are the characters listed as "special" to
  336. // NMake, that are legal in a Windows filespec, and that could cause
  337. // misinterpretation of the dependency string.
  338. if (Filename.find_first_of(" #${}^!") != StringRef::npos)
  339. OS << '\"' << Filename << '\"';
  340. else
  341. OS << Filename;
  342. return;
  343. }
  344. assert(OutputFormat == DependencyOutputFormat::Make);
  345. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  346. if (Filename[i] == '#') // Handle '#' the broken gcc way.
  347. OS << '\\';
  348. else if (Filename[i] == ' ') { // Handle space correctly.
  349. OS << '\\';
  350. unsigned j = i;
  351. while (j > 0 && Filename[--j] == '\\')
  352. OS << '\\';
  353. } else if (Filename[i] == '$') // $ is escaped by $$.
  354. OS << '$';
  355. OS << Filename[i];
  356. }
  357. }
  358. void DFGImpl::OutputDependencyFile() {
  359. if (SeenMissingHeader) {
  360. llvm::sys::fs::remove(OutputFile);
  361. return;
  362. }
  363. std::error_code EC;
  364. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  365. if (EC) {
  366. PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
  367. << EC.message();
  368. return;
  369. }
  370. // Write out the dependency targets, trying to avoid overly long
  371. // lines when possible. We try our best to emit exactly the same
  372. // dependency file as GCC (4.2), assuming the included files are the
  373. // same.
  374. const unsigned MaxColumns = 75;
  375. unsigned Columns = 0;
  376. for (StringRef Target : Targets) {
  377. unsigned N = Target.size();
  378. if (Columns == 0) {
  379. Columns += N;
  380. } else if (Columns + N + 2 > MaxColumns) {
  381. Columns = N + 2;
  382. OS << " \\\n ";
  383. } else {
  384. Columns += N + 1;
  385. OS << ' ';
  386. }
  387. // Targets already quoted as needed.
  388. OS << Target;
  389. }
  390. OS << ':';
  391. Columns += 1;
  392. // Now add each dependency in the order it was seen, but avoiding
  393. // duplicates.
  394. for (StringRef File : Files) {
  395. // Start a new line if this would exceed the column limit. Make
  396. // sure to leave space for a trailing " \" in case we need to
  397. // break the line on the next iteration.
  398. unsigned N = File.size();
  399. if (Columns + (N + 1) + 2 > MaxColumns) {
  400. OS << " \\\n ";
  401. Columns = 2;
  402. }
  403. OS << ' ';
  404. PrintFilename(OS, File, OutputFormat);
  405. Columns += N + 1;
  406. }
  407. OS << '\n';
  408. // Create phony targets if requested.
  409. if (PhonyTarget && !Files.empty()) {
  410. // Skip the first entry, this is always the input file itself.
  411. for (auto I = Files.begin() + 1, E = Files.end(); I != E; ++I) {
  412. OS << '\n';
  413. PrintFilename(OS, *I, OutputFormat);
  414. OS << ":\n";
  415. }
  416. }
  417. }
  418. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  419. bool IsSystem, bool IsOverridden,
  420. bool IsExplicitModule) {
  421. assert(!IsSystem || needsSystemInputFileVisitation());
  422. if (IsOverridden || IsExplicitModule)
  423. return true;
  424. Parent.AddFilename(Filename);
  425. return true;
  426. }
  427. void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename,
  428. serialization::ModuleKind Kind) {
  429. if (Parent.includeModuleFiles())
  430. Parent.AddFilename(Filename);
  431. }