HeaderIncludeGen.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. //===-- HeaderIncludeGen.cpp - Generate Header Includes -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/DependencyOutputOptions.h"
  9. #include "clang/Frontend/Utils.h"
  10. #include "clang/Basic/SourceManager.h"
  11. #include "clang/Frontend/FrontendDiagnostic.h"
  12. #include "clang/Lex/Preprocessor.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/Support/raw_ostream.h"
  15. using namespace clang;
  16. namespace {
  17. class HeaderIncludesCallback : public PPCallbacks {
  18. SourceManager &SM;
  19. raw_ostream *OutputFile;
  20. const DependencyOutputOptions &DepOpts;
  21. unsigned CurrentIncludeDepth;
  22. bool HasProcessedPredefines;
  23. bool OwnsOutputFile;
  24. bool ShowAllHeaders;
  25. bool ShowDepth;
  26. bool MSStyle;
  27. public:
  28. HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,
  29. raw_ostream *OutputFile_,
  30. const DependencyOutputOptions &DepOpts,
  31. bool OwnsOutputFile_, bool ShowDepth_, bool MSStyle_)
  32. : SM(PP->getSourceManager()), OutputFile(OutputFile_), DepOpts(DepOpts),
  33. CurrentIncludeDepth(0), HasProcessedPredefines(false),
  34. OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),
  35. ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}
  36. ~HeaderIncludesCallback() override {
  37. if (OwnsOutputFile)
  38. delete OutputFile;
  39. }
  40. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  41. SrcMgr::CharacteristicKind FileType,
  42. FileID PrevFID) override;
  43. void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
  44. SrcMgr::CharacteristicKind FileType) override;
  45. };
  46. }
  47. static void PrintHeaderInfo(raw_ostream *OutputFile, StringRef Filename,
  48. bool ShowDepth, unsigned CurrentIncludeDepth,
  49. bool MSStyle) {
  50. // Write to a temporary string to avoid unnecessary flushing on errs().
  51. SmallString<512> Pathname(Filename);
  52. if (!MSStyle)
  53. Lexer::Stringify(Pathname);
  54. SmallString<256> Msg;
  55. if (MSStyle)
  56. Msg += "Note: including file:";
  57. if (ShowDepth) {
  58. // The main source file is at depth 1, so skip one dot.
  59. for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
  60. Msg += MSStyle ? ' ' : '.';
  61. if (!MSStyle)
  62. Msg += ' ';
  63. }
  64. Msg += Pathname;
  65. Msg += '\n';
  66. *OutputFile << Msg;
  67. OutputFile->flush();
  68. }
  69. void clang::AttachHeaderIncludeGen(Preprocessor &PP,
  70. const DependencyOutputOptions &DepOpts,
  71. bool ShowAllHeaders, StringRef OutputPath,
  72. bool ShowDepth, bool MSStyle) {
  73. raw_ostream *OutputFile = &llvm::errs();
  74. bool OwnsOutputFile = false;
  75. // Choose output stream, when printing in cl.exe /showIncludes style.
  76. if (MSStyle) {
  77. switch (DepOpts.ShowIncludesDest) {
  78. default:
  79. llvm_unreachable("Invalid destination for /showIncludes output!");
  80. case ShowIncludesDestination::Stderr:
  81. OutputFile = &llvm::errs();
  82. break;
  83. case ShowIncludesDestination::Stdout:
  84. OutputFile = &llvm::outs();
  85. break;
  86. }
  87. }
  88. // Open the output file, if used.
  89. if (!OutputPath.empty()) {
  90. std::error_code EC;
  91. llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
  92. OutputPath.str(), EC,
  93. llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
  94. if (EC) {
  95. PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
  96. << EC.message();
  97. delete OS;
  98. } else {
  99. OS->SetUnbuffered();
  100. OutputFile = OS;
  101. OwnsOutputFile = true;
  102. }
  103. }
  104. // Print header info for extra headers, pretending they were discovered by
  105. // the regular preprocessor. The primary use case is to support proper
  106. // generation of Make / Ninja file dependencies for implicit includes, such
  107. // as sanitizer ignorelists. It's only important for cl.exe compatibility,
  108. // the GNU way to generate rules is -M / -MM / -MD / -MMD.
  109. for (const auto &Header : DepOpts.ExtraDeps)
  110. PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);
  111. PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(
  112. &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
  113. MSStyle));
  114. }
  115. void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
  116. FileChangeReason Reason,
  117. SrcMgr::CharacteristicKind NewFileType,
  118. FileID PrevFID) {
  119. // Unless we are exiting a #include, make sure to skip ahead to the line the
  120. // #include directive was at.
  121. PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
  122. if (UserLoc.isInvalid())
  123. return;
  124. // Adjust the current include depth.
  125. if (Reason == PPCallbacks::EnterFile) {
  126. ++CurrentIncludeDepth;
  127. } else if (Reason == PPCallbacks::ExitFile) {
  128. if (CurrentIncludeDepth)
  129. --CurrentIncludeDepth;
  130. // We track when we are done with the predefines by watching for the first
  131. // place where we drop back to a nesting depth of 1.
  132. if (CurrentIncludeDepth == 1 && !HasProcessedPredefines) {
  133. if (!DepOpts.ShowIncludesPretendHeader.empty()) {
  134. PrintHeaderInfo(OutputFile, DepOpts.ShowIncludesPretendHeader,
  135. ShowDepth, 2, MSStyle);
  136. }
  137. HasProcessedPredefines = true;
  138. }
  139. return;
  140. } else
  141. return;
  142. // Show the header if we are (a) past the predefines, or (b) showing all
  143. // headers and in the predefines at a depth past the initial file and command
  144. // line buffers.
  145. bool ShowHeader = (HasProcessedPredefines ||
  146. (ShowAllHeaders && CurrentIncludeDepth > 2));
  147. unsigned IncludeDepth = CurrentIncludeDepth;
  148. if (!HasProcessedPredefines)
  149. --IncludeDepth; // Ignore indent from <built-in>.
  150. else if (!DepOpts.ShowIncludesPretendHeader.empty())
  151. ++IncludeDepth; // Pretend inclusion by ShowIncludesPretendHeader.
  152. if (!DepOpts.IncludeSystemHeaders && isSystem(NewFileType))
  153. ShowHeader = false;
  154. // Dump the header include information we are past the predefines buffer or
  155. // are showing all headers and this isn't the magic implicit <command line>
  156. // header.
  157. // FIXME: Identify headers in a more robust way than comparing their name to
  158. // "<command line>" and "<built-in>" in a bunch of places.
  159. if (ShowHeader && Reason == PPCallbacks::EnterFile &&
  160. UserLoc.getFilename() != StringRef("<command line>")) {
  161. PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,
  162. MSStyle);
  163. }
  164. }
  165. void HeaderIncludesCallback::FileSkipped(const FileEntryRef &SkippedFile, const
  166. Token &FilenameTok,
  167. SrcMgr::CharacteristicKind FileType) {
  168. if (!DepOpts.ShowSkippedHeaderIncludes)
  169. return;
  170. if (!DepOpts.IncludeSystemHeaders && isSystem(FileType))
  171. return;
  172. PrintHeaderInfo(OutputFile, SkippedFile.getName(), ShowDepth,
  173. CurrentIncludeDepth + 1, MSStyle);
  174. }