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