]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ASTReader.h
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / include / clang / Serialization / ASTReader.h
1 //===--- ASTReader.h - AST File Reader --------------------------*- 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 file defines the ASTReader class, which reads AST files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_FRONTEND_AST_READER_H
15 #define LLVM_CLANG_FRONTEND_AST_READER_H
16
17 #include "clang/Serialization/ASTBitCodes.h"
18 #include "clang/Sema/ExternalSemaSource.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/TemplateBase.h"
22 #include "clang/Lex/ExternalPreprocessorSource.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/PreprocessingRecord.h"
25 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/IdentifierTable.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/OwningPtr.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Bitcode/BitstreamReader.h"
35 #include "llvm/Support/DataTypes.h"
36 #include <deque>
37 #include <map>
38 #include <string>
39 #include <utility>
40 #include <vector>
41
42 namespace llvm {
43   class MemoryBuffer;
44 }
45
46 namespace clang {
47
48 class AddrLabelExpr;
49 class ASTConsumer;
50 class ASTContext;
51 class ASTIdentifierIterator;
52 class Attr;
53 class Decl;
54 class DeclContext;
55 class NestedNameSpecifier;
56 class CXXBaseSpecifier;
57 class CXXConstructorDecl;
58 class CXXCtorInitializer;
59 class GotoStmt;
60 class MacroDefinition;
61 class NamedDecl;
62 class OpaqueValueExpr;
63 class Preprocessor;
64 class Sema;
65 class SwitchCase;
66 class ASTDeserializationListener;
67 class ASTReader;
68 class ASTDeclReader;
69 class ASTStmtReader;
70 class ASTIdentifierLookupTrait;
71 class TypeLocReader;
72 struct HeaderFileInfo;
73 class VersionTuple;
74
75 struct PCHPredefinesBlock {
76   /// \brief The file ID for this predefines buffer in a PCH file.
77   FileID BufferID;
78
79   /// \brief This predefines buffer in a PCH file.
80   llvm::StringRef Data;
81 };
82 typedef llvm::SmallVector<PCHPredefinesBlock, 2> PCHPredefinesBlocks;
83
84 /// \brief Abstract interface for callback invocations by the ASTReader.
85 ///
86 /// While reading an AST file, the ASTReader will call the methods of the
87 /// listener to pass on specific information. Some of the listener methods can
88 /// return true to indicate to the ASTReader that the information (and
89 /// consequently the AST file) is invalid.
90 class ASTReaderListener {
91 public:
92   virtual ~ASTReaderListener();
93
94   /// \brief Receives the language options.
95   ///
96   /// \returns true to indicate the options are invalid or false otherwise.
97   virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
98     return false;
99   }
100
101   /// \brief Receives the target triple.
102   ///
103   /// \returns true to indicate the target triple is invalid or false otherwise.
104   virtual bool ReadTargetTriple(llvm::StringRef Triple) {
105     return false;
106   }
107
108   /// \brief Receives the contents of the predefines buffer.
109   ///
110   /// \param Buffers Information about the predefines buffers.
111   ///
112   /// \param OriginalFileName The original file name for the AST file, which
113   /// will appear as an entry in the predefines buffer.
114   ///
115   /// \param SuggestedPredefines If necessary, additional definitions are added
116   /// here.
117   ///
118   /// \returns true to indicate the predefines are invalid or false otherwise.
119   virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
120                                     llvm::StringRef OriginalFileName,
121                                     std::string &SuggestedPredefines,
122                                     FileManager &FileMgr) {
123     return false;
124   }
125
126   /// \brief Receives a HeaderFileInfo entry.
127   virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {}
128
129   /// \brief Receives __COUNTER__ value.
130   virtual void ReadCounter(unsigned Value) {}
131 };
132
133 /// \brief ASTReaderListener implementation to validate the information of
134 /// the PCH file against an initialized Preprocessor.
135 class PCHValidator : public ASTReaderListener {
136   Preprocessor &PP;
137   ASTReader &Reader;
138
139   unsigned NumHeaderInfos;
140
141 public:
142   PCHValidator(Preprocessor &PP, ASTReader &Reader)
143     : PP(PP), Reader(Reader), NumHeaderInfos(0) {}
144
145   virtual bool ReadLanguageOptions(const LangOptions &LangOpts);
146   virtual bool ReadTargetTriple(llvm::StringRef Triple);
147   virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
148                                     llvm::StringRef OriginalFileName,
149                                     std::string &SuggestedPredefines,
150                                     FileManager &FileMgr);
151   virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID);
152   virtual void ReadCounter(unsigned Value);
153
154 private:
155   void Error(const char *Msg);
156 };
157
158 /// \brief Reads an AST files chain containing the contents of a translation
159 /// unit.
160 ///
161 /// The ASTReader class reads bitstreams (produced by the ASTWriter
162 /// class) containing the serialized representation of a given
163 /// abstract syntax tree and its supporting data structures. An
164 /// instance of the ASTReader can be attached to an ASTContext object,
165 /// which will provide access to the contents of the AST files.
166 ///
167 /// The AST reader provides lazy de-serialization of declarations, as
168 /// required when traversing the AST. Only those AST nodes that are
169 /// actually required will be de-serialized.
170 class ASTReader
171   : public ExternalPreprocessorSource,
172     public ExternalPreprocessingRecordSource,
173     public ExternalHeaderFileInfoSource,
174     public ExternalSemaSource,
175     public IdentifierInfoLookup,
176     public ExternalIdentifierLookup,
177     public ExternalSLocEntrySource 
178 {
179 public:
180   enum ASTReadResult { Success, Failure, IgnorePCH };
181   /// \brief Types of AST files.
182   enum ASTFileType {
183     Module,   ///< File is a module proper.
184     PCH,      ///< File is a PCH file treated as such.
185     Preamble, ///< File is a PCH file treated as the preamble.
186     MainFile  ///< File is a PCH file treated as the actual main file.
187   };
188   friend class PCHValidator;
189   friend class ASTDeclReader;
190   friend class ASTStmtReader;
191   friend class ASTIdentifierIterator;
192   friend class ASTIdentifierLookupTrait;
193   friend class TypeLocReader;
194 private:
195   /// \brief The receiver of some callbacks invoked by ASTReader.
196   llvm::OwningPtr<ASTReaderListener> Listener;
197
198   /// \brief The receiver of deserialization events.
199   ASTDeserializationListener *DeserializationListener;
200
201   SourceManager &SourceMgr;
202   FileManager &FileMgr;
203   Diagnostic &Diags;
204
205   /// \brief The semantic analysis object that will be processing the
206   /// AST files and the translation unit that uses it.
207   Sema *SemaObj;
208
209   /// \brief The preprocessor that will be loading the source file.
210   Preprocessor *PP;
211
212   /// \brief The AST context into which we'll read the AST files.
213   ASTContext *Context;
214       
215   /// \brief The AST consumer.
216   ASTConsumer *Consumer;
217
218   /// \brief AST buffers for chained PCHs created and stored in memory.
219   /// First (not depending on another) PCH in chain is in front.
220   std::vector<llvm::MemoryBuffer *> ASTBuffers;
221
222   /// \brief Information that is needed for every module.
223   struct PerFileData {
224     PerFileData(ASTFileType Ty);
225     ~PerFileData();
226
227     // === General information ===
228
229     /// \brief The type of this AST file.
230     ASTFileType Type;
231
232     /// \brief The file name of the AST file.
233     std::string FileName;
234
235     /// \brief The memory buffer that stores the data associated with
236     /// this AST file.
237     llvm::OwningPtr<llvm::MemoryBuffer> Buffer;
238
239     /// \brief The size of this file, in bits.
240     uint64_t SizeInBits;
241
242     /// \brief The bitstream reader from which we'll read the AST file.
243     llvm::BitstreamReader StreamFile;
244
245     /// \brief The main bitstream cursor for the main block.
246     llvm::BitstreamCursor Stream;
247
248     // === Source Locations ===
249
250     /// \brief Cursor used to read source location entries.
251     llvm::BitstreamCursor SLocEntryCursor;
252
253     /// \brief The number of source location entries in this AST file.
254     unsigned LocalNumSLocEntries;
255
256     /// \brief Offsets for all of the source location entries in the
257     /// AST file.
258     const uint32_t *SLocOffsets;
259
260     /// \brief The number of source location file entries in this AST file.
261     unsigned LocalNumSLocFileEntries;
262
263     /// \brief Offsets for all of the source location file entries in the
264     /// AST file.
265     const uint32_t *SLocFileOffsets;
266
267     /// \brief The entire size of this module's source location offset range.
268     unsigned LocalSLocSize;
269
270     // === Identifiers ===
271
272     /// \brief The number of identifiers in this AST file.
273     unsigned LocalNumIdentifiers;
274
275     /// \brief Offsets into the identifier table data.
276     ///
277     /// This array is indexed by the identifier ID (-1), and provides
278     /// the offset into IdentifierTableData where the string data is
279     /// stored.
280     const uint32_t *IdentifierOffsets;
281
282     /// \brief Actual data for the on-disk hash table of identifiers.
283     ///
284     /// This pointer points into a memory buffer, where the on-disk hash
285     /// table for identifiers actually lives.
286     const char *IdentifierTableData;
287
288     /// \brief A pointer to an on-disk hash table of opaque type
289     /// IdentifierHashTable.
290     void *IdentifierLookupTable;
291
292     // === Macros ===
293
294     /// \brief The cursor to the start of the preprocessor block, which stores
295     /// all of the macro definitions.
296     llvm::BitstreamCursor MacroCursor;
297
298     /// \brief The offset of the start of the set of defined macros.
299     uint64_t MacroStartOffset;
300     
301     // === Detailed PreprocessingRecord ===
302     
303     /// \brief The cursor to the start of the (optional) detailed preprocessing 
304     /// record block.
305     llvm::BitstreamCursor PreprocessorDetailCursor;
306     
307     /// \brief The offset of the start of the preprocessor detail cursor.
308     uint64_t PreprocessorDetailStartOffset;
309     
310     /// \brief The number of macro definitions in this file.
311     unsigned LocalNumMacroDefinitions;
312     
313     /// \brief Offsets of all of the macro definitions in the preprocessing
314     /// record in the AST file.
315     const uint32_t *MacroDefinitionOffsets;
316
317     // === Header search information ===
318     
319     /// \brief The number of local HeaderFileInfo structures.
320     unsigned LocalNumHeaderFileInfos;
321     
322     /// \brief Actual data for the on-disk hash table of header file 
323     /// information.
324     ///
325     /// This pointer points into a memory buffer, where the on-disk hash
326     /// table for header file information actually lives.
327     const char *HeaderFileInfoTableData;
328
329     /// \brief The on-disk hash table that contains information about each of
330     /// the header files.
331     void *HeaderFileInfoTable;
332     
333     // === Selectors ===
334
335     /// \brief The number of selectors new to this file.
336     ///
337     /// This is the number of entries in SelectorOffsets.
338     unsigned LocalNumSelectors;
339
340     /// \brief Offsets into the selector lookup table's data array
341     /// where each selector resides.
342     const uint32_t *SelectorOffsets;
343
344     /// \brief A pointer to the character data that comprises the selector table
345     ///
346     /// The SelectorOffsets table refers into this memory.
347     const unsigned char *SelectorLookupTableData;
348
349     /// \brief A pointer to an on-disk hash table of opaque type
350     /// ASTSelectorLookupTable.
351     ///
352     /// This hash table provides the IDs of all selectors, and the associated
353     /// instance and factory methods.
354     void *SelectorLookupTable;
355
356     /// \brief Method selectors used in a @selector expression. Used for
357     /// implementation of -Wselector.
358     llvm::SmallVector<uint64_t, 64> ReferencedSelectorsData;
359
360     // === Declarations ===
361       
362     /// DeclsCursor - This is a cursor to the start of the DECLS_BLOCK block. It
363     /// has read all the abbreviations at the start of the block and is ready to
364     /// jump around with these in context.
365     llvm::BitstreamCursor DeclsCursor;
366
367     /// \brief The number of declarations in this AST file.
368     unsigned LocalNumDecls;
369
370     /// \brief Offset of each declaration within the bitstream, indexed
371     /// by the declaration ID (-1).
372     const uint32_t *DeclOffsets;
373
374     /// \brief A snapshot of the pending instantiations in the chain.
375     ///
376     /// This record tracks the instantiations that Sema has to perform at the
377     /// end of the TU. It consists of a pair of values for every pending
378     /// instantiation where the first value is the ID of the decl and the second
379     /// is the instantiation location.
380     llvm::SmallVector<uint64_t, 64> PendingInstantiations;
381
382     /// \brief The number of C++ base specifier sets in this AST file.
383     unsigned LocalNumCXXBaseSpecifiers;
384     
385     /// \brief Offset of each C++ base specifier set within the bitstream,
386     /// indexed by the C++ base specifier set ID (-1).
387     const uint32_t *CXXBaseSpecifiersOffsets;
388     
389     // === Types ===
390
391     /// \brief The number of types in this AST file.
392     unsigned LocalNumTypes;
393
394     /// \brief Offset of each type within the bitstream, indexed by the
395     /// type ID, or the representation of a Type*.
396     const uint32_t *TypeOffsets;
397
398     // === Miscellaneous ===
399
400     /// \brief The AST stat cache installed for this file, if any.
401     ///
402     /// The dynamic type of this stat cache is always ASTStatCache
403     void *StatCache;
404
405     /// \brief The number of preallocated preprocessing entities in the
406     /// preprocessing record.
407     unsigned NumPreallocatedPreprocessingEntities;
408
409     /// \brief The next module in source order.
410     PerFileData *NextInSource;
411
412     /// \brief All the modules that loaded this one. Can contain NULL for
413     /// directly loaded modules.
414     llvm::SmallVector<PerFileData *, 1> Loaders;
415   };
416
417   /// \brief All loaded modules, indexed by name.
418   llvm::StringMap<PerFileData*> Modules;
419
420   /// \brief The first module in source order.
421   PerFileData *FirstInSource;
422
423   /// \brief The chain of AST files. The first entry is the one named by the
424   /// user, the last one is the one that doesn't depend on anything further.
425   /// That is, the entry I was created with -include-pch I+1.
426   llvm::SmallVector<PerFileData*, 2> Chain;
427
428   /// \brief SLocEntries that we're going to preload.
429   llvm::SmallVector<uint64_t, 64> PreloadSLocEntries;
430
431   /// \brief Types that have already been loaded from the chain.
432   ///
433   /// When the pointer at index I is non-NULL, the type with
434   /// ID = (I + 1) << FastQual::Width has already been loaded
435   std::vector<QualType> TypesLoaded;
436
437   /// \brief Map that provides the ID numbers of each type within the
438   /// output stream, plus those deserialized from a chained PCH.
439   ///
440   /// The ID numbers of types are consecutive (in order of discovery)
441   /// and start at 1. 0 is reserved for NULL. When types are actually
442   /// stored in the stream, the ID number is shifted by 2 bits to
443   /// allow for the const/volatile qualifiers.
444   ///
445   /// Keys in the map never have const/volatile qualifiers.
446   serialization::TypeIdxMap TypeIdxs;
447
448   /// \brief Declarations that have already been loaded from the chain.
449   ///
450   /// When the pointer at index I is non-NULL, the declaration with ID
451   /// = I + 1 has already been loaded.
452   std::vector<Decl *> DeclsLoaded;
453
454   typedef std::pair<PerFileData *, uint64_t> FileOffset;
455   typedef llvm::SmallVector<FileOffset, 2> FileOffsetsTy;
456   typedef llvm::DenseMap<serialization::DeclID, FileOffsetsTy>
457       DeclUpdateOffsetsMap;
458   /// \brief Declarations that have modifications residing in a later file
459   /// in the chain.
460   DeclUpdateOffsetsMap DeclUpdateOffsets;
461
462   typedef llvm::DenseMap<serialization::DeclID,
463                          std::pair<PerFileData *, uint64_t> >
464       DeclReplacementMap;
465   /// \brief Declarations that have been replaced in a later file in the chain.
466   DeclReplacementMap ReplacedDecls;
467
468   /// \brief Information about the contents of a DeclContext.
469   struct DeclContextInfo {
470     void *NameLookupTableData; // a ASTDeclContextNameLookupTable.
471     const serialization::KindDeclIDPair *LexicalDecls;
472     unsigned NumLexicalDecls;
473   };
474   // In a full chain, there could be multiple updates to every decl context,
475   // so this is a vector. However, typically a chain is only two elements long,
476   // with only one file containing updates, so there will be only one update
477   // per decl context.
478   typedef llvm::SmallVector<DeclContextInfo, 1> DeclContextInfos;
479   typedef llvm::DenseMap<const DeclContext *, DeclContextInfos>
480       DeclContextOffsetsMap;
481   // Updates for visible decls can occur for other contexts than just the
482   // TU, and when we read those update records, the actual context will not
483   // be available yet (unless it's the TU), so have this pending map using the
484   // ID as a key. It will be realized when the context is actually loaded.
485   typedef llvm::SmallVector<void *, 1> DeclContextVisibleUpdates;
486   typedef llvm::DenseMap<serialization::DeclID, DeclContextVisibleUpdates>
487       DeclContextVisibleUpdatesPending;
488
489   /// \brief Offsets of the lexical and visible declarations for each
490   /// DeclContext.
491   DeclContextOffsetsMap DeclContextOffsets;
492
493   /// \brief Updates to the visible declarations of declaration contexts that
494   /// haven't been loaded yet.
495   DeclContextVisibleUpdatesPending PendingVisibleUpdates;
496
497   typedef llvm::SmallVector<CXXRecordDecl *, 4> ForwardRefs;
498   typedef llvm::DenseMap<const CXXRecordDecl *, ForwardRefs>
499       PendingForwardRefsMap;
500   /// \brief Forward references that have a definition but the definition decl
501   /// is still initializing. When the definition gets read it will update
502   /// the DefinitionData pointer of all pending references.
503   PendingForwardRefsMap PendingForwardRefs;
504
505   typedef llvm::DenseMap<serialization::DeclID, serialization::DeclID>
506       FirstLatestDeclIDMap;
507   /// \brief Map of first declarations from a chained PCH that point to the
508   /// most recent declarations in another AST file.
509   FirstLatestDeclIDMap FirstLatestDeclIDs;
510
511   /// \brief Read the records that describe the contents of declcontexts.
512   bool ReadDeclContextStorage(llvm::BitstreamCursor &Cursor,
513                               const std::pair<uint64_t, uint64_t> &Offsets,
514                               DeclContextInfo &Info);
515
516   /// \brief A vector containing identifiers that have already been
517   /// loaded.
518   ///
519   /// If the pointer at index I is non-NULL, then it refers to the
520   /// IdentifierInfo for the identifier with ID=I+1 that has already
521   /// been loaded.
522   std::vector<IdentifierInfo *> IdentifiersLoaded;
523
524   /// \brief A vector containing selectors that have already been loaded.
525   ///
526   /// This vector is indexed by the Selector ID (-1). NULL selector
527   /// entries indicate that the particular selector ID has not yet
528   /// been loaded.
529   llvm::SmallVector<Selector, 16> SelectorsLoaded;
530
531   /// \brief The macro definitions we have already loaded.
532   llvm::SmallVector<MacroDefinition *, 16> MacroDefinitionsLoaded;
533
534   /// \brief Mapping from identifiers that represent macros whose definitions
535   /// have not yet been deserialized to the global offset where the macro
536   /// record resides.
537   llvm::DenseMap<IdentifierInfo *, uint64_t> UnreadMacroRecordOffsets;
538       
539   /// \name CodeGen-relevant special data
540   /// \brief Fields containing data that is relevant to CodeGen.
541   //@{
542
543   /// \brief The IDs of all declarations that fulfill the criteria of
544   /// "interesting" decls.
545   ///
546   /// This contains the data loaded from all EXTERNAL_DEFINITIONS blocks in the
547   /// chain. The referenced declarations are deserialized and passed to the
548   /// consumer eagerly.
549   llvm::SmallVector<uint64_t, 16> ExternalDefinitions;
550
551   /// \brief The IDs of all tentative definitions stored in the the chain.
552   ///
553   /// Sema keeps track of all tentative definitions in a TU because it has to
554   /// complete them and pass them on to CodeGen. Thus, tentative definitions in
555   /// the PCH chain must be eagerly deserialized.
556   llvm::SmallVector<uint64_t, 16> TentativeDefinitions;
557
558   /// \brief The IDs of all CXXRecordDecls stored in the chain whose VTables are
559   /// used.
560   ///
561   /// CodeGen has to emit VTables for these records, so they have to be eagerly
562   /// deserialized.
563   llvm::SmallVector<uint64_t, 64> VTableUses;
564
565   //@}
566
567   /// \name Diagnostic-relevant special data
568   /// \brief Fields containing data that is used for generating diagnostics
569   //@{
570
571   /// \brief A snapshot of Sema's unused file-scoped variable tracking, for
572   /// generating warnings.
573   llvm::SmallVector<uint64_t, 16> UnusedFileScopedDecls;
574
575   /// \brief A list of all the delegating constructors we've seen, to diagnose
576   /// cycles.
577   llvm::SmallVector<uint64_t, 4> DelegatingCtorDecls;
578
579   /// \brief A snapshot of Sema's weak undeclared identifier tracking, for
580   /// generating warnings.
581   llvm::SmallVector<uint64_t, 64> WeakUndeclaredIdentifiers;
582
583   /// \brief The IDs of type aliases for ext_vectors that exist in the chain.
584   ///
585   /// Used by Sema for finding sugared names for ext_vectors in diagnostics.
586   llvm::SmallVector<uint64_t, 4> ExtVectorDecls;
587
588   //@}
589
590   /// \name Sema-relevant special data
591   /// \brief Fields containing data that is used for semantic analysis
592   //@{
593
594   /// \brief The IDs of all locally scoped external decls in the chain.
595   ///
596   /// Sema tracks these to validate that the types are consistent across all
597   /// local external declarations.
598   llvm::SmallVector<uint64_t, 16> LocallyScopedExternalDecls;
599
600   /// \brief The IDs of all dynamic class declarations in the chain.
601   ///
602   /// Sema tracks these because it checks for the key functions being defined
603   /// at the end of the TU, in which case it directs CodeGen to emit the VTable.
604   llvm::SmallVector<uint64_t, 16> DynamicClasses;
605
606   /// \brief The IDs of the declarations Sema stores directly.
607   ///
608   /// Sema tracks a few important decls, such as namespace std, directly.
609   llvm::SmallVector<uint64_t, 4> SemaDeclRefs;
610
611   /// \brief The IDs of the types ASTContext stores directly.
612   ///
613   /// The AST context tracks a few important types, such as va_list, directly.
614   llvm::SmallVector<uint64_t, 16> SpecialTypes;
615
616   /// \brief The IDs of CUDA-specific declarations ASTContext stores directly.
617   ///
618   /// The AST context tracks a few important decls, currently cudaConfigureCall,
619   /// directly.
620   llvm::SmallVector<uint64_t, 2> CUDASpecialDeclRefs;
621
622   /// \brief The floating point pragma option settings.
623   llvm::SmallVector<uint64_t, 1> FPPragmaOptions;
624
625   /// \brief The OpenCL extension settings.
626   llvm::SmallVector<uint64_t, 1> OpenCLExtensions;
627
628   /// \brief A list of the namespaces we've seen.
629   llvm::SmallVector<uint64_t, 4> KnownNamespaces;
630
631   //@}
632
633   /// \brief Diagnostic IDs and their mappings that the user changed.
634   llvm::SmallVector<uint64_t, 8> PragmaDiagMappings;
635
636   /// \brief The original file name that was used to build the primary AST file,
637   /// which may have been modified for relocatable-pch support.
638   std::string OriginalFileName;
639
640   /// \brief The actual original file name that was used to build the primary
641   /// AST file.
642   std::string ActualOriginalFileName;
643
644   /// \brief The file ID for the original file that was used to build the
645   /// primary AST file.
646   FileID OriginalFileID;
647   
648   /// \brief The directory that the PCH was originally created in. Used to
649   /// allow resolving headers even after headers+PCH was moved to a new path.
650   std::string OriginalDir;
651
652   /// \brief The directory that the PCH we are reading is stored in.
653   std::string CurrentDir;
654
655   /// \brief Whether this precompiled header is a relocatable PCH file.
656   bool RelocatablePCH;
657
658   /// \brief The system include root to be used when loading the
659   /// precompiled header.
660   const char *isysroot;
661
662   /// \brief Whether to disable the normal validation performed on precompiled
663   /// headers when they are loaded.
664   bool DisableValidation;
665       
666   /// \brief Whether to disable the use of stat caches in AST files.
667   bool DisableStatCache;
668
669   /// \brief Mapping from switch-case IDs in the chain to switch-case statements
670   ///
671   /// Statements usually don't have IDs, but switch cases need them, so that the
672   /// switch statement can refer to them.
673   std::map<unsigned, SwitchCase *> SwitchCaseStmts;
674
675   /// \brief Mapping from opaque value IDs to OpaqueValueExprs.
676   std::map<unsigned, OpaqueValueExpr*> OpaqueValueExprs;
677
678   /// \brief The number of stat() calls that hit/missed the stat
679   /// cache.
680   unsigned NumStatHits, NumStatMisses;
681
682   /// \brief The number of source location entries de-serialized from
683   /// the PCH file.
684   unsigned NumSLocEntriesRead;
685
686   /// \brief The number of source location entries in the chain.
687   unsigned TotalNumSLocEntries;
688
689   /// \brief The next offset for a SLocEntry after everything in this reader.
690   unsigned NextSLocOffset;
691
692   /// \brief The number of statements (and expressions) de-serialized
693   /// from the chain.
694   unsigned NumStatementsRead;
695
696   /// \brief The total number of statements (and expressions) stored
697   /// in the chain.
698   unsigned TotalNumStatements;
699
700   /// \brief The number of macros de-serialized from the chain.
701   unsigned NumMacrosRead;
702
703   /// \brief The total number of macros stored in the chain.
704   unsigned TotalNumMacros;
705
706   /// \brief The number of selectors that have been read.
707   unsigned NumSelectorsRead;
708
709   /// \brief The number of method pool entries that have been read.
710   unsigned NumMethodPoolEntriesRead;
711
712   /// \brief The number of times we have looked up a selector in the method
713   /// pool and not found anything interesting.
714   unsigned NumMethodPoolMisses;
715
716   /// \brief The total number of method pool entries in the selector table.
717   unsigned TotalNumMethodPoolEntries;
718
719   /// Number of lexical decl contexts read/total.
720   unsigned NumLexicalDeclContextsRead, TotalLexicalDeclContexts;
721
722   /// Number of visible decl contexts read/total.
723   unsigned NumVisibleDeclContextsRead, TotalVisibleDeclContexts;
724   
725   /// \brief Number of Decl/types that are currently deserializing.
726   unsigned NumCurrentElementsDeserializing;
727
728   /// \brief An IdentifierInfo that has been loaded but whose top-level
729   /// declarations of the same name have not (yet) been loaded.
730   struct PendingIdentifierInfo {
731     IdentifierInfo *II;
732     llvm::SmallVector<uint32_t, 4> DeclIDs;
733   };
734
735   /// \brief The set of identifiers that were read while the AST reader was
736   /// (recursively) loading declarations.
737   ///
738   /// The declarations on the identifier chain for these identifiers will be
739   /// loaded once the recursive loading has completed.
740   std::deque<PendingIdentifierInfo> PendingIdentifierInfos;
741
742   /// \brief Contains declarations and definitions that will be
743   /// "interesting" to the ASTConsumer, when we get that AST consumer.
744   ///
745   /// "Interesting" declarations are those that have data that may
746   /// need to be emitted, such as inline function definitions or
747   /// Objective-C protocols.
748   std::deque<Decl *> InterestingDecls;
749
750   /// \brief We delay loading of the previous declaration chain to avoid
751   /// deeply nested calls when there are many redeclarations.
752   std::deque<std::pair<Decl *, serialization::DeclID> > PendingPreviousDecls;
753
754   /// \brief Ready to load the previous declaration of the given Decl.
755   void loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID);
756
757   /// \brief When reading a Stmt tree, Stmt operands are placed in this stack.
758   llvm::SmallVector<Stmt *, 16> StmtStack;
759
760   /// \brief What kind of records we are reading.
761   enum ReadingKind {
762     Read_Decl, Read_Type, Read_Stmt
763   };
764
765   /// \brief What kind of records we are reading. 
766   ReadingKind ReadingKind;
767
768   /// \brief RAII object to change the reading kind.
769   class ReadingKindTracker {
770     ASTReader &Reader;
771     enum ReadingKind PrevKind;
772
773     ReadingKindTracker(const ReadingKindTracker&); // do not implement
774     ReadingKindTracker &operator=(const ReadingKindTracker&);// do not implement
775
776   public:
777     ReadingKindTracker(enum ReadingKind newKind, ASTReader &reader)
778       : Reader(reader), PrevKind(Reader.ReadingKind) {
779       Reader.ReadingKind = newKind;
780     }
781
782     ~ReadingKindTracker() { Reader.ReadingKind = PrevKind; }
783   };
784
785   /// \brief All predefines buffers in the chain, to be treated as if
786   /// concatenated.
787   PCHPredefinesBlocks PCHPredefinesBuffers;
788
789   /// \brief Suggested contents of the predefines buffer, after this
790   /// PCH file has been processed.
791   ///
792   /// In most cases, this string will be empty, because the predefines
793   /// buffer computed to build the PCH file will be identical to the
794   /// predefines buffer computed from the command line. However, when
795   /// there are differences that the PCH reader can work around, this
796   /// predefines buffer may contain additional definitions.
797   std::string SuggestedPredefines;
798
799   /// \brief Reads a statement from the specified cursor.
800   Stmt *ReadStmtFromStream(PerFileData &F);
801
802   /// \brief Get a FileEntry out of stored-in-PCH filename, making sure we take
803   /// into account all the necessary relocations.
804   const FileEntry *getFileEntry(llvm::StringRef filename);
805
806   void MaybeAddSystemRootToFilename(std::string &Filename);
807
808   ASTReadResult ReadASTCore(llvm::StringRef FileName, ASTFileType Type);
809   ASTReadResult ReadASTBlock(PerFileData &F);
810   bool CheckPredefinesBuffers();
811   bool ParseLineTable(PerFileData &F, llvm::SmallVectorImpl<uint64_t> &Record);
812   ASTReadResult ReadSourceManagerBlock(PerFileData &F);
813   ASTReadResult ReadSLocEntryRecord(unsigned ID);
814   PerFileData *SLocCursorForID(unsigned ID);
815   SourceLocation getImportLocation(PerFileData *F);
816   bool ParseLanguageOptions(const llvm::SmallVectorImpl<uint64_t> &Record);
817
818   struct RecordLocation {
819     RecordLocation(PerFileData *M, uint64_t O)
820       : F(M), Offset(O) {}
821     PerFileData *F;
822     uint64_t Offset;
823   };
824
825   QualType ReadTypeRecord(unsigned Index);
826   RecordLocation TypeCursorForIndex(unsigned Index);
827   void LoadedDecl(unsigned Index, Decl *D);
828   Decl *ReadDeclRecord(unsigned Index, serialization::DeclID ID);
829   RecordLocation DeclCursorForIndex(unsigned Index, serialization::DeclID ID);
830
831   void PassInterestingDeclsToConsumer();
832
833   /// \brief Produce an error diagnostic and return true.
834   ///
835   /// This routine should only be used for fatal errors that have to
836   /// do with non-routine failures (e.g., corrupted AST file).
837   void Error(llvm::StringRef Msg);
838   void Error(unsigned DiagID, llvm::StringRef Arg1 = llvm::StringRef(),
839              llvm::StringRef Arg2 = llvm::StringRef());
840
841   ASTReader(const ASTReader&); // do not implement
842   ASTReader &operator=(const ASTReader &); // do not implement
843 public:
844   typedef llvm::SmallVector<uint64_t, 64> RecordData;
845
846   /// \brief Load the AST file and validate its contents against the given
847   /// Preprocessor.
848   ///
849   /// \param PP the preprocessor associated with the context in which this
850   /// precompiled header will be loaded.
851   ///
852   /// \param Context the AST context that this precompiled header will be
853   /// loaded into.
854   ///
855   /// \param isysroot If non-NULL, the system include path specified by the
856   /// user. This is only used with relocatable PCH files. If non-NULL,
857   /// a relocatable PCH file will use the default path "/".
858   ///
859   /// \param DisableValidation If true, the AST reader will suppress most
860   /// of its regular consistency checking, allowing the use of precompiled
861   /// headers that cannot be determined to be compatible.
862   ///
863   /// \param DisableStatCache If true, the AST reader will ignore the
864   /// stat cache in the AST files. This performance pessimization can
865   /// help when an AST file is being used in cases where the
866   /// underlying files in the file system may have changed, but
867   /// parsing should still continue.
868   ASTReader(Preprocessor &PP, ASTContext *Context, const char *isysroot = 0,
869             bool DisableValidation = false, bool DisableStatCache = false);
870
871   /// \brief Load the AST file without using any pre-initialized Preprocessor.
872   ///
873   /// The necessary information to initialize a Preprocessor later can be
874   /// obtained by setting a ASTReaderListener.
875   ///
876   /// \param SourceMgr the source manager into which the AST file will be loaded
877   ///
878   /// \param FileMgr the file manager into which the AST file will be loaded.
879   ///
880   /// \param Diags the diagnostics system to use for reporting errors and
881   /// warnings relevant to loading the AST file.
882   ///
883   /// \param isysroot If non-NULL, the system include path specified by the
884   /// user. This is only used with relocatable PCH files. If non-NULL,
885   /// a relocatable PCH file will use the default path "/".
886   ///
887   /// \param DisableValidation If true, the AST reader will suppress most
888   /// of its regular consistency checking, allowing the use of precompiled
889   /// headers that cannot be determined to be compatible.
890   ///
891   /// \param DisableStatCache If true, the AST reader will ignore the
892   /// stat cache in the AST files. This performance pessimization can
893   /// help when an AST file is being used in cases where the
894   /// underlying files in the file system may have changed, but
895   /// parsing should still continue.
896   ASTReader(SourceManager &SourceMgr, FileManager &FileMgr,
897             Diagnostic &Diags, const char *isysroot = 0,
898             bool DisableValidation = false, bool DisableStatCache = false);
899   ~ASTReader();
900
901   /// \brief Load the precompiled header designated by the given file
902   /// name.
903   ASTReadResult ReadAST(const std::string &FileName, ASTFileType Type);
904
905   /// \brief Checks that no file that is stored in PCH is out-of-sync with
906   /// the actual file in the file system.
907   ASTReadResult validateFileEntries();
908
909   /// \brief Set the AST callbacks listener.
910   void setListener(ASTReaderListener *listener) {
911     Listener.reset(listener);
912   }
913
914   /// \brief Set the AST deserialization listener.
915   void setDeserializationListener(ASTDeserializationListener *Listener);
916
917   /// \brief Set the Preprocessor to use.
918   void setPreprocessor(Preprocessor &pp);
919
920   /// \brief Sets and initializes the given Context.
921   void InitializeContext(ASTContext &Context);
922
923   /// \brief Set AST buffers for chained PCHs created and stored in memory.
924   /// First (not depending on another) PCH in chain is first in array.
925   void setASTMemoryBuffers(llvm::MemoryBuffer **bufs, unsigned numBufs) {
926     ASTBuffers.clear();
927     ASTBuffers.insert(ASTBuffers.begin(), bufs, bufs + numBufs);
928   }
929
930   /// \brief Retrieve the name of the named (primary) AST file
931   const std::string &getFileName() const { return Chain[0]->FileName; }
932
933   /// \brief Retrieve the name of the original source file name
934   const std::string &getOriginalSourceFile() { return OriginalFileName; }
935
936   /// \brief Retrieve the name of the original source file name directly from
937   /// the AST file, without actually loading the AST file.
938   static std::string getOriginalSourceFile(const std::string &ASTFileName,
939                                            FileManager &FileMgr,
940                                            Diagnostic &Diags);
941
942   /// \brief Returns the suggested contents of the predefines buffer,
943   /// which contains a (typically-empty) subset of the predefines
944   /// build prior to including the precompiled header.
945   const std::string &getSuggestedPredefines() { return SuggestedPredefines; }
946       
947   /// \brief Read preprocessed entities into the preprocessing record.
948   virtual void ReadPreprocessedEntities();
949
950   /// \brief Read the preprocessed entity at the given offset.
951   virtual PreprocessedEntity *ReadPreprocessedEntityAtOffset(uint64_t Offset);
952
953   /// \brief Read the header file information for the given file entry.
954   virtual HeaderFileInfo GetHeaderFileInfo(const FileEntry *FE);
955
956   void ReadPragmaDiagnosticMappings(Diagnostic &Diag);
957
958   /// \brief Returns the number of source locations found in the chain.
959   unsigned getTotalNumSLocs() const {
960     return TotalNumSLocEntries;
961   }
962
963   /// \brief Returns the next SLocEntry offset after the chain.
964   unsigned getNextSLocOffset() const {
965     return NextSLocOffset;
966   }
967
968   /// \brief Returns the number of identifiers found in the chain.
969   unsigned getTotalNumIdentifiers() const {
970     return static_cast<unsigned>(IdentifiersLoaded.size());
971   }
972
973   /// \brief Returns the number of types found in the chain.
974   unsigned getTotalNumTypes() const {
975     return static_cast<unsigned>(TypesLoaded.size());
976   }
977
978   /// \brief Returns the number of declarations found in the chain.
979   unsigned getTotalNumDecls() const {
980     return static_cast<unsigned>(DeclsLoaded.size());
981   }
982
983   /// \brief Returns the number of selectors found in the chain.
984   unsigned getTotalNumSelectors() const {
985     return static_cast<unsigned>(SelectorsLoaded.size());
986   }
987
988   /// \brief Returns the number of macro definitions found in the chain.
989   unsigned getTotalNumMacroDefinitions() const {
990     return static_cast<unsigned>(MacroDefinitionsLoaded.size());
991   }
992       
993   /// \brief Returns the number of C++ base specifiers found in the chain.
994   unsigned getTotalNumCXXBaseSpecifiers() const;
995       
996   /// \brief Reads a TemplateArgumentLocInfo appropriate for the
997   /// given TemplateArgument kind.
998   TemplateArgumentLocInfo
999   GetTemplateArgumentLocInfo(PerFileData &F, TemplateArgument::ArgKind Kind,
1000                              const RecordData &Record, unsigned &Idx);
1001
1002   /// \brief Reads a TemplateArgumentLoc.
1003   TemplateArgumentLoc
1004   ReadTemplateArgumentLoc(PerFileData &F,
1005                           const RecordData &Record, unsigned &Idx);
1006
1007   /// \brief Reads a declarator info from the given record.
1008   TypeSourceInfo *GetTypeSourceInfo(PerFileData &F,
1009                                     const RecordData &Record, unsigned &Idx);
1010
1011   /// \brief Resolve and return the translation unit declaration.
1012   TranslationUnitDecl *GetTranslationUnitDecl();
1013
1014   /// \brief Resolve a type ID into a type, potentially building a new
1015   /// type.
1016   QualType GetType(serialization::TypeID ID);
1017
1018   /// \brief Returns the type ID associated with the given type.
1019   /// If the type didn't come from the AST file the ID that is returned is
1020   /// marked as "doesn't exist in AST".
1021   serialization::TypeID GetTypeID(QualType T) const;
1022
1023   /// \brief Returns the type index associated with the given type.
1024   /// If the type didn't come from the AST file the index that is returned is
1025   /// marked as "doesn't exist in AST".
1026   serialization::TypeIdx GetTypeIdx(QualType T) const;
1027
1028   /// \brief Resolve a declaration ID into a declaration, potentially
1029   /// building a new declaration.
1030   Decl *GetDecl(serialization::DeclID ID);
1031   virtual Decl *GetExternalDecl(uint32_t ID);
1032
1033   /// \brief Resolve a CXXBaseSpecifiers ID into an offset into the chain
1034   /// of loaded AST files.
1035   uint64_t GetCXXBaseSpecifiersOffset(serialization::CXXBaseSpecifiersID ID);
1036       
1037   virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
1038       
1039   /// \brief Resolve the offset of a statement into a statement.
1040   ///
1041   /// This operation will read a new statement from the external
1042   /// source each time it is called, and is meant to be used via a
1043   /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
1044   virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
1045
1046   /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
1047   /// specified cursor.  Read the abbreviations that are at the top of the block
1048   /// and then leave the cursor pointing into the block.
1049   bool ReadBlockAbbrevs(llvm::BitstreamCursor &Cursor, unsigned BlockID);
1050
1051   /// \brief Finds all the visible declarations with a given name.
1052   /// The current implementation of this method just loads the entire
1053   /// lookup table as unmaterialized references.
1054   virtual DeclContext::lookup_result
1055   FindExternalVisibleDeclsByName(const DeclContext *DC,
1056                                  DeclarationName Name);
1057
1058   virtual void MaterializeVisibleDecls(const DeclContext *DC);
1059
1060   /// \brief Read all of the declarations lexically stored in a
1061   /// declaration context.
1062   ///
1063   /// \param DC The declaration context whose declarations will be
1064   /// read.
1065   ///
1066   /// \param Decls Vector that will contain the declarations loaded
1067   /// from the external source. The caller is responsible for merging
1068   /// these declarations with any declarations already stored in the
1069   /// declaration context.
1070   ///
1071   /// \returns true if there was an error while reading the
1072   /// declarations for this declaration context.
1073   virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
1074                                         bool (*isKindWeWant)(Decl::Kind),
1075                                         llvm::SmallVectorImpl<Decl*> &Decls);
1076
1077   /// \brief Notify ASTReader that we started deserialization of
1078   /// a decl or type so until FinishedDeserializing is called there may be
1079   /// decls that are initializing. Must be paired with FinishedDeserializing.
1080   virtual void StartedDeserializing() { ++NumCurrentElementsDeserializing; }
1081
1082   /// \brief Notify ASTReader that we finished the deserialization of
1083   /// a decl or type. Must be paired with StartedDeserializing.
1084   virtual void FinishedDeserializing();
1085
1086   /// \brief Function that will be invoked when we begin parsing a new
1087   /// translation unit involving this external AST source.
1088   ///
1089   /// This function will provide all of the external definitions to
1090   /// the ASTConsumer.
1091   virtual void StartTranslationUnit(ASTConsumer *Consumer);
1092
1093   /// \brief Print some statistics about AST usage.
1094   virtual void PrintStats();
1095
1096   /// Return the amount of memory used by memory buffers, breaking down
1097   /// by heap-backed versus mmap'ed memory.
1098   virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
1099
1100   /// \brief Initialize the semantic source with the Sema instance
1101   /// being used to perform semantic analysis on the abstract syntax
1102   /// tree.
1103   virtual void InitializeSema(Sema &S);
1104
1105   /// \brief Inform the semantic consumer that Sema is no longer available.
1106   virtual void ForgetSema() { SemaObj = 0; }
1107
1108   /// \brief Retrieve the IdentifierInfo for the named identifier.
1109   ///
1110   /// This routine builds a new IdentifierInfo for the given identifier. If any
1111   /// declarations with this name are visible from translation unit scope, their
1112   /// declarations will be deserialized and introduced into the declaration
1113   /// chain of the identifier.
1114   virtual IdentifierInfo *get(const char *NameStart, const char *NameEnd);
1115   IdentifierInfo *get(llvm::StringRef Name) {
1116     return get(Name.begin(), Name.end());
1117   }
1118
1119   /// \brief Retrieve an iterator into the set of all identifiers
1120   /// in all loaded AST files.
1121   virtual IdentifierIterator *getIdentifiers() const;
1122
1123   /// \brief Load the contents of the global method pool for a given
1124   /// selector.
1125   ///
1126   /// \returns a pair of Objective-C methods lists containing the
1127   /// instance and factory methods, respectively, with this selector.
1128   virtual std::pair<ObjCMethodList, ObjCMethodList>
1129     ReadMethodPool(Selector Sel);
1130
1131   /// \brief Load the set of namespaces that are known to the external source,
1132   /// which will be used during typo correction.
1133   virtual void ReadKnownNamespaces(
1134                            llvm::SmallVectorImpl<NamespaceDecl *> &Namespaces);
1135
1136   /// \brief Load a selector from disk, registering its ID if it exists.
1137   void LoadSelector(Selector Sel);
1138
1139   void SetIdentifierInfo(unsigned ID, IdentifierInfo *II);
1140   void SetGloballyVisibleDecls(IdentifierInfo *II,
1141                                const llvm::SmallVectorImpl<uint32_t> &DeclIDs,
1142                                bool Nonrecursive = false);
1143
1144   /// \brief Report a diagnostic.
1145   DiagnosticBuilder Diag(unsigned DiagID);
1146
1147   /// \brief Report a diagnostic.
1148   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
1149
1150   IdentifierInfo *DecodeIdentifierInfo(unsigned Idx);
1151
1152   IdentifierInfo *GetIdentifierInfo(const RecordData &Record, unsigned &Idx) {
1153     return DecodeIdentifierInfo(Record[Idx++]);
1154   }
1155
1156   virtual IdentifierInfo *GetIdentifier(unsigned ID) {
1157     return DecodeIdentifierInfo(ID);
1158   }
1159
1160   /// \brief Read the source location entry with index ID.
1161   virtual bool ReadSLocEntry(unsigned ID);
1162
1163   Selector DecodeSelector(unsigned Idx);
1164
1165   virtual Selector GetExternalSelector(uint32_t ID);
1166   uint32_t GetNumExternalSelectors();
1167
1168   Selector GetSelector(const RecordData &Record, unsigned &Idx) {
1169     return DecodeSelector(Record[Idx++]);
1170   }
1171
1172   /// \brief Read a declaration name.
1173   DeclarationName ReadDeclarationName(const RecordData &Record, unsigned &Idx);
1174   void ReadDeclarationNameLoc(PerFileData &F,
1175                               DeclarationNameLoc &DNLoc, DeclarationName Name,
1176                               const RecordData &Record, unsigned &Idx);
1177   void ReadDeclarationNameInfo(PerFileData &F, DeclarationNameInfo &NameInfo,
1178                                const RecordData &Record, unsigned &Idx);
1179
1180   void ReadQualifierInfo(PerFileData &F, QualifierInfo &Info,
1181                          const RecordData &Record, unsigned &Idx);
1182
1183   NestedNameSpecifier *ReadNestedNameSpecifier(const RecordData &Record,
1184                                                unsigned &Idx);
1185
1186   NestedNameSpecifierLoc ReadNestedNameSpecifierLoc(PerFileData &F, 
1187                                                     const RecordData &Record,
1188                                                     unsigned &Idx);
1189
1190   /// \brief Read a template name.
1191   TemplateName ReadTemplateName(PerFileData &F, const RecordData &Record, 
1192                                 unsigned &Idx);
1193
1194   /// \brief Read a template argument.
1195   TemplateArgument ReadTemplateArgument(PerFileData &F,
1196                                         const RecordData &Record,unsigned &Idx);
1197   
1198   /// \brief Read a template parameter list.
1199   TemplateParameterList *ReadTemplateParameterList(PerFileData &F,
1200                                                    const RecordData &Record,
1201                                                    unsigned &Idx);
1202   
1203   /// \brief Read a template argument array.
1204   void
1205   ReadTemplateArgumentList(llvm::SmallVector<TemplateArgument, 8> &TemplArgs,
1206                            PerFileData &F, const RecordData &Record,
1207                            unsigned &Idx);
1208
1209   /// \brief Read a UnresolvedSet structure.
1210   void ReadUnresolvedSet(UnresolvedSetImpl &Set,
1211                          const RecordData &Record, unsigned &Idx);
1212
1213   /// \brief Read a C++ base specifier.
1214   CXXBaseSpecifier ReadCXXBaseSpecifier(PerFileData &F,
1215                                         const RecordData &Record,unsigned &Idx);
1216
1217   /// \brief Read a CXXCtorInitializer array.
1218   std::pair<CXXCtorInitializer **, unsigned>
1219   ReadCXXCtorInitializers(PerFileData &F, const RecordData &Record,
1220                           unsigned &Idx);
1221
1222   /// \brief Read a source location from raw form.
1223   SourceLocation ReadSourceLocation(PerFileData &Module, unsigned Raw) {
1224     (void)Module; // No remapping yet
1225     return SourceLocation::getFromRawEncoding(Raw);
1226   }
1227
1228   /// \brief Read a source location.
1229   SourceLocation ReadSourceLocation(PerFileData &Module,
1230                                     const RecordData &Record, unsigned& Idx) {
1231     return ReadSourceLocation(Module, Record[Idx++]);
1232   }
1233
1234   /// \brief Read a source range.
1235   SourceRange ReadSourceRange(PerFileData &F,
1236                               const RecordData &Record, unsigned& Idx);
1237
1238   /// \brief Read an integral value
1239   llvm::APInt ReadAPInt(const RecordData &Record, unsigned &Idx);
1240
1241   /// \brief Read a signed integral value
1242   llvm::APSInt ReadAPSInt(const RecordData &Record, unsigned &Idx);
1243
1244   /// \brief Read a floating-point value
1245   llvm::APFloat ReadAPFloat(const RecordData &Record, unsigned &Idx);
1246
1247   // \brief Read a string
1248   std::string ReadString(const RecordData &Record, unsigned &Idx);
1249
1250   /// \brief Read a version tuple.
1251   VersionTuple ReadVersionTuple(const RecordData &Record, unsigned &Idx);
1252
1253   CXXTemporary *ReadCXXTemporary(const RecordData &Record, unsigned &Idx);
1254       
1255   /// \brief Reads attributes from the current stream position.
1256   void ReadAttributes(PerFileData &F, AttrVec &Attrs,
1257                       const RecordData &Record, unsigned &Idx);
1258
1259   /// \brief Reads a statement.
1260   Stmt *ReadStmt(PerFileData &F);
1261
1262   /// \brief Reads an expression.
1263   Expr *ReadExpr(PerFileData &F);
1264
1265   /// \brief Reads a sub-statement operand during statement reading.
1266   Stmt *ReadSubStmt() {
1267     assert(ReadingKind == Read_Stmt &&
1268            "Should be called only during statement reading!");
1269     // Subexpressions are stored from last to first, so the next Stmt we need
1270     // is at the back of the stack.
1271     assert(!StmtStack.empty() && "Read too many sub statements!");
1272     return StmtStack.pop_back_val();
1273   }
1274
1275   /// \brief Reads a sub-expression operand during statement reading.
1276   Expr *ReadSubExpr();
1277
1278   /// \brief Reads the macro record located at the given offset.
1279   PreprocessedEntity *ReadMacroRecord(PerFileData &F, uint64_t Offset);
1280
1281   /// \brief Reads the preprocessed entity located at the current stream
1282   /// position.
1283   PreprocessedEntity *LoadPreprocessedEntity(PerFileData &F);
1284       
1285   /// \brief Note that the identifier is a macro whose record will be loaded
1286   /// from the given AST file at the given (file-local) offset.
1287   void SetIdentifierIsMacro(IdentifierInfo *II, PerFileData &F,
1288                             uint64_t Offset);
1289       
1290   /// \brief Read the set of macros defined by this external macro source.
1291   virtual void ReadDefinedMacros();
1292
1293   /// \brief Read the macro definition for this identifier.
1294   virtual void LoadMacroDefinition(IdentifierInfo *II);
1295
1296   /// \brief Read the macro definition corresponding to this iterator
1297   /// into the unread macro record offsets table.
1298   void LoadMacroDefinition(
1299                      llvm::DenseMap<IdentifierInfo *, uint64_t>::iterator Pos);
1300       
1301   /// \brief Retrieve the macro definition with the given ID.
1302   MacroDefinition *getMacroDefinition(serialization::MacroID ID);
1303
1304   /// \brief Retrieve the AST context that this AST reader supplements.
1305   ASTContext *getContext() { return Context; }
1306
1307   // \brief Contains declarations that were loaded before we have
1308   // access to a Sema object.
1309   llvm::SmallVector<NamedDecl *, 16> PreloadedDecls;
1310
1311   /// \brief Retrieve the semantic analysis object used to analyze the
1312   /// translation unit in which the precompiled header is being
1313   /// imported.
1314   Sema *getSema() { return SemaObj; }
1315
1316   /// \brief Retrieve the identifier table associated with the
1317   /// preprocessor.
1318   IdentifierTable &getIdentifierTable();
1319
1320   /// \brief Record that the given ID maps to the given switch-case
1321   /// statement.
1322   void RecordSwitchCaseID(SwitchCase *SC, unsigned ID);
1323
1324   /// \brief Retrieve the switch-case statement with the given ID.
1325   SwitchCase *getSwitchCaseWithID(unsigned ID);
1326
1327   void ClearSwitchCaseIDs();
1328 };
1329
1330 /// \brief Helper class that saves the current stream position and
1331 /// then restores it when destroyed.
1332 struct SavedStreamPosition {
1333   explicit SavedStreamPosition(llvm::BitstreamCursor &Cursor)
1334   : Cursor(Cursor), Offset(Cursor.GetCurrentBitNo()) { }
1335
1336   ~SavedStreamPosition() {
1337     Cursor.JumpToBit(Offset);
1338   }
1339
1340 private:
1341   llvm::BitstreamCursor &Cursor;
1342   uint64_t Offset;
1343 };
1344
1345 inline void PCHValidator::Error(const char *Msg) {
1346   Reader.Error(Msg);
1347 }
1348
1349 } // end namespace clang
1350
1351 #endif