HeaderIncludeGen.cpp 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. };
  44. }
  45. static void PrintHeaderInfo(raw_ostream *OutputFile, StringRef Filename,
  46. bool ShowDepth, unsigned CurrentIncludeDepth,
  47. bool MSStyle) {
  48. // Write to a temporary string to avoid unnecessary flushing on errs().
  49. SmallString<512> Pathname(Filename);
  50. if (!MSStyle)
  51. Lexer::Stringify(Pathname);
  52. SmallString<256> Msg;
  53. if (MSStyle)
  54. Msg += "Note: including file:";
  55. if (ShowDepth) {
  56. // The main source file is at depth 1, so skip one dot.
  57. for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
  58. Msg += MSStyle ? ' ' : '.';
  59. if (!MSStyle)
  60. Msg += ' ';
  61. }
  62. Msg += Pathname;
  63. Msg += '\n';
  64. *OutputFile << Msg;
  65. OutputFile->flush();
  66. }
  67. void clang::AttachHeaderIncludeGen(Preprocessor &PP,
  68. const DependencyOutputOptions &DepOpts,
  69. bool ShowAllHeaders, StringRef OutputPath,
  70. bool ShowDepth, bool MSStyle) {
  71. raw_ostream *OutputFile = &llvm::errs();
  72. bool OwnsOutputFile = false;
  73. // Choose output stream, when printing in cl.exe /showIncludes style.
  74. if (MSStyle) {
  75. switch (DepOpts.ShowIncludesDest) {
  76. default:
  77. llvm_unreachable("Invalid destination for /showIncludes output!");
  78. case ShowIncludesDestination::Stderr:
  79. OutputFile = &llvm::errs();
  80. break;
  81. case ShowIncludesDestination::Stdout:
  82. OutputFile = &llvm::outs();
  83. break;
  84. }
  85. }
  86. // Open the output file, if used.
  87. if (!OutputPath.empty()) {
  88. std::error_code EC;
  89. llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
  90. OutputPath.str(), EC,
  91. llvm::sys::fs::OF_Append | llvm::sys::fs::OF_Text);
  92. if (EC) {
  93. PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
  94. << EC.message();
  95. delete OS;
  96. } else {
  97. OS->SetUnbuffered();
  98. OutputFile = OS;
  99. OwnsOutputFile = true;
  100. }
  101. }
  102. // Print header info for extra headers, pretending they were discovered by
  103. // the regular preprocessor. The primary use case is to support proper
  104. // generation of Make / Ninja file dependencies for implicit includes, such
  105. // as sanitizer blacklists. It's only important for cl.exe compatibility,
  106. // the GNU way to generate rules is -M / -MM / -MD / -MMD.
  107. for (const auto &Header : DepOpts.ExtraDeps)
  108. PrintHeaderInfo(OutputFile, Header, ShowDepth, 2, MSStyle);
  109. PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(
  110. &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
  111. MSStyle));
  112. }
  113. void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
  114. FileChangeReason Reason,
  115. SrcMgr::CharacteristicKind NewFileType,
  116. FileID PrevFID) {
  117. // Unless we are exiting a #include, make sure to skip ahead to the line the
  118. // #include directive was at.
  119. PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
  120. if (UserLoc.isInvalid())
  121. return;
  122. // Adjust the current include depth.
  123. if (Reason == PPCallbacks::EnterFile) {
  124. ++CurrentIncludeDepth;
  125. } else if (Reason == PPCallbacks::ExitFile) {
  126. if (CurrentIncludeDepth)
  127. --CurrentIncludeDepth;
  128. // We track when we are done with the predefines by watching for the first
  129. // place where we drop back to a nesting depth of 1.
  130. if (CurrentIncludeDepth == 1 && !HasProcessedPredefines) {
  131. if (!DepOpts.ShowIncludesPretendHeader.empty()) {
  132. PrintHeaderInfo(OutputFile, DepOpts.ShowIncludesPretendHeader,
  133. ShowDepth, 2, MSStyle);
  134. }
  135. HasProcessedPredefines = true;
  136. }
  137. return;
  138. } else
  139. return;
  140. // Show the header if we are (a) past the predefines, or (b) showing all
  141. // headers and in the predefines at a depth past the initial file and command
  142. // line buffers.
  143. bool ShowHeader = (HasProcessedPredefines ||
  144. (ShowAllHeaders && CurrentIncludeDepth > 2));
  145. unsigned IncludeDepth = CurrentIncludeDepth;
  146. if (!HasProcessedPredefines)
  147. --IncludeDepth; // Ignore indent from <built-in>.
  148. else if (!DepOpts.ShowIncludesPretendHeader.empty())
  149. ++IncludeDepth; // Pretend inclusion by ShowIncludesPretendHeader.
  150. // Dump the header include information we are past the predefines buffer or
  151. // are showing all headers and this isn't the magic implicit <command line>
  152. // header.
  153. // FIXME: Identify headers in a more robust way than comparing their name to
  154. // "<command line>" and "<built-in>" in a bunch of places.
  155. if (ShowHeader && Reason == PPCallbacks::EnterFile &&
  156. UserLoc.getFilename() != StringRef("<command line>")) {
  157. PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,
  158. MSStyle);
  159. }
  160. }