Path: blob/main/contrib/llvm-project/clang/lib/Frontend/HeaderIncludeGen.cpp
35232 views
//===-- HeaderIncludeGen.cpp - Generate Header Includes -------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#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/JSON.h"15#include "llvm/Support/raw_ostream.h"16using namespace clang;1718namespace {19class HeaderIncludesCallback : public PPCallbacks {20SourceManager &SM;21raw_ostream *OutputFile;22const DependencyOutputOptions &DepOpts;23unsigned CurrentIncludeDepth;24bool HasProcessedPredefines;25bool OwnsOutputFile;26bool ShowAllHeaders;27bool ShowDepth;28bool MSStyle;2930public:31HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,32raw_ostream *OutputFile_,33const DependencyOutputOptions &DepOpts,34bool OwnsOutputFile_, bool ShowDepth_, bool MSStyle_)35: SM(PP->getSourceManager()), OutputFile(OutputFile_), DepOpts(DepOpts),36CurrentIncludeDepth(0), HasProcessedPredefines(false),37OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),38ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}3940~HeaderIncludesCallback() override {41if (OwnsOutputFile)42delete OutputFile;43}4445HeaderIncludesCallback(const HeaderIncludesCallback &) = delete;46HeaderIncludesCallback &operator=(const HeaderIncludesCallback &) = delete;4748void FileChanged(SourceLocation Loc, FileChangeReason Reason,49SrcMgr::CharacteristicKind FileType,50FileID PrevFID) override;5152void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,53SrcMgr::CharacteristicKind FileType) override;5455private:56bool ShouldShowHeader(SrcMgr::CharacteristicKind HeaderType) {57if (!DepOpts.IncludeSystemHeaders && isSystem(HeaderType))58return false;5960// Show the current header if we are (a) past the predefines, or (b) showing61// all headers and in the predefines at a depth past the initial file and62// command line buffers.63return (HasProcessedPredefines ||64(ShowAllHeaders && CurrentIncludeDepth > 2));65}66};6768/// A callback for emitting header usage information to a file in JSON. Each69/// line in the file is a JSON object that includes the source file name and70/// the list of headers directly or indirectly included from it. For example:71///72/// {"source":"/tmp/foo.c",73/// "includes":["/usr/include/stdio.h", "/usr/include/stdlib.h"]}74///75/// To reduce the amount of data written to the file, we only record system76/// headers that are directly included from a file that isn't in the system77/// directory.78class HeaderIncludesJSONCallback : public PPCallbacks {79SourceManager &SM;80raw_ostream *OutputFile;81bool OwnsOutputFile;82SmallVector<std::string, 16> IncludedHeaders;8384public:85HeaderIncludesJSONCallback(const Preprocessor *PP, raw_ostream *OutputFile_,86bool OwnsOutputFile_)87: SM(PP->getSourceManager()), OutputFile(OutputFile_),88OwnsOutputFile(OwnsOutputFile_) {}8990~HeaderIncludesJSONCallback() override {91if (OwnsOutputFile)92delete OutputFile;93}9495HeaderIncludesJSONCallback(const HeaderIncludesJSONCallback &) = delete;96HeaderIncludesJSONCallback &97operator=(const HeaderIncludesJSONCallback &) = delete;9899void EndOfMainFile() override;100101void FileChanged(SourceLocation Loc, FileChangeReason Reason,102SrcMgr::CharacteristicKind FileType,103FileID PrevFID) override;104105void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,106SrcMgr::CharacteristicKind FileType) override;107};108}109110static void PrintHeaderInfo(raw_ostream *OutputFile, StringRef Filename,111bool ShowDepth, unsigned CurrentIncludeDepth,112bool MSStyle) {113// Write to a temporary string to avoid unnecessary flushing on errs().114SmallString<512> Pathname(Filename);115if (!MSStyle)116Lexer::Stringify(Pathname);117118SmallString<256> Msg;119if (MSStyle)120Msg += "Note: including file:";121122if (ShowDepth) {123// The main source file is at depth 1, so skip one dot.124for (unsigned i = 1; i != CurrentIncludeDepth; ++i)125Msg += MSStyle ? ' ' : '.';126127if (!MSStyle)128Msg += ' ';129}130Msg += Pathname;131Msg += '\n';132133*OutputFile << Msg;134OutputFile->flush();135}136137void clang::AttachHeaderIncludeGen(Preprocessor &PP,138const DependencyOutputOptions &DepOpts,139bool ShowAllHeaders, StringRef OutputPath,140bool ShowDepth, bool MSStyle) {141raw_ostream *OutputFile = &llvm::errs();142bool OwnsOutputFile = false;143144// Choose output stream, when printing in cl.exe /showIncludes style.145if (MSStyle) {146switch (DepOpts.ShowIncludesDest) {147default:148llvm_unreachable("Invalid destination for /showIncludes output!");149case ShowIncludesDestination::Stderr:150OutputFile = &llvm::errs();151break;152case ShowIncludesDestination::Stdout:153OutputFile = &llvm::outs();154break;155}156}157158// Open the output file, if used.159if (!OutputPath.empty()) {160std::error_code EC;161llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(162OutputPath.str(), EC,163llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);164if (EC) {165PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)166<< EC.message();167delete OS;168} else {169OS->SetUnbuffered();170OutputFile = OS;171OwnsOutputFile = true;172}173}174175switch (DepOpts.HeaderIncludeFormat) {176case HIFMT_None:177llvm_unreachable("unexpected header format kind");178case HIFMT_Textual: {179assert(DepOpts.HeaderIncludeFiltering == HIFIL_None &&180"header filtering is currently always disabled when output format is"181"textual");182// Print header info for extra headers, pretending they were discovered by183// the regular preprocessor. The primary use case is to support proper184// generation of Make / Ninja file dependencies for implicit includes, such185// as sanitizer ignorelists. It's only important for cl.exe compatibility,186// the GNU way to generate rules is -M / -MM / -MD / -MMD.187for (const auto &Header : DepOpts.ExtraDeps)188PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);189PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(190&PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,191MSStyle));192break;193}194case HIFMT_JSON: {195assert(DepOpts.HeaderIncludeFiltering == HIFIL_Only_Direct_System &&196"only-direct-system is the only option for filtering");197PP.addPPCallbacks(std::make_unique<HeaderIncludesJSONCallback>(198&PP, OutputFile, OwnsOutputFile));199break;200}201}202}203204void HeaderIncludesCallback::FileChanged(SourceLocation Loc,205FileChangeReason Reason,206SrcMgr::CharacteristicKind NewFileType,207FileID PrevFID) {208// Unless we are exiting a #include, make sure to skip ahead to the line the209// #include directive was at.210PresumedLoc UserLoc = SM.getPresumedLoc(Loc);211if (UserLoc.isInvalid())212return;213214// Adjust the current include depth.215if (Reason == PPCallbacks::EnterFile) {216++CurrentIncludeDepth;217} else if (Reason == PPCallbacks::ExitFile) {218if (CurrentIncludeDepth)219--CurrentIncludeDepth;220221// We track when we are done with the predefines by watching for the first222// place where we drop back to a nesting depth of 1.223if (CurrentIncludeDepth == 1 && !HasProcessedPredefines)224HasProcessedPredefines = true;225226return;227} else {228return;229}230231if (!ShouldShowHeader(NewFileType))232return;233234unsigned IncludeDepth = CurrentIncludeDepth;235if (!HasProcessedPredefines)236--IncludeDepth; // Ignore indent from <built-in>.237238// FIXME: Identify headers in a more robust way than comparing their name to239// "<command line>" and "<built-in>" in a bunch of places.240if (Reason == PPCallbacks::EnterFile &&241UserLoc.getFilename() != StringRef("<command line>")) {242PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,243MSStyle);244}245}246247void HeaderIncludesCallback::FileSkipped(const FileEntryRef &SkippedFile, const248Token &FilenameTok,249SrcMgr::CharacteristicKind FileType) {250if (!DepOpts.ShowSkippedHeaderIncludes)251return;252253if (!ShouldShowHeader(FileType))254return;255256PrintHeaderInfo(OutputFile, SkippedFile.getName(), ShowDepth,257CurrentIncludeDepth + 1, MSStyle);258}259260void HeaderIncludesJSONCallback::EndOfMainFile() {261OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getMainFileID());262SmallString<256> MainFile(FE->getName());263SM.getFileManager().makeAbsolutePath(MainFile);264265std::string Str;266llvm::raw_string_ostream OS(Str);267llvm::json::OStream JOS(OS);268JOS.object([&] {269JOS.attribute("source", MainFile.c_str());270JOS.attributeArray("includes", [&] {271llvm::StringSet<> SeenHeaders;272for (const std::string &H : IncludedHeaders)273if (SeenHeaders.insert(H).second)274JOS.value(H);275});276});277OS << "\n";278279if (OutputFile->get_kind() == raw_ostream::OStreamKind::OK_FDStream) {280llvm::raw_fd_ostream *FDS = static_cast<llvm::raw_fd_ostream *>(OutputFile);281if (auto L = FDS->lock())282*OutputFile << Str;283} else284*OutputFile << Str;285}286287/// Determine whether the header file should be recorded. The header file should288/// be recorded only if the header file is a system header and the current file289/// isn't a system header.290static bool shouldRecordNewFile(SrcMgr::CharacteristicKind NewFileType,291SourceLocation PrevLoc, SourceManager &SM) {292return SrcMgr::isSystem(NewFileType) && !SM.isInSystemHeader(PrevLoc);293}294295void HeaderIncludesJSONCallback::FileChanged(296SourceLocation Loc, FileChangeReason Reason,297SrcMgr::CharacteristicKind NewFileType, FileID PrevFID) {298if (PrevFID.isInvalid() ||299!shouldRecordNewFile(NewFileType, SM.getLocForStartOfFile(PrevFID), SM))300return;301302// Unless we are exiting a #include, make sure to skip ahead to the line the303// #include directive was at.304PresumedLoc UserLoc = SM.getPresumedLoc(Loc);305if (UserLoc.isInvalid())306return;307308if (Reason == PPCallbacks::EnterFile &&309UserLoc.getFilename() != StringRef("<command line>"))310IncludedHeaders.push_back(UserLoc.getFilename());311}312313void HeaderIncludesJSONCallback::FileSkipped(314const FileEntryRef &SkippedFile, const Token &FilenameTok,315SrcMgr::CharacteristicKind FileType) {316if (!shouldRecordNewFile(FileType, FilenameTok.getLocation(), SM))317return;318319IncludedHeaders.push_back(SkippedFile.getName().str());320}321322323