Yi Kong | 878f994 | 2023-12-13 12:55:04 +0900 | [diff] [blame^] | 1 | //===- Utils.h - Misc utilities for the front-end ---------------*- C++ -*-===// |
| 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 | // |
| 9 | // This header contains miscellaneous utilities for various front-end actions. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #ifndef LLVM_CLANG_FRONTEND_UTILS_H |
| 14 | #define LLVM_CLANG_FRONTEND_UTILS_H |
| 15 | |
| 16 | #include "clang/Basic/Diagnostic.h" |
| 17 | #include "clang/Basic/LLVM.h" |
| 18 | #include "clang/Driver/OptionUtils.h" |
| 19 | #include "clang/Frontend/DependencyOutputOptions.h" |
| 20 | #include "llvm/ADT/ArrayRef.h" |
| 21 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
| 22 | #include "llvm/ADT/StringMap.h" |
| 23 | #include "llvm/ADT/StringRef.h" |
| 24 | #include "llvm/ADT/StringSet.h" |
| 25 | #include "llvm/Support/FileCollector.h" |
| 26 | #include "llvm/Support/VirtualFileSystem.h" |
| 27 | #include <cstdint> |
| 28 | #include <memory> |
| 29 | #include <string> |
| 30 | #include <system_error> |
| 31 | #include <utility> |
| 32 | #include <vector> |
| 33 | |
| 34 | namespace clang { |
| 35 | |
| 36 | class ASTReader; |
| 37 | class CompilerInstance; |
| 38 | class CompilerInvocation; |
| 39 | class DiagnosticsEngine; |
| 40 | class ExternalSemaSource; |
| 41 | class FrontendOptions; |
| 42 | class PCHContainerReader; |
| 43 | class Preprocessor; |
| 44 | class FileManager; |
| 45 | class PreprocessorOptions; |
| 46 | class PreprocessorOutputOptions; |
| 47 | |
| 48 | /// InitializePreprocessor - Initialize the preprocessor getting it and the |
| 49 | /// environment ready to process a single file. |
| 50 | void InitializePreprocessor(Preprocessor &PP, const PreprocessorOptions &PPOpts, |
| 51 | const PCHContainerReader &PCHContainerRdr, |
| 52 | const FrontendOptions &FEOpts); |
| 53 | |
| 54 | /// DoPrintPreprocessedInput - Implement -E mode. |
| 55 | void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream *OS, |
| 56 | const PreprocessorOutputOptions &Opts); |
| 57 | |
| 58 | /// An interface for collecting the dependencies of a compilation. Users should |
| 59 | /// use \c attachToPreprocessor and \c attachToASTReader to get all of the |
| 60 | /// dependencies. |
| 61 | /// FIXME: Migrate DependencyGraphGen to use this interface. |
| 62 | class DependencyCollector { |
| 63 | public: |
| 64 | virtual ~DependencyCollector(); |
| 65 | |
| 66 | virtual void attachToPreprocessor(Preprocessor &PP); |
| 67 | virtual void attachToASTReader(ASTReader &R); |
| 68 | ArrayRef<std::string> getDependencies() const { return Dependencies; } |
| 69 | |
| 70 | /// Called when a new file is seen. Return true if \p Filename should be added |
| 71 | /// to the list of dependencies. |
| 72 | /// |
| 73 | /// The default implementation ignores <built-in> and system files. |
| 74 | virtual bool sawDependency(StringRef Filename, bool FromModule, |
| 75 | bool IsSystem, bool IsModuleFile, bool IsMissing); |
| 76 | |
| 77 | /// Called when the end of the main file is reached. |
| 78 | virtual void finishedMainFile(DiagnosticsEngine &Diags) {} |
| 79 | |
| 80 | /// Return true if system files should be passed to sawDependency(). |
| 81 | virtual bool needSystemDependencies() { return false; } |
| 82 | |
| 83 | /// Return true if system files should be canonicalized. |
| 84 | virtual bool shouldCanonicalizeSystemDependencies() { return false; } |
| 85 | |
| 86 | /// Add a dependency \p Filename if it has not been seen before and |
| 87 | /// sawDependency() returns true. |
| 88 | virtual void maybeAddDependency(StringRef Filename, bool FromModule, |
| 89 | bool IsSystem, bool IsModuleFile, |
| 90 | FileManager *FileMgr, bool IsMissing); |
| 91 | |
| 92 | protected: |
| 93 | /// Return true if the filename was added to the list of dependencies, false |
| 94 | /// otherwise. |
| 95 | bool addDependency(StringRef Filename); |
| 96 | |
| 97 | private: |
| 98 | llvm::StringSet<> Seen; |
| 99 | std::vector<std::string> Dependencies; |
| 100 | }; |
| 101 | |
| 102 | /// Builds a dependency file when attached to a Preprocessor (for includes) and |
| 103 | /// ASTReader (for module imports), and writes it out at the end of processing |
| 104 | /// a source file. Users should attach to the ast reader whenever a module is |
| 105 | /// loaded. |
| 106 | class DependencyFileGenerator : public DependencyCollector { |
| 107 | public: |
| 108 | DependencyFileGenerator(const DependencyOutputOptions &Opts); |
| 109 | |
| 110 | void attachToPreprocessor(Preprocessor &PP) override; |
| 111 | |
| 112 | void finishedMainFile(DiagnosticsEngine &Diags) override; |
| 113 | |
| 114 | bool needSystemDependencies() final { return IncludeSystemHeaders; } |
| 115 | |
| 116 | bool sawDependency(StringRef Filename, bool FromModule, bool IsSystem, |
| 117 | bool IsModuleFile, bool IsMissing) final; |
| 118 | |
| 119 | bool shouldCanonicalizeSystemDependencies() override { |
| 120 | return CanonicalSystemHeaders; |
| 121 | } |
| 122 | |
| 123 | protected: |
| 124 | void outputDependencyFile(llvm::raw_ostream &OS); |
| 125 | |
| 126 | private: |
| 127 | void outputDependencyFile(DiagnosticsEngine &Diags); |
| 128 | |
| 129 | std::string OutputFile; |
| 130 | std::vector<std::string> Targets; |
| 131 | bool IncludeSystemHeaders; |
| 132 | bool CanonicalSystemHeaders; |
| 133 | bool PhonyTarget; |
| 134 | bool AddMissingHeaderDeps; |
| 135 | bool SeenMissingHeader; |
| 136 | bool IncludeModuleFiles; |
| 137 | DependencyOutputFormat OutputFormat; |
| 138 | unsigned InputFileIndex; |
| 139 | }; |
| 140 | |
| 141 | /// Collects the dependencies for imported modules into a directory. Users |
| 142 | /// should attach to the AST reader whenever a module is loaded. |
| 143 | class ModuleDependencyCollector : public DependencyCollector { |
| 144 | std::string DestDir; |
| 145 | bool HasErrors = false; |
| 146 | llvm::StringSet<> Seen; |
| 147 | llvm::vfs::YAMLVFSWriter VFSWriter; |
| 148 | llvm::FileCollector::PathCanonicalizer Canonicalizer; |
| 149 | |
| 150 | std::error_code copyToRoot(StringRef Src, StringRef Dst = {}); |
| 151 | |
| 152 | public: |
| 153 | ModuleDependencyCollector(std::string DestDir) |
| 154 | : DestDir(std::move(DestDir)) {} |
| 155 | ~ModuleDependencyCollector() override { writeFileMap(); } |
| 156 | |
| 157 | StringRef getDest() { return DestDir; } |
| 158 | virtual bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; } |
| 159 | virtual void addFile(StringRef Filename, StringRef FileDst = {}); |
| 160 | |
| 161 | virtual void addFileMapping(StringRef VPath, StringRef RPath) { |
| 162 | VFSWriter.addFileMapping(VPath, RPath); |
| 163 | } |
| 164 | |
| 165 | void attachToPreprocessor(Preprocessor &PP) override; |
| 166 | void attachToASTReader(ASTReader &R) override; |
| 167 | |
| 168 | virtual void writeFileMap(); |
| 169 | virtual bool hasErrors() { return HasErrors; } |
| 170 | }; |
| 171 | |
| 172 | /// AttachDependencyGraphGen - Create a dependency graph generator, and attach |
| 173 | /// it to the given preprocessor. |
| 174 | void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile, |
| 175 | StringRef SysRoot); |
| 176 | |
| 177 | /// AttachHeaderIncludeGen - Create a header include list generator, and attach |
| 178 | /// it to the given preprocessor. |
| 179 | /// |
| 180 | /// \param DepOpts - Options controlling the output. |
| 181 | /// \param ShowAllHeaders - If true, show all header information instead of just |
| 182 | /// headers following the predefines buffer. This is useful for making sure |
| 183 | /// includes mentioned on the command line are also reported, but differs from |
| 184 | /// the default behavior used by -H. |
| 185 | /// \param OutputPath - If non-empty, a path to write the header include |
| 186 | /// information to, instead of writing to stderr. |
| 187 | /// \param ShowDepth - Whether to indent to show the nesting of the includes. |
| 188 | /// \param MSStyle - Whether to print in cl.exe /showIncludes style. |
| 189 | void AttachHeaderIncludeGen(Preprocessor &PP, |
| 190 | const DependencyOutputOptions &DepOpts, |
| 191 | bool ShowAllHeaders = false, |
| 192 | StringRef OutputPath = {}, |
| 193 | bool ShowDepth = true, bool MSStyle = false); |
| 194 | |
| 195 | /// The ChainedIncludesSource class converts headers to chained PCHs in |
| 196 | /// memory, mainly for testing. |
| 197 | IntrusiveRefCntPtr<ExternalSemaSource> |
| 198 | createChainedIncludesSource(CompilerInstance &CI, |
| 199 | IntrusiveRefCntPtr<ExternalSemaSource> &Reader); |
| 200 | |
| 201 | /// Optional inputs to createInvocation. |
| 202 | struct CreateInvocationOptions { |
| 203 | /// Receives diagnostics encountered while parsing command-line flags. |
| 204 | /// If not provided, these are printed to stderr. |
| 205 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags = nullptr; |
| 206 | /// Used e.g. to probe for system headers locations. |
| 207 | /// If not provided, the real filesystem is used. |
| 208 | /// FIXME: the driver does perform some non-virtualized IO. |
| 209 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS = nullptr; |
| 210 | /// Whether to attempt to produce a non-null (possibly incorrect) invocation |
| 211 | /// if any errors were encountered. |
| 212 | /// By default, always return null on errors. |
| 213 | bool RecoverOnError = false; |
| 214 | /// Allow the driver to probe the filesystem for PCH files. |
| 215 | /// This is used to replace -include with -include-pch in the cc1 args. |
| 216 | /// FIXME: ProbePrecompiled=true is a poor, historical default. |
| 217 | /// It misbehaves if the PCH file is from GCC, has the wrong version, etc. |
| 218 | bool ProbePrecompiled = false; |
| 219 | /// If set, the target is populated with the cc1 args produced by the driver. |
| 220 | /// This may be populated even if createInvocation returns nullptr. |
| 221 | std::vector<std::string> *CC1Args = nullptr; |
| 222 | }; |
| 223 | |
| 224 | /// Interpret clang arguments in preparation to parse a file. |
| 225 | /// |
| 226 | /// This simulates a number of steps Clang takes when its driver is invoked: |
| 227 | /// - choosing actions (e.g compile + link) to run |
| 228 | /// - probing the system for settings like standard library locations |
| 229 | /// - spawning a cc1 subprocess to compile code, with more explicit arguments |
| 230 | /// - in the cc1 process, assembling those arguments into a CompilerInvocation |
| 231 | /// which is used to configure the parser |
| 232 | /// |
| 233 | /// This simulation is lossy, e.g. in some situations one driver run would |
| 234 | /// result in multiple parses. (Multi-arch, CUDA, ...). |
| 235 | /// This function tries to select a reasonable invocation that tools should use. |
| 236 | /// |
| 237 | /// Args[0] should be the driver name, such as "clang" or "/usr/bin/g++". |
| 238 | /// Absolute path is preferred - this affects searching for system headers. |
| 239 | /// |
| 240 | /// May return nullptr if an invocation could not be determined. |
| 241 | /// See CreateInvocationOptions::ShouldRecoverOnErrors to try harder! |
| 242 | std::unique_ptr<CompilerInvocation> |
| 243 | createInvocation(ArrayRef<const char *> Args, |
| 244 | CreateInvocationOptions Opts = {}); |
| 245 | |
| 246 | } // namespace clang |
| 247 | |
| 248 | #endif // LLVM_CLANG_FRONTEND_UTILS_H |