1 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- 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 // ASTUnit utility class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
16 
17 #include "clang-c/Index.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Lex/HeaderSearchOptions.h"
25 #include "clang/Lex/ModuleLoader.h"
26 #include "clang/Lex/PreprocessingRecord.h"
27 #include "clang/Sema/CodeCompleteConsumer.h"
28 #include "clang/Serialization/ASTBitCodes.h"
29 #include "llvm/ADT/IntrusiveRefCntPtr.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/Path.h"
34 #include <cassert>
35 #include <map>
36 #include <memory>
37 #include <string>
38 #include <sys/types.h>
39 #include <utility>
40 #include <vector>
41 
42 namespace llvm {
43   class MemoryBuffer;
44 }
45 
46 namespace clang {
47 class Sema;
48 class ASTContext;
49 class ASTReader;
50 class CodeCompleteConsumer;
51 class CompilerInvocation;
52 class CompilerInstance;
53 class Decl;
54 class DiagnosticsEngine;
55 class FileEntry;
56 class FileManager;
57 class HeaderSearch;
58 class Preprocessor;
59 class PCHContainerOperations;
60 class PCHContainerReader;
61 class SourceManager;
62 class TargetInfo;
63 class ASTFrontendAction;
64 class ASTDeserializationListener;
65 
66 /// \brief Utility class for loading a ASTContext from an AST file.
67 ///
68 class ASTUnit : public ModuleLoader {
69 public:
70   struct StandaloneFixIt {
71     std::pair<unsigned, unsigned> RemoveRange;
72     std::pair<unsigned, unsigned> InsertFromRange;
73     std::string CodeToInsert;
74     bool BeforePreviousInsertions;
75   };
76 
77   struct StandaloneDiagnostic {
78     unsigned ID;
79     DiagnosticsEngine::Level Level;
80     std::string Message;
81     std::string Filename;
82     unsigned LocOffset;
83     std::vector<std::pair<unsigned, unsigned> > Ranges;
84     std::vector<StandaloneFixIt> FixIts;
85   };
86 
87 private:
88   std::shared_ptr<LangOptions>            LangOpts;
89   IntrusiveRefCntPtr<DiagnosticsEngine>   Diagnostics;
90   IntrusiveRefCntPtr<FileManager>         FileMgr;
91   IntrusiveRefCntPtr<SourceManager>       SourceMgr;
92   std::unique_ptr<HeaderSearch>           HeaderInfo;
93   IntrusiveRefCntPtr<TargetInfo>          Target;
94   IntrusiveRefCntPtr<Preprocessor>        PP;
95   IntrusiveRefCntPtr<ASTContext>          Ctx;
96   std::shared_ptr<TargetOptions>          TargetOpts;
97   IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
98   IntrusiveRefCntPtr<ASTReader> Reader;
99   bool HadModuleLoaderFatalFailure;
100 
101   struct ASTWriterData;
102   std::unique_ptr<ASTWriterData> WriterData;
103 
104   FileSystemOptions FileSystemOpts;
105 
106   /// \brief The AST consumer that received information about the translation
107   /// unit as it was parsed or loaded.
108   std::unique_ptr<ASTConsumer> Consumer;
109 
110   /// \brief The semantic analysis object used to type-check the translation
111   /// unit.
112   std::unique_ptr<Sema> TheSema;
113 
114   /// Optional owned invocation, just used to make the invocation used in
115   /// LoadFromCommandLine available.
116   IntrusiveRefCntPtr<CompilerInvocation> Invocation;
117 
118   // OnlyLocalDecls - when true, walking this AST should only visit declarations
119   // that come from the AST itself, not from included precompiled headers.
120   // FIXME: This is temporary; eventually, CIndex will always do this.
121   bool                              OnlyLocalDecls;
122 
123   /// \brief Whether to capture any diagnostics produced.
124   bool CaptureDiagnostics;
125 
126   /// \brief Track whether the main file was loaded from an AST or not.
127   bool MainFileIsAST;
128 
129   /// \brief What kind of translation unit this AST represents.
130   TranslationUnitKind TUKind;
131 
132   /// \brief Whether we should time each operation.
133   bool WantTiming;
134 
135   /// \brief Whether the ASTUnit should delete the remapped buffers.
136   bool OwnsRemappedFileBuffers;
137 
138   /// Track the top-level decls which appeared in an ASTUnit which was loaded
139   /// from a source file.
140   //
141   // FIXME: This is just an optimization hack to avoid deserializing large parts
142   // of a PCH file when using the Index library on an ASTUnit loaded from
143   // source. In the long term we should make the Index library use efficient and
144   // more scalable search mechanisms.
145   std::vector<Decl*> TopLevelDecls;
146 
147   /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
148   typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
149   typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
150 
151   /// \brief Map from FileID to the file-level declarations that it contains.
152   /// The files and decls are only local (and non-preamble) ones.
153   FileDeclsTy FileDecls;
154 
155   /// The name of the original source file used to generate this ASTUnit.
156   std::string OriginalSourceFile;
157 
158   /// \brief The set of diagnostics produced when creating the preamble.
159   SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
160 
161   /// \brief The set of diagnostics produced when creating this
162   /// translation unit.
163   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
164 
165   /// \brief The set of diagnostics produced when failing to parse, e.g. due
166   /// to failure to load the PCH.
167   SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
168 
169   /// \brief The number of stored diagnostics that come from the driver
170   /// itself.
171   ///
172   /// Diagnostics that come from the driver are retained from one parse to
173   /// the next.
174   unsigned NumStoredDiagnosticsFromDriver;
175 
176   /// \brief Counter that determines when we want to try building a
177   /// precompiled preamble.
178   ///
179   /// If zero, we will never build a precompiled preamble. Otherwise,
180   /// it's treated as a counter that decrements each time we reparse
181   /// without the benefit of a precompiled preamble. When it hits 1,
182   /// we'll attempt to rebuild the precompiled header. This way, if
183   /// building the precompiled preamble fails, we won't try again for
184   /// some number of calls.
185   unsigned PreambleRebuildCounter;
186 
187 public:
188   class PreambleData {
189     const FileEntry *File;
190     std::vector<char> Buffer;
191     mutable unsigned NumLines;
192 
193   public:
PreambleData()194     PreambleData() : File(nullptr), NumLines(0) { }
195 
assign(const FileEntry * F,const char * begin,const char * end)196     void assign(const FileEntry *F, const char *begin, const char *end) {
197       File = F;
198       Buffer.assign(begin, end);
199       NumLines = 0;
200     }
201 
clear()202     void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
203 
size()204     size_t size() const { return Buffer.size(); }
empty()205     bool empty() const { return Buffer.empty(); }
206 
getBufferStart()207     const char *getBufferStart() const { return &Buffer[0]; }
208 
getNumLines()209     unsigned getNumLines() const {
210       if (NumLines)
211         return NumLines;
212       countLines();
213       return NumLines;
214     }
215 
getSourceRange(const SourceManager & SM)216     SourceRange getSourceRange(const SourceManager &SM) const {
217       SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
218       return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
219     }
220 
221   private:
222     void countLines() const;
223   };
224 
getPreambleData()225   const PreambleData &getPreambleData() const {
226     return Preamble;
227   }
228 
229   /// Data used to determine if a file used in the preamble has been changed.
230   struct PreambleFileHash {
231     /// All files have size set.
232     off_t Size;
233 
234     /// Modification time is set for files that are on disk.  For memory
235     /// buffers it is zero.
236     time_t ModTime;
237 
238     /// Memory buffers have MD5 instead of modification time.  We don't
239     /// compute MD5 for on-disk files because we hope that modification time is
240     /// enough to tell if the file was changed.
241     llvm::MD5::MD5Result MD5;
242 
243     static PreambleFileHash createForFile(off_t Size, time_t ModTime);
244     static PreambleFileHash
245     createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
246 
247     friend bool operator==(const PreambleFileHash &LHS,
248                            const PreambleFileHash &RHS);
249 
250     friend bool operator!=(const PreambleFileHash &LHS,
251                            const PreambleFileHash &RHS) {
252       return !(LHS == RHS);
253     }
254   };
255 
256 private:
257   /// \brief The contents of the preamble that has been precompiled to
258   /// \c PreambleFile.
259   PreambleData Preamble;
260 
261   /// \brief Whether the preamble ends at the start of a new line.
262   ///
263   /// Used to inform the lexer as to whether it's starting at the beginning of
264   /// a line after skipping the preamble.
265   bool PreambleEndsAtStartOfLine;
266 
267   /// \brief Keeps track of the files that were used when computing the
268   /// preamble, with both their buffer size and their modification time.
269   ///
270   /// If any of the files have changed from one compile to the next,
271   /// the preamble must be thrown away.
272   llvm::StringMap<PreambleFileHash> FilesInPreamble;
273 
274   /// \brief When non-NULL, this is the buffer used to store the contents of
275   /// the main file when it has been padded for use with the precompiled
276   /// preamble.
277   std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
278 
279   /// \brief When non-NULL, this is the buffer used to store the
280   /// contents of the preamble when it has been padded to build the
281   /// precompiled preamble.
282   std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
283 
284   /// \brief The number of warnings that occurred while parsing the preamble.
285   ///
286   /// This value will be used to restore the state of the \c DiagnosticsEngine
287   /// object when re-using the precompiled preamble. Note that only the
288   /// number of warnings matters, since we will not save the preamble
289   /// when any errors are present.
290   unsigned NumWarningsInPreamble;
291 
292   /// \brief A list of the serialization ID numbers for each of the top-level
293   /// declarations parsed within the precompiled preamble.
294   std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
295 
296   /// \brief Whether we should be caching code-completion results.
297   bool ShouldCacheCodeCompletionResults : 1;
298 
299   /// \brief Whether to include brief documentation within the set of code
300   /// completions cached.
301   bool IncludeBriefCommentsInCodeCompletion : 1;
302 
303   /// \brief True if non-system source files should be treated as volatile
304   /// (likely to change while trying to use them).
305   bool UserFilesAreVolatile : 1;
306 
307   /// \brief The language options used when we load an AST file.
308   LangOptions ASTFileLangOpts;
309 
310   static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
311                              ASTUnit &AST, bool CaptureDiagnostics);
312 
313   void TranslateStoredDiagnostics(FileManager &FileMgr,
314                                   SourceManager &SrcMan,
315                       const SmallVectorImpl<StandaloneDiagnostic> &Diags,
316                             SmallVectorImpl<StoredDiagnostic> &Out);
317 
318   void clearFileLevelDecls();
319 
320 public:
321   /// \brief A cached code-completion result, which may be introduced in one of
322   /// many different contexts.
323   struct CachedCodeCompletionResult {
324     /// \brief The code-completion string corresponding to this completion
325     /// result.
326     CodeCompletionString *Completion;
327 
328     /// \brief A bitmask that indicates which code-completion contexts should
329     /// contain this completion result.
330     ///
331     /// The bits in the bitmask correspond to the values of
332     /// CodeCompleteContext::Kind. To map from a completion context kind to a
333     /// bit, shift 1 by that number of bits. Many completions can occur in
334     /// several different contexts.
335     uint64_t ShowInContexts;
336 
337     /// \brief The priority given to this code-completion result.
338     unsigned Priority;
339 
340     /// \brief The libclang cursor kind corresponding to this code-completion
341     /// result.
342     CXCursorKind Kind;
343 
344     /// \brief The availability of this code-completion result.
345     CXAvailabilityKind Availability;
346 
347     /// \brief The simplified type class for a non-macro completion result.
348     SimplifiedTypeClass TypeClass;
349 
350     /// \brief The type of a non-macro completion result, stored as a unique
351     /// integer used by the string map of cached completion types.
352     ///
353     /// This value will be zero if the type is not known, or a unique value
354     /// determined by the formatted type string. Se \c CachedCompletionTypes
355     /// for more information.
356     unsigned Type;
357   };
358 
359   /// \brief Retrieve the mapping from formatted type names to unique type
360   /// identifiers.
getCachedCompletionTypes()361   llvm::StringMap<unsigned> &getCachedCompletionTypes() {
362     return CachedCompletionTypes;
363   }
364 
365   /// \brief Retrieve the allocator used to cache global code completions.
366   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
getCachedCompletionAllocator()367   getCachedCompletionAllocator() {
368     return CachedCompletionAllocator;
369   }
370 
getCodeCompletionTUInfo()371   CodeCompletionTUInfo &getCodeCompletionTUInfo() {
372     if (!CCTUInfo)
373       CCTUInfo.reset(new CodeCompletionTUInfo(
374                                             new GlobalCodeCompletionAllocator));
375     return *CCTUInfo;
376   }
377 
378 private:
379   /// \brief Allocator used to store cached code completions.
380   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
381     CachedCompletionAllocator;
382 
383   std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
384 
385   /// \brief The set of cached code-completion results.
386   std::vector<CachedCodeCompletionResult> CachedCompletionResults;
387 
388   /// \brief A mapping from the formatted type name to a unique number for that
389   /// type, which is used for type equality comparisons.
390   llvm::StringMap<unsigned> CachedCompletionTypes;
391 
392   /// \brief A string hash of the top-level declaration and macro definition
393   /// names processed the last time that we reparsed the file.
394   ///
395   /// This hash value is used to determine when we need to refresh the
396   /// global code-completion cache.
397   unsigned CompletionCacheTopLevelHashValue;
398 
399   /// \brief A string hash of the top-level declaration and macro definition
400   /// names processed the last time that we reparsed the precompiled preamble.
401   ///
402   /// This hash value is used to determine when we need to refresh the
403   /// global code-completion cache after a rebuild of the precompiled preamble.
404   unsigned PreambleTopLevelHashValue;
405 
406   /// \brief The current hash value for the top-level declaration and macro
407   /// definition names
408   unsigned CurrentTopLevelHashValue;
409 
410   /// \brief Bit used by CIndex to mark when a translation unit may be in an
411   /// inconsistent state, and is not safe to free.
412   unsigned UnsafeToFree : 1;
413 
414   /// \brief Cache any "global" code-completion results, so that we can avoid
415   /// recomputing them with each completion.
416   void CacheCodeCompletionResults();
417 
418   /// \brief Clear out and deallocate
419   void ClearCachedCompletionResults();
420 
421   ASTUnit(const ASTUnit &) = delete;
422   void operator=(const ASTUnit &) = delete;
423 
424   explicit ASTUnit(bool MainFileIsAST);
425 
426   void CleanTemporaryFiles();
427   bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
428              std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
429 
430   struct ComputedPreamble {
431     llvm::MemoryBuffer *Buffer;
432     std::unique_ptr<llvm::MemoryBuffer> Owner;
433     unsigned Size;
434     bool PreambleEndsAtStartOfLine;
ComputedPreambleComputedPreamble435     ComputedPreamble(llvm::MemoryBuffer *Buffer,
436                      std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
437                      bool PreambleEndsAtStartOfLine)
438         : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
439           PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
ComputedPreambleComputedPreamble440     ComputedPreamble(ComputedPreamble &&C)
441         : Buffer(C.Buffer), Owner(std::move(C.Owner)), Size(C.Size),
442           PreambleEndsAtStartOfLine(C.PreambleEndsAtStartOfLine) {}
443   };
444   ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
445                                    unsigned MaxLines);
446 
447   std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
448       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
449       const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
450       unsigned MaxLines = 0);
451   void RealizeTopLevelDeclsFromPreamble();
452 
453   /// \brief Transfers ownership of the objects (like SourceManager) from
454   /// \param CI to this ASTUnit.
455   void transferASTDataFromCompilerInstance(CompilerInstance &CI);
456 
457   /// \brief Allows us to assert that ASTUnit is not being used concurrently,
458   /// which is not supported.
459   ///
460   /// Clients should create instances of the ConcurrencyCheck class whenever
461   /// using the ASTUnit in a way that isn't intended to be concurrent, which is
462   /// just about any usage.
463   /// Becomes a noop in release mode; only useful for debug mode checking.
464   class ConcurrencyState {
465     void *Mutex; // a llvm::sys::MutexImpl in debug;
466 
467   public:
468     ConcurrencyState();
469     ~ConcurrencyState();
470 
471     void start();
472     void finish();
473   };
474   ConcurrencyState ConcurrencyCheckValue;
475 
476 public:
477   class ConcurrencyCheck {
478     ASTUnit &Self;
479 
480   public:
ConcurrencyCheck(ASTUnit & Self)481     explicit ConcurrencyCheck(ASTUnit &Self)
482       : Self(Self)
483     {
484       Self.ConcurrencyCheckValue.start();
485     }
~ConcurrencyCheck()486     ~ConcurrencyCheck() {
487       Self.ConcurrencyCheckValue.finish();
488     }
489   };
490   friend class ConcurrencyCheck;
491 
492   ~ASTUnit() override;
493 
isMainFileAST()494   bool isMainFileAST() const { return MainFileIsAST; }
495 
isUnsafeToFree()496   bool isUnsafeToFree() const { return UnsafeToFree; }
setUnsafeToFree(bool Value)497   void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
498 
getDiagnostics()499   const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
getDiagnostics()500   DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
501 
getSourceManager()502   const SourceManager &getSourceManager() const { return *SourceMgr; }
getSourceManager()503         SourceManager &getSourceManager()       { return *SourceMgr; }
504 
getPreprocessor()505   const Preprocessor &getPreprocessor() const { return *PP; }
getPreprocessor()506         Preprocessor &getPreprocessor()       { return *PP; }
507 
getASTContext()508   const ASTContext &getASTContext() const { return *Ctx; }
getASTContext()509         ASTContext &getASTContext()       { return *Ctx; }
510 
setASTContext(ASTContext * ctx)511   void setASTContext(ASTContext *ctx) { Ctx = ctx; }
512   void setPreprocessor(Preprocessor *pp);
513 
hasSema()514   bool hasSema() const { return (bool)TheSema; }
getSema()515   Sema &getSema() const {
516     assert(TheSema && "ASTUnit does not have a Sema object!");
517     return *TheSema;
518   }
519 
getLangOpts()520   const LangOptions &getLangOpts() const {
521     assert(LangOpts && " ASTUnit does not have language options");
522     return *LangOpts;
523   }
524 
getFileManager()525   const FileManager &getFileManager() const { return *FileMgr; }
getFileManager()526         FileManager &getFileManager()       { return *FileMgr; }
527 
getFileSystemOpts()528   const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
529 
getOriginalSourceFileName()530   StringRef getOriginalSourceFileName() {
531     return OriginalSourceFile;
532   }
533 
534   ASTMutationListener *getASTMutationListener();
535   ASTDeserializationListener *getDeserializationListener();
536 
537   /// \brief Add a temporary file that the ASTUnit depends on.
538   ///
539   /// This file will be erased when the ASTUnit is destroyed.
540   void addTemporaryFile(StringRef TempFile);
541 
getOnlyLocalDecls()542   bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
543 
getOwnsRemappedFileBuffers()544   bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
setOwnsRemappedFileBuffers(bool val)545   void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
546 
547   StringRef getMainFileName() const;
548 
549   /// \brief If this ASTUnit came from an AST file, returns the filename for it.
550   StringRef getASTFileName() const;
551 
552   typedef std::vector<Decl *>::iterator top_level_iterator;
553 
top_level_begin()554   top_level_iterator top_level_begin() {
555     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
556     if (!TopLevelDeclsInPreamble.empty())
557       RealizeTopLevelDeclsFromPreamble();
558     return TopLevelDecls.begin();
559   }
560 
top_level_end()561   top_level_iterator top_level_end() {
562     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
563     if (!TopLevelDeclsInPreamble.empty())
564       RealizeTopLevelDeclsFromPreamble();
565     return TopLevelDecls.end();
566   }
567 
top_level_size()568   std::size_t top_level_size() const {
569     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
570     return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
571   }
572 
top_level_empty()573   bool top_level_empty() const {
574     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
575     return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
576   }
577 
578   /// \brief Add a new top-level declaration.
addTopLevelDecl(Decl * D)579   void addTopLevelDecl(Decl *D) {
580     TopLevelDecls.push_back(D);
581   }
582 
583   /// \brief Add a new local file-level declaration.
584   void addFileLevelDecl(Decl *D);
585 
586   /// \brief Get the decls that are contained in a file in the Offset/Length
587   /// range. \p Length can be 0 to indicate a point at \p Offset instead of
588   /// a range.
589   void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
590                            SmallVectorImpl<Decl *> &Decls);
591 
592   /// \brief Add a new top-level declaration, identified by its ID in
593   /// the precompiled preamble.
addTopLevelDeclFromPreamble(serialization::DeclID D)594   void addTopLevelDeclFromPreamble(serialization::DeclID D) {
595     TopLevelDeclsInPreamble.push_back(D);
596   }
597 
598   /// \brief Retrieve a reference to the current top-level name hash value.
599   ///
600   /// Note: This is used internally by the top-level tracking action
getCurrentTopLevelHashValue()601   unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
602 
603   /// \brief Get the source location for the given file:line:col triplet.
604   ///
605   /// The difference with SourceManager::getLocation is that this method checks
606   /// whether the requested location points inside the precompiled preamble
607   /// in which case the returned source location will be a "loaded" one.
608   SourceLocation getLocation(const FileEntry *File,
609                              unsigned Line, unsigned Col) const;
610 
611   /// \brief Get the source location for the given file:offset pair.
612   SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
613 
614   /// \brief If \p Loc is a loaded location from the preamble, returns
615   /// the corresponding local location of the main file, otherwise it returns
616   /// \p Loc.
617   SourceLocation mapLocationFromPreamble(SourceLocation Loc);
618 
619   /// \brief If \p Loc is a local location of the main file but inside the
620   /// preamble chunk, returns the corresponding loaded location from the
621   /// preamble, otherwise it returns \p Loc.
622   SourceLocation mapLocationToPreamble(SourceLocation Loc);
623 
624   bool isInPreambleFileID(SourceLocation Loc);
625   bool isInMainFileID(SourceLocation Loc);
626   SourceLocation getStartOfMainFileID();
627   SourceLocation getEndOfPreambleFileID();
628 
629   /// \see mapLocationFromPreamble.
mapRangeFromPreamble(SourceRange R)630   SourceRange mapRangeFromPreamble(SourceRange R) {
631     return SourceRange(mapLocationFromPreamble(R.getBegin()),
632                        mapLocationFromPreamble(R.getEnd()));
633   }
634 
635   /// \see mapLocationToPreamble.
mapRangeToPreamble(SourceRange R)636   SourceRange mapRangeToPreamble(SourceRange R) {
637     return SourceRange(mapLocationToPreamble(R.getBegin()),
638                        mapLocationToPreamble(R.getEnd()));
639   }
640 
641   // Retrieve the diagnostics associated with this AST
642   typedef StoredDiagnostic *stored_diag_iterator;
643   typedef const StoredDiagnostic *stored_diag_const_iterator;
stored_diag_begin()644   stored_diag_const_iterator stored_diag_begin() const {
645     return StoredDiagnostics.begin();
646   }
stored_diag_begin()647   stored_diag_iterator stored_diag_begin() {
648     return StoredDiagnostics.begin();
649   }
stored_diag_end()650   stored_diag_const_iterator stored_diag_end() const {
651     return StoredDiagnostics.end();
652   }
stored_diag_end()653   stored_diag_iterator stored_diag_end() {
654     return StoredDiagnostics.end();
655   }
stored_diag_size()656   unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
657 
stored_diag_afterDriver_begin()658   stored_diag_iterator stored_diag_afterDriver_begin() {
659     if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
660       NumStoredDiagnosticsFromDriver = 0;
661     return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
662   }
663 
664   typedef std::vector<CachedCodeCompletionResult>::iterator
665     cached_completion_iterator;
666 
cached_completion_begin()667   cached_completion_iterator cached_completion_begin() {
668     return CachedCompletionResults.begin();
669   }
670 
cached_completion_end()671   cached_completion_iterator cached_completion_end() {
672     return CachedCompletionResults.end();
673   }
674 
cached_completion_size()675   unsigned cached_completion_size() const {
676     return CachedCompletionResults.size();
677   }
678 
679   /// \brief Returns an iterator range for the local preprocessing entities
680   /// of the local Preprocessor, if this is a parsed source file, or the loaded
681   /// preprocessing entities of the primary module if this is an AST file.
682   llvm::iterator_range<PreprocessingRecord::iterator>
683   getLocalPreprocessingEntities() const;
684 
685   /// \brief Type for a function iterating over a number of declarations.
686   /// \returns true to continue iteration and false to abort.
687   typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
688 
689   /// \brief Iterate over local declarations (locally parsed if this is a parsed
690   /// source file or the loaded declarations of the primary module if this is an
691   /// AST file).
692   /// \returns true if the iteration was complete or false if it was aborted.
693   bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
694 
695   /// \brief Get the PCH file if one was included.
696   const FileEntry *getPCHFile();
697 
698   /// \brief Returns true if the ASTUnit was constructed from a serialized
699   /// module file.
700   bool isModuleFile();
701 
702   std::unique_ptr<llvm::MemoryBuffer>
703   getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
704 
705   /// \brief Determine what kind of translation unit this AST represents.
getTranslationUnitKind()706   TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
707 
708   /// \brief A mapping from a file name to the memory buffer that stores the
709   /// remapped contents of that file.
710   typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
711 
712   /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
713   static ASTUnit *create(CompilerInvocation *CI,
714                          IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
715                          bool CaptureDiagnostics,
716                          bool UserFilesAreVolatile);
717 
718   /// \brief Create a ASTUnit from an AST file.
719   ///
720   /// \param Filename - The AST file to load.
721   ///
722   /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
723   /// creating modules.
724   /// \param Diags - The diagnostics engine to use for reporting errors; its
725   /// lifetime is expected to extend past that of the returned ASTUnit.
726   ///
727   /// \returns - The initialized ASTUnit or null if the AST failed to load.
728   static std::unique_ptr<ASTUnit> LoadFromASTFile(
729       const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
730       IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
731       const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
732       bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
733       bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
734       bool UserFilesAreVolatile = false);
735 
736 private:
737   /// \brief Helper function for \c LoadFromCompilerInvocation() and
738   /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
739   ///
740   /// \param PrecompilePreambleAfterNParses After how many parses the preamble
741   /// of this translation unit should be precompiled, to improve the performance
742   /// of reparsing. Set to zero to disable preambles.
743   ///
744   /// \returns \c true if a catastrophic failure occurred (which means that the
745   /// \c ASTUnit itself is invalid), or \c false otherwise.
746   bool LoadFromCompilerInvocation(
747       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
748       unsigned PrecompilePreambleAfterNParses);
749 
750 public:
751 
752   /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
753   /// object, by invoking the optionally provided ASTFrontendAction.
754   ///
755   /// \param CI - The compiler invocation to use; it must have exactly one input
756   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
757   ///
758   /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
759   /// creating modules.
760   ///
761   /// \param Diags - The diagnostics engine to use for reporting errors; its
762   /// lifetime is expected to extend past that of the returned ASTUnit.
763   ///
764   /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
765   /// transferred.
766   ///
767   /// \param Unit - optionally an already created ASTUnit. Its ownership is not
768   /// transferred.
769   ///
770   /// \param Persistent - if true the returned ASTUnit will be complete.
771   /// false means the caller is only interested in getting info through the
772   /// provided \see Action.
773   ///
774   /// \param ErrAST - If non-null and parsing failed without any AST to return
775   /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
776   /// mainly to allow the caller to see the diagnostics.
777   /// This will only receive an ASTUnit if a new one was created. If an already
778   /// created ASTUnit was passed in \p Unit then the caller can check that.
779   ///
780   static ASTUnit *LoadFromCompilerInvocationAction(
781       CompilerInvocation *CI,
782       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
783       IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
784       ASTFrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
785       bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
786       bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
787       unsigned PrecompilePreambleAfterNParses = 0,
788       bool CacheCodeCompletionResults = false,
789       bool IncludeBriefCommentsInCodeCompletion = false,
790       bool UserFilesAreVolatile = false,
791       std::unique_ptr<ASTUnit> *ErrAST = nullptr);
792 
793   /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
794   /// CompilerInvocation object.
795   ///
796   /// \param CI - The compiler invocation to use; it must have exactly one input
797   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
798   ///
799   /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
800   /// creating modules.
801   ///
802   /// \param Diags - The diagnostics engine to use for reporting errors; its
803   /// lifetime is expected to extend past that of the returned ASTUnit.
804   //
805   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
806   // shouldn't need to specify them at construction time.
807   static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
808       CompilerInvocation *CI,
809       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
810       IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
811       bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
812       unsigned PrecompilePreambleAfterNParses = 0,
813       TranslationUnitKind TUKind = TU_Complete,
814       bool CacheCodeCompletionResults = false,
815       bool IncludeBriefCommentsInCodeCompletion = false,
816       bool UserFilesAreVolatile = false);
817 
818   /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
819   /// arguments, which must specify exactly one source file.
820   ///
821   /// \param ArgBegin - The beginning of the argument vector.
822   ///
823   /// \param ArgEnd - The end of the argument vector.
824   ///
825   /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
826   /// creating modules.
827   ///
828   /// \param Diags - The diagnostics engine to use for reporting errors; its
829   /// lifetime is expected to extend past that of the returned ASTUnit.
830   ///
831   /// \param ResourceFilesPath - The path to the compiler resource files.
832   ///
833   /// \param ModuleFormat - If provided, uses the specific module format.
834   ///
835   /// \param ErrAST - If non-null and parsing failed without any AST to return
836   /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
837   /// mainly to allow the caller to see the diagnostics.
838   ///
839   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
840   // shouldn't need to specify them at construction time.
841   static ASTUnit *LoadFromCommandLine(
842       const char **ArgBegin, const char **ArgEnd,
843       std::shared_ptr<PCHContainerOperations> PCHContainerOps,
844       IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
845       bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
846       ArrayRef<RemappedFile> RemappedFiles = None,
847       bool RemappedFilesKeepOriginalName = true,
848       unsigned PrecompilePreambleAfterNParses = 0,
849       TranslationUnitKind TUKind = TU_Complete,
850       bool CacheCodeCompletionResults = false,
851       bool IncludeBriefCommentsInCodeCompletion = false,
852       bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
853       bool UserFilesAreVolatile = false, bool ForSerialization = false,
854       llvm::Optional<StringRef> ModuleFormat = llvm::None,
855       std::unique_ptr<ASTUnit> *ErrAST = nullptr);
856 
857   /// \brief Reparse the source files using the same command-line options that
858   /// were originally used to produce this translation unit.
859   ///
860   /// \returns True if a failure occurred that causes the ASTUnit not to
861   /// contain any translation-unit information, false otherwise.
862   bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
863                ArrayRef<RemappedFile> RemappedFiles = None);
864 
865   /// \brief Perform code completion at the given file, line, and
866   /// column within this translation unit.
867   ///
868   /// \param File The file in which code completion will occur.
869   ///
870   /// \param Line The line at which code completion will occur.
871   ///
872   /// \param Column The column at which code completion will occur.
873   ///
874   /// \param IncludeMacros Whether to include macros in the code-completion
875   /// results.
876   ///
877   /// \param IncludeCodePatterns Whether to include code patterns (such as a
878   /// for loop) in the code-completion results.
879   ///
880   /// \param IncludeBriefComments Whether to include brief documentation within
881   /// the set of code completions returned.
882   ///
883   /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
884   /// OwnedBuffers parameters are all disgusting hacks. They will go away.
885   void CodeComplete(StringRef File, unsigned Line, unsigned Column,
886                     ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
887                     bool IncludeCodePatterns, bool IncludeBriefComments,
888                     CodeCompleteConsumer &Consumer,
889                     std::shared_ptr<PCHContainerOperations> PCHContainerOps,
890                     DiagnosticsEngine &Diag, LangOptions &LangOpts,
891                     SourceManager &SourceMgr, FileManager &FileMgr,
892                     SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
893                     SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
894 
895   /// \brief Save this translation unit to a file with the given name.
896   ///
897   /// \returns true if there was a file error or false if the save was
898   /// successful.
899   bool Save(StringRef File);
900 
901   /// \brief Serialize this translation unit with the given output stream.
902   ///
903   /// \returns True if an error occurred, false otherwise.
904   bool serialize(raw_ostream &OS);
905 
loadModule(SourceLocation ImportLoc,ModuleIdPath Path,Module::NameVisibilityKind Visibility,bool IsInclusionDirective)906   ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
907                               Module::NameVisibilityKind Visibility,
908                               bool IsInclusionDirective) override {
909     // ASTUnit doesn't know how to load modules (not that this matters).
910     return ModuleLoadResult();
911   }
912 
makeModuleVisible(Module * Mod,Module::NameVisibilityKind Visibility,SourceLocation ImportLoc)913   void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
914                          SourceLocation ImportLoc) override {}
915 
loadGlobalModuleIndex(SourceLocation TriggerLoc)916   GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
917     { return nullptr; }
lookupMissingImports(StringRef Name,SourceLocation TriggerLoc)918   bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override
919     { return 0; }
920 };
921 
922 } // namespace clang
923 
924 #endif
925