• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- ASTWriter.h - AST File Writer --------------------------*- 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 ASTWriter class, which writes an AST file
11 //  containing a serialized representation of a translation unit.
12 //
13 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_AST_WRITER_H
15 #define LLVM_CLANG_FRONTEND_AST_WRITER_H
16 
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclarationName.h"
19 #include "clang/AST/TemplateBase.h"
20 #include "clang/AST/ASTMutationListener.h"
21 #include "clang/Serialization/ASTBitCodes.h"
22 #include "clang/Serialization/ASTDeserializationListener.h"
23 #include "clang/Sema/SemaConsumer.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/Bitcode/BitstreamWriter.h"
30 #include <map>
31 #include <queue>
32 #include <vector>
33 
34 namespace llvm {
35   class APFloat;
36   class APInt;
37   class BitstreamWriter;
38 }
39 
40 namespace clang {
41 
42 class ASTContext;
43 class NestedNameSpecifier;
44 class CXXBaseSpecifier;
45 class CXXCtorInitializer;
46 class FPOptions;
47 class HeaderSearch;
48 class IdentifierResolver;
49 class MacroDefinition;
50 class MemorizeStatCalls;
51 class OpaqueValueExpr;
52 class OpenCLOptions;
53 class ASTReader;
54 class Module;
55 class PreprocessedEntity;
56 class PreprocessingRecord;
57 class Preprocessor;
58 class Sema;
59 class SourceManager;
60 class SwitchCase;
61 class TargetInfo;
62 class VersionTuple;
63 
64 namespace SrcMgr { class SLocEntry; }
65 
66 /// \brief Writes an AST file containing the contents of a translation unit.
67 ///
68 /// The ASTWriter class produces a bitstream containing the serialized
69 /// representation of a given abstract syntax tree and its supporting
70 /// data structures. This bitstream can be de-serialized via an
71 /// instance of the ASTReader class.
72 class ASTWriter : public ASTDeserializationListener,
73                   public ASTMutationListener {
74 public:
75   typedef SmallVector<uint64_t, 64> RecordData;
76   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
77 
78   friend class ASTDeclWriter;
79   friend class ASTStmtWriter;
80 private:
81   /// \brief Map that provides the ID numbers of each type within the
82   /// output stream, plus those deserialized from a chained PCH.
83   ///
84   /// The ID numbers of types are consecutive (in order of discovery)
85   /// and start at 1. 0 is reserved for NULL. When types are actually
86   /// stored in the stream, the ID number is shifted by 2 bits to
87   /// allow for the const/volatile qualifiers.
88   ///
89   /// Keys in the map never have const/volatile qualifiers.
90   typedef llvm::DenseMap<QualType, serialization::TypeIdx,
91                          serialization::UnsafeQualTypeDenseMapInfo>
92     TypeIdxMap;
93 
94   /// \brief The bitstream writer used to emit this precompiled header.
95   llvm::BitstreamWriter &Stream;
96 
97   /// \brief The ASTContext we're writing.
98   ASTContext *Context;
99 
100   /// \brief The preprocessor we're writing.
101   Preprocessor *PP;
102 
103   /// \brief The reader of existing AST files, if we're chaining.
104   ASTReader *Chain;
105 
106   /// \brief The module we're currently writing, if any.
107   Module *WritingModule;
108 
109   /// \brief Indicates when the AST writing is actively performing
110   /// serialization, rather than just queueing updates.
111   bool WritingAST;
112 
113   /// \brief Indicates that the AST contained compiler errors.
114   bool ASTHasCompilerErrors;
115 
116   /// \brief Stores a declaration or a type to be written to the AST file.
117   class DeclOrType {
118   public:
DeclOrType(Decl * D)119     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
DeclOrType(QualType T)120     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
121 
isType()122     bool isType() const { return IsType; }
isDecl()123     bool isDecl() const { return !IsType; }
124 
getType()125     QualType getType() const {
126       assert(isType() && "Not a type!");
127       return QualType::getFromOpaquePtr(Stored);
128     }
129 
getDecl()130     Decl *getDecl() const {
131       assert(isDecl() && "Not a decl!");
132       return static_cast<Decl *>(Stored);
133     }
134 
135   private:
136     void *Stored;
137     bool IsType;
138   };
139 
140   /// \brief The declarations and types to emit.
141   std::queue<DeclOrType> DeclTypesToEmit;
142 
143   /// \brief The first ID number we can use for our own declarations.
144   serialization::DeclID FirstDeclID;
145 
146   /// \brief The decl ID that will be assigned to the next new decl.
147   serialization::DeclID NextDeclID;
148 
149   /// \brief Map that provides the ID numbers of each declaration within
150   /// the output stream, as well as those deserialized from a chained PCH.
151   ///
152   /// The ID numbers of declarations are consecutive (in order of
153   /// discovery) and start at 2. 1 is reserved for the translation
154   /// unit, while 0 is reserved for NULL.
155   llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
156 
157   /// \brief Offset of each declaration in the bitstream, indexed by
158   /// the declaration's ID.
159   std::vector<serialization::DeclOffset> DeclOffsets;
160 
161   /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
162   typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
163     LocDeclIDsTy;
164   struct DeclIDInFileInfo {
165     LocDeclIDsTy DeclIDs;
166     /// \brief Set when the DeclIDs vectors from all files are joined, this
167     /// indicates the index that this particular vector has in the global one.
168     unsigned FirstDeclIndex;
169   };
170   typedef llvm::DenseMap<const SrcMgr::SLocEntry *,
171                          DeclIDInFileInfo *> FileDeclIDsTy;
172 
173   /// \brief Map from file SLocEntries to info about the file-level declarations
174   /// that it contains.
175   FileDeclIDsTy FileDeclIDs;
176 
177   void associateDeclWithFile(const Decl *D, serialization::DeclID);
178 
179   /// \brief The first ID number we can use for our own types.
180   serialization::TypeID FirstTypeID;
181 
182   /// \brief The type ID that will be assigned to the next new type.
183   serialization::TypeID NextTypeID;
184 
185   /// \brief Map that provides the ID numbers of each type within the
186   /// output stream, plus those deserialized from a chained PCH.
187   ///
188   /// The ID numbers of types are consecutive (in order of discovery)
189   /// and start at 1. 0 is reserved for NULL. When types are actually
190   /// stored in the stream, the ID number is shifted by 2 bits to
191   /// allow for the const/volatile qualifiers.
192   ///
193   /// Keys in the map never have const/volatile qualifiers.
194   TypeIdxMap TypeIdxs;
195 
196   /// \brief Offset of each type in the bitstream, indexed by
197   /// the type's ID.
198   std::vector<uint32_t> TypeOffsets;
199 
200   /// \brief The first ID number we can use for our own identifiers.
201   serialization::IdentID FirstIdentID;
202 
203   /// \brief The identifier ID that will be assigned to the next new identifier.
204   serialization::IdentID NextIdentID;
205 
206   /// \brief Map that provides the ID numbers of each identifier in
207   /// the output stream.
208   ///
209   /// The ID numbers for identifiers are consecutive (in order of
210   /// discovery), starting at 1. An ID of zero refers to a NULL
211   /// IdentifierInfo.
212   llvm::DenseMap<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
213 
214   /// @name FlushStmt Caches
215   /// @{
216 
217   /// \brief Set of parent Stmts for the currently serializing sub stmt.
218   llvm::DenseSet<Stmt *> ParentStmts;
219 
220   /// \brief Offsets of sub stmts already serialized. The offset points
221   /// just after the stmt record.
222   llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
223 
224   /// @}
225 
226   /// \brief Offsets of each of the identifier IDs into the identifier
227   /// table.
228   std::vector<uint32_t> IdentifierOffsets;
229 
230   /// \brief The first ID number we can use for our own submodules.
231   serialization::SubmoduleID FirstSubmoduleID;
232 
233   /// \brief The submodule ID that will be assigned to the next new submodule.
234   serialization::SubmoduleID NextSubmoduleID;
235 
236   /// \brief The first ID number we can use for our own selectors.
237   serialization::SelectorID FirstSelectorID;
238 
239   /// \brief The selector ID that will be assigned to the next new selector.
240   serialization::SelectorID NextSelectorID;
241 
242   /// \brief Map that provides the ID numbers of each Selector.
243   llvm::DenseMap<Selector, serialization::SelectorID> SelectorIDs;
244 
245   /// \brief Offset of each selector within the method pool/selector
246   /// table, indexed by the Selector ID (-1).
247   std::vector<uint32_t> SelectorOffsets;
248 
249   /// \brief Offsets of each of the macro identifiers into the
250   /// bitstream.
251   ///
252   /// For each identifier that is associated with a macro, this map
253   /// provides the offset into the bitstream where that macro is
254   /// defined.
255   llvm::DenseMap<const IdentifierInfo *, uint64_t> MacroOffsets;
256 
257   /// \brief The set of identifiers that had macro definitions at some point.
258   std::vector<const IdentifierInfo *> DeserializedMacroNames;
259 
260   /// \brief Mapping from macro definitions (as they occur in the preprocessing
261   /// record) to the macro IDs.
262   llvm::DenseMap<const MacroDefinition *, serialization::PreprocessedEntityID>
263       MacroDefinitions;
264 
265   typedef SmallVector<uint64_t, 2> UpdateRecord;
266   typedef llvm::DenseMap<const Decl *, UpdateRecord> DeclUpdateMap;
267   /// \brief Mapping from declarations that came from a chained PCH to the
268   /// record containing modifications to them.
269   DeclUpdateMap DeclUpdates;
270 
271   typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
272   /// \brief Map of first declarations from a chained PCH that point to the
273   /// most recent declarations in another PCH.
274   FirstLatestDeclMap FirstLatestDecls;
275 
276   /// \brief Declarations encountered that might be external
277   /// definitions.
278   ///
279   /// We keep track of external definitions (as well as tentative
280   /// definitions) as we are emitting declarations to the AST
281   /// file. The AST file contains a separate record for these external
282   /// definitions, which are provided to the AST consumer by the AST
283   /// reader. This is behavior is required to properly cope with,
284   /// e.g., tentative variable definitions that occur within
285   /// headers. The declarations themselves are stored as declaration
286   /// IDs, since they will be written out to an EXTERNAL_DEFINITIONS
287   /// record.
288   SmallVector<uint64_t, 16> ExternalDefinitions;
289 
290   /// \brief DeclContexts that have received extensions since their serialized
291   /// form.
292   ///
293   /// For namespaces, when we're chaining and encountering a namespace, we check
294   /// if its primary namespace comes from the chain. If it does, we add the
295   /// primary to this set, so that we can write out lexical content updates for
296   /// it.
297   llvm::SmallPtrSet<const DeclContext *, 16> UpdatedDeclContexts;
298 
299   typedef llvm::SmallPtrSet<const Decl *, 16> DeclsToRewriteTy;
300   /// \brief Decls that will be replaced in the current dependent AST file.
301   DeclsToRewriteTy DeclsToRewrite;
302 
303   /// \brief The set of Objective-C class that have categories we
304   /// should serialize.
305   llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
306 
307   struct ReplacedDeclInfo {
308     serialization::DeclID ID;
309     uint64_t Offset;
310     unsigned Loc;
311 
ReplacedDeclInfoReplacedDeclInfo312     ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
ReplacedDeclInfoReplacedDeclInfo313     ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
314                      SourceLocation Loc)
315       : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
316   };
317 
318   /// \brief Decls that have been replaced in the current dependent AST file.
319   ///
320   /// When a decl changes fundamentally after being deserialized (this shouldn't
321   /// happen, but the ObjC AST nodes are designed this way), it will be
322   /// serialized again. In this case, it is registered here, so that the reader
323   /// knows to read the updated version.
324   SmallVector<ReplacedDeclInfo, 16> ReplacedDecls;
325 
326   /// \brief The set of declarations that may have redeclaration chains that
327   /// need to be serialized.
328   llvm::SetVector<Decl *, llvm::SmallVector<Decl *, 4>,
329                   llvm::SmallPtrSet<Decl *, 4> > Redeclarations;
330 
331   /// \brief Statements that we've encountered while serializing a
332   /// declaration or type.
333   SmallVector<Stmt *, 16> StmtsToEmit;
334 
335   /// \brief Statements collection to use for ASTWriter::AddStmt().
336   /// It will point to StmtsToEmit unless it is overriden.
337   SmallVector<Stmt *, 16> *CollectedStmts;
338 
339   /// \brief Mapping from SwitchCase statements to IDs.
340   std::map<SwitchCase *, unsigned> SwitchCaseIDs;
341 
342   /// \brief The number of statements written to the AST file.
343   unsigned NumStatements;
344 
345   /// \brief The number of macros written to the AST file.
346   unsigned NumMacros;
347 
348   /// \brief The number of lexical declcontexts written to the AST
349   /// file.
350   unsigned NumLexicalDeclContexts;
351 
352   /// \brief The number of visible declcontexts written to the AST
353   /// file.
354   unsigned NumVisibleDeclContexts;
355 
356   /// \brief The offset of each CXXBaseSpecifier set within the AST.
357   SmallVector<uint32_t, 4> CXXBaseSpecifiersOffsets;
358 
359   /// \brief The first ID number we can use for our own base specifiers.
360   serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
361 
362   /// \brief The base specifiers ID that will be assigned to the next new
363   /// set of C++ base specifiers.
364   serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
365 
366   /// \brief A set of C++ base specifiers that is queued to be written into the
367   /// AST file.
368   struct QueuedCXXBaseSpecifiers {
QueuedCXXBaseSpecifiersQueuedCXXBaseSpecifiers369     QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
370 
QueuedCXXBaseSpecifiersQueuedCXXBaseSpecifiers371     QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
372                             CXXBaseSpecifier const *Bases,
373                             CXXBaseSpecifier const *BasesEnd)
374       : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
375 
376     serialization::CXXBaseSpecifiersID ID;
377     CXXBaseSpecifier const * Bases;
378     CXXBaseSpecifier const * BasesEnd;
379   };
380 
381   /// \brief Queue of C++ base specifiers to be written to the AST file,
382   /// in the order they should be written.
383   SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite;
384 
385   /// \brief A mapping from each known submodule to its ID number, which will
386   /// be a positive integer.
387   llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
388 
389   /// \brief Retrieve or create a submodule ID for this module.
390   unsigned getSubmoduleID(Module *Mod);
391 
392   /// \brief Write the given subexpression to the bitstream.
393   void WriteSubStmt(Stmt *S,
394                     llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries,
395                     llvm::DenseSet<Stmt *> &ParentStmts);
396 
397   void WriteBlockInfoBlock();
398   void WriteMetadata(ASTContext &Context, StringRef isysroot,
399                      const std::string &OutputFile);
400   void WriteLanguageOptions(const LangOptions &LangOpts);
401   void WriteStatCache(MemorizeStatCalls &StatCalls);
402   void WriteSourceManagerBlock(SourceManager &SourceMgr,
403                                const Preprocessor &PP,
404                                StringRef isysroot);
405   void WritePreprocessor(const Preprocessor &PP, bool IsModule);
406   void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot);
407   void WritePreprocessorDetail(PreprocessingRecord &PPRec);
408   void WriteSubmodules(Module *WritingModule);
409 
410   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag);
411   void WriteCXXBaseSpecifiersOffsets();
412   void WriteType(QualType T);
413   uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
414   uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
415   void WriteTypeDeclOffsets();
416   void WriteFileDeclIDsMap();
417   void WriteSelectors(Sema &SemaRef);
418   void WriteReferencedSelectorsPool(Sema &SemaRef);
419   void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
420                             bool IsModule);
421   void WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record);
422   void ResolveDeclUpdatesBlocks();
423   void WriteDeclUpdatesBlocks();
424   void WriteDeclReplacementsBlock();
425   void WriteDeclContextVisibleUpdate(const DeclContext *DC);
426   void WriteFPPragmaOptions(const FPOptions &Opts);
427   void WriteOpenCLExtensions(Sema &SemaRef);
428   void WriteObjCCategories();
429   void WriteRedeclarations();
430   void WriteMergedDecls();
431 
432   unsigned DeclParmVarAbbrev;
433   unsigned DeclContextLexicalAbbrev;
434   unsigned DeclContextVisibleLookupAbbrev;
435   unsigned UpdateVisibleAbbrev;
436   unsigned DeclRefExprAbbrev;
437   unsigned CharacterLiteralAbbrev;
438   unsigned DeclRecordAbbrev;
439   unsigned IntegerLiteralAbbrev;
440   unsigned DeclTypedefAbbrev;
441   unsigned DeclVarAbbrev;
442   unsigned DeclFieldAbbrev;
443   unsigned DeclEnumAbbrev;
444   unsigned DeclObjCIvarAbbrev;
445 
446   void WriteDeclsBlockAbbrevs();
447   void WriteDecl(ASTContext &Context, Decl *D);
448 
449   void WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
450                     StringRef isysroot, const std::string &OutputFile,
451                     Module *WritingModule);
452 
453 public:
454   /// \brief Create a new precompiled header writer that outputs to
455   /// the given bitstream.
456   ASTWriter(llvm::BitstreamWriter &Stream);
457   ~ASTWriter();
458 
459   /// \brief Write a precompiled header for the given semantic analysis.
460   ///
461   /// \param SemaRef a reference to the semantic analysis object that processed
462   /// the AST to be written into the precompiled header.
463   ///
464   /// \param StatCalls the object that cached all of the stat() calls made while
465   /// searching for source files and headers.
466   ///
467   /// \param WritingModule The module that we are writing. If null, we are
468   /// writing a precompiled header.
469   ///
470   /// \param isysroot if non-empty, write a relocatable file whose headers
471   /// are relative to the given system root.
472   void WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
473                 const std::string &OutputFile,
474                 Module *WritingModule, StringRef isysroot,
475                 bool hasErrors = false);
476 
477   /// \brief Emit a source location.
478   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
479 
480   /// \brief Emit a source range.
481   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
482 
483   /// \brief Emit an integral value.
484   void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
485 
486   /// \brief Emit a signed integral value.
487   void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
488 
489   /// \brief Emit a floating-point value.
490   void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
491 
492   /// \brief Emit a reference to an identifier.
493   void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
494 
495   /// \brief Emit a Selector (which is a smart pointer reference).
496   void AddSelectorRef(Selector, RecordDataImpl &Record);
497 
498   /// \brief Emit a CXXTemporary.
499   void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
500 
501   /// \brief Emit a set of C++ base specifiers to the record.
502   void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
503                                CXXBaseSpecifier const *BasesEnd,
504                                RecordDataImpl &Record);
505 
506   /// \brief Get the unique number used to refer to the given selector.
507   serialization::SelectorID getSelectorRef(Selector Sel);
508 
509   /// \brief Get the unique number used to refer to the given identifier.
510   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
511 
512   /// \brief Retrieve the offset of the macro definition for the given
513   /// identifier.
514   ///
515   /// The identifier must refer to a macro.
getMacroOffset(const IdentifierInfo * II)516   uint64_t getMacroOffset(const IdentifierInfo *II) {
517     assert(MacroOffsets.find(II) != MacroOffsets.end() &&
518            "Identifier does not name a macro");
519     return MacroOffsets[II];
520   }
521 
522   /// \brief Emit a reference to a type.
523   void AddTypeRef(QualType T, RecordDataImpl &Record);
524 
525   /// \brief Force a type to be emitted and get its ID.
526   serialization::TypeID GetOrCreateTypeID(QualType T);
527 
528   /// \brief Determine the type ID of an already-emitted type.
529   serialization::TypeID getTypeID(QualType T) const;
530 
531   /// \brief Force a type to be emitted and get its index.
532   serialization::TypeIdx GetOrCreateTypeIdx( QualType T);
533 
534   /// \brief Determine the type index of an already-emitted type.
535   serialization::TypeIdx getTypeIdx(QualType T) const;
536 
537   /// \brief Emits a reference to a declarator info.
538   void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
539 
540   /// \brief Emits a type with source-location information.
541   void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
542 
543   /// \brief Emits a template argument location info.
544   void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
545                                   const TemplateArgumentLocInfo &Arg,
546                                   RecordDataImpl &Record);
547 
548   /// \brief Emits a template argument location.
549   void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
550                               RecordDataImpl &Record);
551 
552   /// \brief Emit a reference to a declaration.
553   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
554 
555 
556   /// \brief Force a declaration to be emitted and get its ID.
557   serialization::DeclID GetDeclRef(const Decl *D);
558 
559   /// \brief Determine the declaration ID of an already-emitted
560   /// declaration.
561   serialization::DeclID getDeclID(const Decl *D);
562 
563   /// \brief Emit a declaration name.
564   void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record);
565   void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
566                              DeclarationName Name, RecordDataImpl &Record);
567   void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
568                               RecordDataImpl &Record);
569 
570   void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
571 
572   /// \brief Emit a nested name specifier.
573   void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
574 
575   /// \brief Emit a nested name specifier with source-location information.
576   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
577                                  RecordDataImpl &Record);
578 
579   /// \brief Emit a template name.
580   void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
581 
582   /// \brief Emit a template argument.
583   void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
584 
585   /// \brief Emit a template parameter list.
586   void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
587                                 RecordDataImpl &Record);
588 
589   /// \brief Emit a template argument list.
590   void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
591                                 RecordDataImpl &Record);
592 
593   /// \brief Emit a UnresolvedSet structure.
594   void AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record);
595 
596   /// \brief Emit a C++ base specifier.
597   void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
598                            RecordDataImpl &Record);
599 
600   /// \brief Emit a CXXCtorInitializer array.
601   void AddCXXCtorInitializers(
602                              const CXXCtorInitializer * const *CtorInitializers,
603                              unsigned NumCtorInitializers,
604                              RecordDataImpl &Record);
605 
606   void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
607 
608   /// \brief Add a string to the given record.
609   void AddString(StringRef Str, RecordDataImpl &Record);
610 
611   /// \brief Add a version tuple to the given record
612   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
613 
614   /// \brief Mark a declaration context as needing an update.
AddUpdatedDeclContext(const DeclContext * DC)615   void AddUpdatedDeclContext(const DeclContext *DC) {
616     UpdatedDeclContexts.insert(DC);
617   }
618 
RewriteDecl(const Decl * D)619   void RewriteDecl(const Decl *D) {
620     DeclsToRewrite.insert(D);
621   }
622 
isRewritten(const Decl * D)623   bool isRewritten(const Decl *D) const {
624     return DeclsToRewrite.count(D);
625   }
626 
627   /// \brief Infer the submodule ID that contains an entity at the given
628   /// source location.
629   serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
630 
631   /// \brief Note that the identifier II occurs at the given offset
632   /// within the identifier table.
633   void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
634 
635   /// \brief Note that the selector Sel occurs at the given offset
636   /// within the method pool/selector table.
637   void SetSelectorOffset(Selector Sel, uint32_t Offset);
638 
639   /// \brief Add the given statement or expression to the queue of
640   /// statements to emit.
641   ///
642   /// This routine should be used when emitting types and declarations
643   /// that have expressions as part of their formulation. Once the
644   /// type or declaration has been written, call FlushStmts() to write
645   /// the corresponding statements just after the type or
646   /// declaration.
AddStmt(Stmt * S)647   void AddStmt(Stmt *S) {
648       CollectedStmts->push_back(S);
649   }
650 
651   /// \brief Flush all of the statements and expressions that have
652   /// been added to the queue via AddStmt().
653   void FlushStmts();
654 
655   /// \brief Flush all of the C++ base specifier sets that have been added
656   /// via \c AddCXXBaseSpecifiersRef().
657   void FlushCXXBaseSpecifiers();
658 
659   /// \brief Record an ID for the given switch-case statement.
660   unsigned RecordSwitchCaseID(SwitchCase *S);
661 
662   /// \brief Retrieve the ID for the given switch-case statement.
663   unsigned getSwitchCaseID(SwitchCase *S);
664 
665   void ClearSwitchCaseIDs();
666 
getDeclParmVarAbbrev()667   unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
getDeclRefExprAbbrev()668   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
getCharacterLiteralAbbrev()669   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
getDeclRecordAbbrev()670   unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
getIntegerLiteralAbbrev()671   unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
getDeclTypedefAbbrev()672   unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
getDeclVarAbbrev()673   unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
getDeclFieldAbbrev()674   unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
getDeclEnumAbbrev()675   unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
getDeclObjCIvarAbbrev()676   unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
677 
hasChain()678   bool hasChain() const { return Chain; }
679 
680   // ASTDeserializationListener implementation
681   void ReaderInitialized(ASTReader *Reader);
682   void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II);
683   void TypeRead(serialization::TypeIdx Idx, QualType T);
684   void SelectorRead(serialization::SelectorID ID, Selector Sel);
685   void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
686                            MacroDefinition *MD);
687   void MacroVisible(IdentifierInfo *II);
688   void ModuleRead(serialization::SubmoduleID ID, Module *Mod);
689 
690   // ASTMutationListener implementation.
691   virtual void CompletedTagDefinition(const TagDecl *D);
692   virtual void AddedVisibleDecl(const DeclContext *DC, const Decl *D);
693   virtual void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D);
694   virtual void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
695                                     const ClassTemplateSpecializationDecl *D);
696   virtual void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
697                                               const FunctionDecl *D);
698   virtual void CompletedImplicitDefinition(const FunctionDecl *D);
699   virtual void StaticDataMemberInstantiated(const VarDecl *D);
700   virtual void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
701                                             const ObjCInterfaceDecl *IFD);
702   virtual void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
703                                             const ObjCPropertyDecl *OrigProp,
704                                             const ObjCCategoryDecl *ClassExt);
705 };
706 
707 /// \brief AST and semantic-analysis consumer that generates a
708 /// precompiled header from the parsed source code.
709 class PCHGenerator : public SemaConsumer {
710   const Preprocessor &PP;
711   std::string OutputFile;
712   clang::Module *Module;
713   std::string isysroot;
714   raw_ostream *Out;
715   Sema *SemaPtr;
716   MemorizeStatCalls *StatCalls; // owned by the FileManager
717   llvm::SmallVector<char, 128> Buffer;
718   llvm::BitstreamWriter Stream;
719   ASTWriter Writer;
720 
721 protected:
getWriter()722   ASTWriter &getWriter() { return Writer; }
getWriter()723   const ASTWriter &getWriter() const { return Writer; }
724 
725 public:
726   PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
727                clang::Module *Module,
728                StringRef isysroot, raw_ostream *Out);
729   ~PCHGenerator();
InitializeSema(Sema & S)730   virtual void InitializeSema(Sema &S) { SemaPtr = &S; }
731   virtual void HandleTranslationUnit(ASTContext &Ctx);
732   virtual ASTMutationListener *GetASTMutationListener();
733   virtual ASTDeserializationListener *GetASTDeserializationListener();
734 };
735 
736 } // end namespace clang
737 
738 #endif
739