1 //===--- Utils.h - Misc utilities for the front-end -------------*- C++ -*-===//
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 header contains miscellaneous utilities for various front-end actions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_FRONTEND_UTILS_H
15 #define LLVM_CLANG_FRONTEND_UTILS_H
16 
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/VirtualFileSystem.h"
19 #include "llvm/ADT/IntrusiveRefCntPtr.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Option/OptSpecifier.h"
23 
24 namespace llvm {
25 class raw_fd_ostream;
26 class Triple;
27 
28 namespace opt {
29 class ArgList;
30 }
31 }
32 
33 namespace clang {
34 class ASTConsumer;
35 class ASTReader;
36 class CompilerInstance;
37 class CompilerInvocation;
38 class Decl;
39 class DependencyOutputOptions;
40 class DiagnosticsEngine;
41 class DiagnosticOptions;
42 class ExternalSemaSource;
43 class FileManager;
44 class HeaderSearch;
45 class HeaderSearchOptions;
46 class IdentifierTable;
47 class LangOptions;
48 class Preprocessor;
49 class PreprocessorOptions;
50 class PreprocessorOutputOptions;
51 class SourceManager;
52 class Stmt;
53 class TargetInfo;
54 class FrontendOptions;
55 
56 /// Apply the header search options to get given HeaderSearch object.
57 void ApplyHeaderSearchOptions(HeaderSearch &HS,
58                               const HeaderSearchOptions &HSOpts,
59                               const LangOptions &Lang,
60                               const llvm::Triple &triple);
61 
62 /// InitializePreprocessor - Initialize the preprocessor getting it and the
63 /// environment ready to process a single file.
64 void InitializePreprocessor(Preprocessor &PP,
65                             const PreprocessorOptions &PPOpts,
66                             const FrontendOptions &FEOpts);
67 
68 /// DoPrintPreprocessedInput - Implement -E mode.
69 void DoPrintPreprocessedInput(Preprocessor &PP, raw_ostream* OS,
70                               const PreprocessorOutputOptions &Opts);
71 
72 /// An interface for collecting the dependencies of a compilation. Users should
73 /// use \c attachToPreprocessor and \c attachToASTReader to get all of the
74 /// dependencies.
75 // FIXME: Migrate DependencyFileGen, DependencyGraphGen, ModuleDepCollectory to
76 // use this interface.
77 class DependencyCollector {
78 public:
79   void attachToPreprocessor(Preprocessor &PP);
80   void attachToASTReader(ASTReader &R);
getDependencies()81   llvm::ArrayRef<std::string> getDependencies() const { return Dependencies; }
82 
83   /// Called when a new file is seen. Return true if \p Filename should be added
84   /// to the list of dependencies.
85   ///
86   /// The default implementation ignores <built-in> and system files.
87   virtual bool sawDependency(StringRef Filename, bool FromModule,
88                              bool IsSystem, bool IsModuleFile, bool IsMissing);
89   /// Called when the end of the main file is reached.
finishedMainFile()90   virtual void finishedMainFile() { }
91   /// Return true if system files should be passed to sawDependency().
needSystemDependencies()92   virtual bool needSystemDependencies() { return false; }
93   virtual ~DependencyCollector();
94 
95 public: // implementation detail
96   /// Add a dependency \p Filename if it has not been seen before and
97   /// sawDependency() returns true.
98   void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem,
99                           bool IsModuleFile, bool IsMissing);
100 private:
101   llvm::StringSet<> Seen;
102   std::vector<std::string> Dependencies;
103 };
104 
105 /// Builds a depdenency file when attached to a Preprocessor (for includes) and
106 /// ASTReader (for module imports), and writes it out at the end of processing
107 /// a source file.  Users should attach to the ast reader whenever a module is
108 /// loaded.
109 class DependencyFileGenerator {
110   void *Impl; // Opaque implementation
111   DependencyFileGenerator(void *Impl);
112 public:
113   static DependencyFileGenerator *CreateAndAttachToPreprocessor(
114     Preprocessor &PP, const DependencyOutputOptions &Opts);
115   void AttachToASTReader(ASTReader &R);
116 };
117 
118 /// Collects the dependencies for imported modules into a directory.  Users
119 /// should attach to the AST reader whenever a module is loaded.
120 class ModuleDependencyCollector {
121   std::string DestDir;
122   bool HasErrors;
123   llvm::StringSet<> Seen;
124   vfs::YAMLVFSWriter VFSWriter;
125 
126 public:
getDest()127   StringRef getDest() { return DestDir; }
insertSeen(StringRef Filename)128   bool insertSeen(StringRef Filename) { return Seen.insert(Filename).second; }
setHasErrors()129   void setHasErrors() { HasErrors = true; }
addFileMapping(StringRef VPath,StringRef RPath)130   void addFileMapping(StringRef VPath, StringRef RPath) {
131     VFSWriter.addFileMapping(VPath, RPath);
132   }
133 
134   void attachToASTReader(ASTReader &R);
135   void writeFileMap();
hasErrors()136   bool hasErrors() { return HasErrors; }
ModuleDependencyCollector(std::string DestDir)137   ModuleDependencyCollector(std::string DestDir)
138       : DestDir(DestDir), HasErrors(false) {}
~ModuleDependencyCollector()139   ~ModuleDependencyCollector() { writeFileMap(); }
140 };
141 
142 /// AttachDependencyGraphGen - Create a dependency graph generator, and attach
143 /// it to the given preprocessor.
144   void AttachDependencyGraphGen(Preprocessor &PP, StringRef OutputFile,
145                                 StringRef SysRoot);
146 
147 /// AttachHeaderIncludeGen - Create a header include list generator, and attach
148 /// it to the given preprocessor.
149 ///
150 /// \param ShowAllHeaders - If true, show all header information instead of just
151 /// headers following the predefines buffer. This is useful for making sure
152 /// includes mentioned on the command line are also reported, but differs from
153 /// the default behavior used by -H.
154 /// \param OutputPath - If non-empty, a path to write the header include
155 /// information to, instead of writing to stderr.
156 /// \param ShowDepth - Whether to indent to show the nesting of the includes.
157 /// \param MSStyle - Whether to print in cl.exe /showIncludes style.
158 void AttachHeaderIncludeGen(Preprocessor &PP, bool ShowAllHeaders = false,
159                             StringRef OutputPath = "",
160                             bool ShowDepth = true, bool MSStyle = false);
161 
162 /// Cache tokens for use with PCH. Note that this requires a seekable stream.
163 void CacheTokens(Preprocessor &PP, raw_pwrite_stream *OS);
164 
165 /// The ChainedIncludesSource class converts headers to chained PCHs in
166 /// memory, mainly for testing.
167 IntrusiveRefCntPtr<ExternalSemaSource>
168 createChainedIncludesSource(CompilerInstance &CI,
169                             IntrusiveRefCntPtr<ExternalSemaSource> &Reader);
170 
171 /// createInvocationFromCommandLine - Construct a compiler invocation object for
172 /// a command line argument vector.
173 ///
174 /// \return A CompilerInvocation, or 0 if none was built for the given
175 /// argument vector.
176 CompilerInvocation *
177 createInvocationFromCommandLine(ArrayRef<const char *> Args,
178                             IntrusiveRefCntPtr<DiagnosticsEngine> Diags =
179                                 IntrusiveRefCntPtr<DiagnosticsEngine>());
180 
181 /// Return the value of the last argument as an integer, or a default. If Diags
182 /// is non-null, emits an error if the argument is given, but non-integral.
183 int getLastArgIntValue(const llvm::opt::ArgList &Args,
184                        llvm::opt::OptSpecifier Id, int Default,
185                        DiagnosticsEngine *Diags = nullptr);
186 
getLastArgIntValue(const llvm::opt::ArgList & Args,llvm::opt::OptSpecifier Id,int Default,DiagnosticsEngine & Diags)187 inline int getLastArgIntValue(const llvm::opt::ArgList &Args,
188                               llvm::opt::OptSpecifier Id, int Default,
189                               DiagnosticsEngine &Diags) {
190   return getLastArgIntValue(Args, Id, Default, &Diags);
191 }
192 
193 uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
194                                llvm::opt::OptSpecifier Id, uint64_t Default,
195                                DiagnosticsEngine *Diags = nullptr);
196 
getLastArgUInt64Value(const llvm::opt::ArgList & Args,llvm::opt::OptSpecifier Id,uint64_t Default,DiagnosticsEngine & Diags)197 inline uint64_t getLastArgUInt64Value(const llvm::opt::ArgList &Args,
198                                       llvm::opt::OptSpecifier Id,
199                                       uint64_t Default,
200                                       DiagnosticsEngine &Diags) {
201   return getLastArgUInt64Value(Args, Id, Default, &Diags);
202 }
203 
204 // When Clang->getFrontendOpts().DisableFree is set we don't delete some of the
205 // global objects, but we don't want LeakDetectors to complain, so we bury them
206 // in a globally visible array.
207 void BuryPointer(const void *Ptr);
BuryPointer(std::unique_ptr<T> Ptr)208 template <typename T> void BuryPointer(std::unique_ptr<T> Ptr) {
209   BuryPointer(Ptr.release());
210 }
211 
212 } // end namespace clang
213 
214 #endif
215