]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Serialization/ASTWriter.h
Update clang to trunk r290819 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Serialization / ASTWriter.h
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_SERIALIZATION_ASTWRITER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTWRITER_H
16
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/TemplateBase.h"
20 #include "clang/Frontend/PCHContainerOperations.h"
21 #include "clang/Sema/SemaConsumer.h"
22 #include "clang/Serialization/ASTBitCodes.h"
23 #include "clang/Serialization/ASTDeserializationListener.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Bitcode/BitstreamWriter.h"
30 #include <queue>
31 #include <vector>
32
33 namespace llvm {
34   class APFloat;
35   class APInt;
36 }
37
38 namespace clang {
39
40 class DeclarationName;
41 class ASTContext;
42 class Attr;
43 class NestedNameSpecifier;
44 class CXXBaseSpecifier;
45 class CXXCtorInitializer;
46 class FileEntry;
47 class FPOptions;
48 class HeaderSearch;
49 class HeaderSearchOptions;
50 class IdentifierResolver;
51 class MacroDefinitionRecord;
52 class MacroDirective;
53 class MacroInfo;
54 class OpaqueValueExpr;
55 class OpenCLOptions;
56 class ASTReader;
57 class Module;
58 class ModuleFileExtension;
59 class ModuleFileExtensionWriter;
60 class PreprocessedEntity;
61 class PreprocessingRecord;
62 class Preprocessor;
63 class RecordDecl;
64 class Sema;
65 class SourceManager;
66 struct StoredDeclsList;
67 class SwitchCase;
68 class TargetInfo;
69 class Token;
70 class VersionTuple;
71 class ASTUnresolvedSet;
72
73 namespace SrcMgr { class SLocEntry; }
74
75 /// \brief Writes an AST file containing the contents of a translation unit.
76 ///
77 /// The ASTWriter class produces a bitstream containing the serialized
78 /// representation of a given abstract syntax tree and its supporting
79 /// data structures. This bitstream can be de-serialized via an
80 /// instance of the ASTReader class.
81 class ASTWriter : public ASTDeserializationListener,
82                   public ASTMutationListener {
83 public:
84   typedef SmallVector<uint64_t, 64> RecordData;
85   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
86   typedef ArrayRef<uint64_t> RecordDataRef;
87
88   friend class ASTDeclWriter;
89   friend class ASTStmtWriter;
90   friend class ASTTypeWriter;
91   friend class ASTRecordWriter;
92 private:
93   /// \brief Map that provides the ID numbers of each type within the
94   /// output stream, plus those deserialized from a chained PCH.
95   ///
96   /// The ID numbers of types are consecutive (in order of discovery)
97   /// and start at 1. 0 is reserved for NULL. When types are actually
98   /// stored in the stream, the ID number is shifted by 2 bits to
99   /// allow for the const/volatile qualifiers.
100   ///
101   /// Keys in the map never have const/volatile qualifiers.
102   typedef llvm::DenseMap<QualType, serialization::TypeIdx,
103                          serialization::UnsafeQualTypeDenseMapInfo>
104     TypeIdxMap;
105
106   /// \brief The bitstream writer used to emit this precompiled header.
107   llvm::BitstreamWriter &Stream;
108
109   /// \brief The ASTContext we're writing.
110   ASTContext *Context;
111
112   /// \brief The preprocessor we're writing.
113   Preprocessor *PP;
114
115   /// \brief The reader of existing AST files, if we're chaining.
116   ASTReader *Chain;
117
118   /// \brief The module we're currently writing, if any.
119   Module *WritingModule;
120
121   /// \brief The base directory for any relative paths we emit.
122   std::string BaseDirectory;
123
124   /// \brief Indicates whether timestamps should be written to the produced
125   /// module file. This is the case for files implicitly written to the
126   /// module cache, where we need the timestamps to determine if the module
127   /// file is up to date, but not otherwise.
128   bool IncludeTimestamps;
129
130   /// \brief Indicates when the AST writing is actively performing
131   /// serialization, rather than just queueing updates.
132   bool WritingAST;
133
134   /// \brief Indicates that we are done serializing the collection of decls
135   /// and types to emit.
136   bool DoneWritingDeclsAndTypes;
137
138   /// \brief Indicates that the AST contained compiler errors.
139   bool ASTHasCompilerErrors;
140
141   /// \brief Mapping from input file entries to the index into the
142   /// offset table where information about that input file is stored.
143   llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
144
145   /// \brief Stores a declaration or a type to be written to the AST file.
146   class DeclOrType {
147   public:
148     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
149     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
150
151     bool isType() const { return IsType; }
152     bool isDecl() const { return !IsType; }
153
154     QualType getType() const {
155       assert(isType() && "Not a type!");
156       return QualType::getFromOpaquePtr(Stored);
157     }
158
159     Decl *getDecl() const {
160       assert(isDecl() && "Not a decl!");
161       return static_cast<Decl *>(Stored);
162     }
163
164   private:
165     void *Stored;
166     bool IsType;
167   };
168
169   /// \brief The declarations and types to emit.
170   std::queue<DeclOrType> DeclTypesToEmit;
171
172   /// \brief The first ID number we can use for our own declarations.
173   serialization::DeclID FirstDeclID;
174
175   /// \brief The decl ID that will be assigned to the next new decl.
176   serialization::DeclID NextDeclID;
177
178   /// \brief Map that provides the ID numbers of each declaration within
179   /// the output stream, as well as those deserialized from a chained PCH.
180   ///
181   /// The ID numbers of declarations are consecutive (in order of
182   /// discovery) and start at 2. 1 is reserved for the translation
183   /// unit, while 0 is reserved for NULL.
184   llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
185
186   /// \brief Offset of each declaration in the bitstream, indexed by
187   /// the declaration's ID.
188   std::vector<serialization::DeclOffset> DeclOffsets;
189
190   /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
191   typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
192     LocDeclIDsTy;
193   struct DeclIDInFileInfo {
194     LocDeclIDsTy DeclIDs;
195     /// \brief Set when the DeclIDs vectors from all files are joined, this
196     /// indicates the index that this particular vector has in the global one.
197     unsigned FirstDeclIndex;
198   };
199   typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
200
201   /// \brief Map from file SLocEntries to info about the file-level declarations
202   /// that it contains.
203   FileDeclIDsTy FileDeclIDs;
204
205   void associateDeclWithFile(const Decl *D, serialization::DeclID);
206
207   /// \brief The first ID number we can use for our own types.
208   serialization::TypeID FirstTypeID;
209
210   /// \brief The type ID that will be assigned to the next new type.
211   serialization::TypeID NextTypeID;
212
213   /// \brief Map that provides the ID numbers of each type within the
214   /// output stream, plus those deserialized from a chained PCH.
215   ///
216   /// The ID numbers of types are consecutive (in order of discovery)
217   /// and start at 1. 0 is reserved for NULL. When types are actually
218   /// stored in the stream, the ID number is shifted by 2 bits to
219   /// allow for the const/volatile qualifiers.
220   ///
221   /// Keys in the map never have const/volatile qualifiers.
222   TypeIdxMap TypeIdxs;
223
224   /// \brief Offset of each type in the bitstream, indexed by
225   /// the type's ID.
226   std::vector<uint32_t> TypeOffsets;
227
228   /// \brief The first ID number we can use for our own identifiers.
229   serialization::IdentID FirstIdentID;
230
231   /// \brief The identifier ID that will be assigned to the next new identifier.
232   serialization::IdentID NextIdentID;
233
234   /// \brief Map that provides the ID numbers of each identifier in
235   /// the output stream.
236   ///
237   /// The ID numbers for identifiers are consecutive (in order of
238   /// discovery), starting at 1. An ID of zero refers to a NULL
239   /// IdentifierInfo.
240   llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
241
242   /// \brief The first ID number we can use for our own macros.
243   serialization::MacroID FirstMacroID;
244
245   /// \brief The identifier ID that will be assigned to the next new identifier.
246   serialization::MacroID NextMacroID;
247
248   /// \brief Map that provides the ID numbers of each macro.
249   llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
250
251   struct MacroInfoToEmitData {
252     const IdentifierInfo *Name;
253     MacroInfo *MI;
254     serialization::MacroID ID;
255   };
256   /// \brief The macro infos to emit.
257   std::vector<MacroInfoToEmitData> MacroInfosToEmit;
258
259   llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
260
261   /// @name FlushStmt Caches
262   /// @{
263
264   /// \brief Set of parent Stmts for the currently serializing sub-stmt.
265   llvm::DenseSet<Stmt *> ParentStmts;
266
267   /// \brief Offsets of sub-stmts already serialized. The offset points
268   /// just after the stmt record.
269   llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
270
271   /// @}
272
273   /// \brief Offsets of each of the identifier IDs into the identifier
274   /// table.
275   std::vector<uint32_t> IdentifierOffsets;
276
277   /// \brief The first ID number we can use for our own submodules.
278   serialization::SubmoduleID FirstSubmoduleID;
279   
280   /// \brief The submodule ID that will be assigned to the next new submodule.
281   serialization::SubmoduleID NextSubmoduleID;
282
283   /// \brief The first ID number we can use for our own selectors.
284   serialization::SelectorID FirstSelectorID;
285
286   /// \brief The selector ID that will be assigned to the next new selector.
287   serialization::SelectorID NextSelectorID;
288
289   /// \brief Map that provides the ID numbers of each Selector.
290   llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
291
292   /// \brief Offset of each selector within the method pool/selector
293   /// table, indexed by the Selector ID (-1).
294   std::vector<uint32_t> SelectorOffsets;
295
296   /// \brief Mapping from macro definitions (as they occur in the preprocessing
297   /// record) to the macro IDs.
298   llvm::DenseMap<const MacroDefinitionRecord *,
299                  serialization::PreprocessedEntityID> MacroDefinitions;
300
301   /// \brief Cache of indices of anonymous declarations within their lexical
302   /// contexts.
303   llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
304
305   /// An update to a Decl.
306   class DeclUpdate {
307     /// A DeclUpdateKind.
308     unsigned Kind;
309     union {
310       const Decl *Dcl;
311       void *Type;
312       unsigned Loc;
313       unsigned Val;
314       Module *Mod;
315       const Attr *Attribute;
316     };
317
318   public:
319     DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {}
320     DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {}
321     DeclUpdate(unsigned Kind, QualType Type)
322         : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
323     DeclUpdate(unsigned Kind, SourceLocation Loc)
324         : Kind(Kind), Loc(Loc.getRawEncoding()) {}
325     DeclUpdate(unsigned Kind, unsigned Val)
326         : Kind(Kind), Val(Val) {}
327     DeclUpdate(unsigned Kind, Module *M)
328           : Kind(Kind), Mod(M) {}
329     DeclUpdate(unsigned Kind, const Attr *Attribute)
330           : Kind(Kind), Attribute(Attribute) {}
331
332     unsigned getKind() const { return Kind; }
333     const Decl *getDecl() const { return Dcl; }
334     QualType getType() const { return QualType::getFromOpaquePtr(Type); }
335     SourceLocation getLoc() const {
336       return SourceLocation::getFromRawEncoding(Loc);
337     }
338     unsigned getNumber() const { return Val; }
339     Module *getModule() const { return Mod; }
340     const Attr *getAttr() const { return Attribute; }
341   };
342
343   typedef SmallVector<DeclUpdate, 1> UpdateRecord;
344   typedef llvm::MapVector<const Decl *, UpdateRecord> DeclUpdateMap;
345   /// \brief Mapping from declarations that came from a chained PCH to the
346   /// record containing modifications to them.
347   DeclUpdateMap DeclUpdates;
348
349   typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
350   /// \brief Map of first declarations from a chained PCH that point to the
351   /// most recent declarations in another PCH.
352   FirstLatestDeclMap FirstLatestDecls;
353
354   /// \brief Declarations encountered that might be external
355   /// definitions.
356   ///
357   /// We keep track of external definitions and other 'interesting' declarations
358   /// as we are emitting declarations to the AST file. The AST file contains a
359   /// separate record for these declarations, which are provided to the AST
360   /// consumer by the AST reader. This is behavior is required to properly cope with,
361   /// e.g., tentative variable definitions that occur within
362   /// headers. The declarations themselves are stored as declaration
363   /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
364   /// record.
365   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
366
367   /// \brief DeclContexts that have received extensions since their serialized
368   /// form.
369   ///
370   /// For namespaces, when we're chaining and encountering a namespace, we check
371   /// if its primary namespace comes from the chain. If it does, we add the
372   /// primary to this set, so that we can write out lexical content updates for
373   /// it.
374   llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
375
376   /// \brief Keeps track of declarations that we must emit, even though we're
377   /// not guaranteed to be able to find them by walking the AST starting at the
378   /// translation unit.
379   SmallVector<const Decl *, 16> DeclsToEmitEvenIfUnreferenced;
380
381   /// \brief The set of Objective-C class that have categories we
382   /// should serialize.
383   llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
384                     
385   /// \brief The set of declarations that may have redeclaration chains that
386   /// need to be serialized.
387   llvm::SmallVector<const Decl *, 16> Redeclarations;
388
389   /// \brief A cache of the first local declaration for "interesting"
390   /// redeclaration chains.
391   llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
392                                       
393   /// \brief Mapping from SwitchCase statements to IDs.
394   llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
395
396   /// \brief The number of statements written to the AST file.
397   unsigned NumStatements;
398
399   /// \brief The number of macros written to the AST file.
400   unsigned NumMacros;
401
402   /// \brief The number of lexical declcontexts written to the AST
403   /// file.
404   unsigned NumLexicalDeclContexts;
405
406   /// \brief The number of visible declcontexts written to the AST
407   /// file.
408   unsigned NumVisibleDeclContexts;
409
410   /// \brief A mapping from each known submodule to its ID number, which will
411   /// be a positive integer.
412   llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
413
414   /// \brief A list of the module file extension writers.
415   std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
416     ModuleFileExtensionWriters;
417
418   /// \brief Retrieve or create a submodule ID for this module.
419   unsigned getSubmoduleID(Module *Mod);
420
421   /// \brief Write the given subexpression to the bitstream.
422   void WriteSubStmt(Stmt *S);
423
424   void WriteBlockInfoBlock();
425   uint64_t WriteControlBlock(Preprocessor &PP, ASTContext &Context,
426                              StringRef isysroot, const std::string &OutputFile);
427   void WriteInputFiles(SourceManager &SourceMgr, HeaderSearchOptions &HSOpts,
428                        bool Modules);
429   void WriteSourceManagerBlock(SourceManager &SourceMgr,
430                                const Preprocessor &PP);
431   void WritePreprocessor(const Preprocessor &PP, bool IsModule);
432   void WriteHeaderSearch(const HeaderSearch &HS);
433   void WritePreprocessorDetail(PreprocessingRecord &PPRec);
434   void WriteSubmodules(Module *WritingModule);
435                                         
436   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
437                                      bool isModule);
438
439   unsigned TypeExtQualAbbrev;
440   unsigned TypeFunctionProtoAbbrev;
441   void WriteTypeAbbrevs();
442   void WriteType(QualType T);
443
444   bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
445   bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
446
447   void GenerateNameLookupTable(const DeclContext *DC,
448                                llvm::SmallVectorImpl<char> &LookupTable);
449   uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
450   uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
451   void WriteTypeDeclOffsets();
452   void WriteFileDeclIDsMap();
453   void WriteComments();
454   void WriteSelectors(Sema &SemaRef);
455   void WriteReferencedSelectorsPool(Sema &SemaRef);
456   void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
457                             bool IsModule);
458   void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord);
459   void WriteDeclContextVisibleUpdate(const DeclContext *DC);
460   void WriteFPPragmaOptions(const FPOptions &Opts);
461   void WriteOpenCLExtensions(Sema &SemaRef);
462   void WriteOpenCLExtensionTypes(Sema &SemaRef);
463   void WriteOpenCLExtensionDecls(Sema &SemaRef);
464   void WriteCUDAPragmas(Sema &SemaRef);
465   void WriteObjCCategories();
466   void WriteLateParsedTemplates(Sema &SemaRef);
467   void WriteOptimizePragmaOptions(Sema &SemaRef);
468   void WriteMSStructPragmaOptions(Sema &SemaRef);
469   void WriteMSPointersToMembersPragmaOptions(Sema &SemaRef);
470   void WriteModuleFileExtension(Sema &SemaRef,
471                                 ModuleFileExtensionWriter &Writer);
472
473   unsigned DeclParmVarAbbrev;
474   unsigned DeclContextLexicalAbbrev;
475   unsigned DeclContextVisibleLookupAbbrev;
476   unsigned UpdateVisibleAbbrev;
477   unsigned DeclRecordAbbrev;
478   unsigned DeclTypedefAbbrev;
479   unsigned DeclVarAbbrev;
480   unsigned DeclFieldAbbrev;
481   unsigned DeclEnumAbbrev;
482   unsigned DeclObjCIvarAbbrev;
483   unsigned DeclCXXMethodAbbrev;
484
485   unsigned DeclRefExprAbbrev;
486   unsigned CharacterLiteralAbbrev;
487   unsigned IntegerLiteralAbbrev;
488   unsigned ExprImplicitCastAbbrev;
489
490   void WriteDeclAbbrevs();
491   void WriteDecl(ASTContext &Context, Decl *D);
492
493   uint64_t WriteASTCore(Sema &SemaRef,
494                         StringRef isysroot, const std::string &OutputFile,
495                         Module *WritingModule);
496
497 public:
498   /// \brief Create a new precompiled header writer that outputs to
499   /// the given bitstream.
500   ASTWriter(llvm::BitstreamWriter &Stream,
501             ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
502             bool IncludeTimestamps = true);
503   ~ASTWriter() override;
504
505   const LangOptions &getLangOpts() const;
506
507   /// \brief Get a timestamp for output into the AST file. The actual timestamp
508   /// of the specified file may be ignored if we have been instructed to not
509   /// include timestamps in the output file.
510   time_t getTimestampForOutput(const FileEntry *E) const;
511
512   /// \brief Write a precompiled header for the given semantic analysis.
513   ///
514   /// \param SemaRef a reference to the semantic analysis object that processed
515   /// the AST to be written into the precompiled header.
516   ///
517   /// \param WritingModule The module that we are writing. If null, we are
518   /// writing a precompiled header.
519   ///
520   /// \param isysroot if non-empty, write a relocatable file whose headers
521   /// are relative to the given system root. If we're writing a module, its
522   /// build directory will be used in preference to this if both are available.
523   ///
524   /// \return the module signature, which eventually will be a hash of
525   /// the module but currently is merely a random 32-bit number.
526   uint64_t WriteAST(Sema &SemaRef, const std::string &OutputFile,
527                     Module *WritingModule, StringRef isysroot,
528                     bool hasErrors = false);
529
530   /// \brief Emit a token.
531   void AddToken(const Token &Tok, RecordDataImpl &Record);
532
533   /// \brief Emit a source location.
534   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
535
536   /// \brief Emit a source range.
537   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
538
539   /// \brief Emit a reference to an identifier.
540   void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
541
542   /// \brief Get the unique number used to refer to the given selector.
543   serialization::SelectorID getSelectorRef(Selector Sel);
544
545   /// \brief Get the unique number used to refer to the given identifier.
546   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
547
548   /// \brief Get the unique number used to refer to the given macro.
549   serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
550
551   /// \brief Determine the ID of an already-emitted macro.
552   serialization::MacroID getMacroID(MacroInfo *MI);
553
554   uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
555
556   /// \brief Emit a reference to a type.
557   void AddTypeRef(QualType T, RecordDataImpl &Record);
558
559   /// \brief Force a type to be emitted and get its ID.
560   serialization::TypeID GetOrCreateTypeID(QualType T);
561
562   /// \brief Determine the type ID of an already-emitted type.
563   serialization::TypeID getTypeID(QualType T) const;
564
565   /// \brief Find the first local declaration of a given local redeclarable
566   /// decl.
567   const Decl *getFirstLocalDecl(const Decl *D);
568
569   /// \brief Is this a local declaration (that is, one that will be written to
570   /// our AST file)? This is the case for declarations that are neither imported
571   /// from another AST file nor predefined.
572   bool IsLocalDecl(const Decl *D) {
573     if (D->isFromASTFile())
574       return false;
575     auto I = DeclIDs.find(D);
576     return (I == DeclIDs.end() ||
577             I->second >= serialization::NUM_PREDEF_DECL_IDS);
578   };
579
580   /// \brief Emit a reference to a declaration.
581   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
582
583
584   /// \brief Force a declaration to be emitted and get its ID.
585   serialization::DeclID GetDeclRef(const Decl *D);
586
587   /// \brief Determine the declaration ID of an already-emitted
588   /// declaration.
589   serialization::DeclID getDeclID(const Decl *D);
590
591   unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
592
593   /// \brief Add a string to the given record.
594   void AddString(StringRef Str, RecordDataImpl &Record);
595
596   /// \brief Convert a path from this build process into one that is appropriate
597   /// for emission in the module file.
598   bool PreparePathForOutput(SmallVectorImpl<char> &Path);
599
600   /// \brief Add a path to the given record.
601   void AddPath(StringRef Path, RecordDataImpl &Record);
602
603   /// \brief Emit the current record with the given path as a blob.
604   void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
605                           StringRef Path);
606
607   /// \brief Add a version tuple to the given record
608   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
609
610   /// \brief Infer the submodule ID that contains an entity at the given
611   /// source location.
612   serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
613
614   /// \brief Retrieve or create a submodule ID for this module, or return 0 if
615   /// the submodule is neither local (a submodle of the currently-written module)
616   /// nor from an imported module.
617   unsigned getLocalOrImportedSubmoduleID(Module *Mod);
618
619   /// \brief Note that the identifier II occurs at the given offset
620   /// within the identifier table.
621   void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
622
623   /// \brief Note that the selector Sel occurs at the given offset
624   /// within the method pool/selector table.
625   void SetSelectorOffset(Selector Sel, uint32_t Offset);
626
627   /// \brief Record an ID for the given switch-case statement.
628   unsigned RecordSwitchCaseID(SwitchCase *S);
629
630   /// \brief Retrieve the ID for the given switch-case statement.
631   unsigned getSwitchCaseID(SwitchCase *S);
632
633   void ClearSwitchCaseIDs();
634
635   unsigned getTypeExtQualAbbrev() const {
636     return TypeExtQualAbbrev;
637   }
638   unsigned getTypeFunctionProtoAbbrev() const {
639     return TypeFunctionProtoAbbrev;
640   }
641
642   unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
643   unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
644   unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
645   unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
646   unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
647   unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
648   unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
649   unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; }
650
651   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
652   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
653   unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
654   unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
655
656   bool hasChain() const { return Chain; }
657   ASTReader *getChain() const { return Chain; }
658
659 private:
660   // ASTDeserializationListener implementation
661   void ReaderInitialized(ASTReader *Reader) override;
662   void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override;
663   void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
664   void TypeRead(serialization::TypeIdx Idx, QualType T) override;
665   void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
666   void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
667                            MacroDefinitionRecord *MD) override;
668   void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
669
670   // ASTMutationListener implementation.
671   void CompletedTagDefinition(const TagDecl *D) override;
672   void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
673   void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
674   void AddedCXXTemplateSpecialization(
675       const ClassTemplateDecl *TD,
676       const ClassTemplateSpecializationDecl *D) override;
677   void AddedCXXTemplateSpecialization(
678       const VarTemplateDecl *TD,
679       const VarTemplateSpecializationDecl *D) override;
680   void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
681                                       const FunctionDecl *D) override;
682   void ResolvedExceptionSpec(const FunctionDecl *FD) override;
683   void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
684   void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
685                               const FunctionDecl *Delete) override;
686   void CompletedImplicitDefinition(const FunctionDecl *D) override;
687   void StaticDataMemberInstantiated(const VarDecl *D) override;
688   void DefaultArgumentInstantiated(const ParmVarDecl *D) override;
689   void DefaultMemberInitializerInstantiated(const FieldDecl *D) override;
690   void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
691   void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
692                                     const ObjCInterfaceDecl *IFD) override;
693   void DeclarationMarkedUsed(const Decl *D) override;
694   void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
695   void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
696                                             const Attr *Attr) override;
697   void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override;
698   void AddedAttributeToRecord(const Attr *Attr,
699                               const RecordDecl *Record) override;
700 };
701
702 /// \brief An object for streaming information to a record.
703 class ASTRecordWriter {
704   ASTWriter *Writer;
705   ASTWriter::RecordDataImpl *Record;
706
707   /// \brief Statements that we've encountered while serializing a
708   /// declaration or type.
709   SmallVector<Stmt *, 16> StmtsToEmit;
710
711   /// \brief Indices of record elements that describe offsets within the
712   /// bitcode. These will be converted to offsets relative to the current
713   /// record when emitted.
714   SmallVector<unsigned, 8> OffsetIndices;
715
716   /// \brief Flush all of the statements and expressions that have
717   /// been added to the queue via AddStmt().
718   void FlushStmts();
719   void FlushSubStmts();
720
721   void PrepareToEmit(uint64_t MyOffset) {
722     // Convert offsets into relative form.
723     for (unsigned I : OffsetIndices) {
724       auto &StoredOffset = (*Record)[I];
725       assert(StoredOffset < MyOffset && "invalid offset");
726       if (StoredOffset)
727         StoredOffset = MyOffset - StoredOffset;
728     }
729     OffsetIndices.clear();
730   }
731
732 public:
733   /// Construct a ASTRecordWriter that uses the default encoding scheme.
734   ASTRecordWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
735       : Writer(&Writer), Record(&Record) {}
736
737   /// Construct a ASTRecordWriter that uses the same encoding scheme as another
738   /// ASTRecordWriter.
739   ASTRecordWriter(ASTRecordWriter &Parent, ASTWriter::RecordDataImpl &Record)
740       : Writer(Parent.Writer), Record(&Record) {}
741
742   /// Copying an ASTRecordWriter is almost certainly a bug.
743   ASTRecordWriter(const ASTRecordWriter&) = delete;
744   void operator=(const ASTRecordWriter&) = delete;
745
746   /// \brief Extract the underlying record storage.
747   ASTWriter::RecordDataImpl &getRecordData() const { return *Record; }
748
749   /// \brief Minimal vector-like interface.
750   /// @{
751   void push_back(uint64_t N) { Record->push_back(N); }
752   template<typename InputIterator>
753   void append(InputIterator begin, InputIterator end) {
754     Record->append(begin, end);
755   }
756   bool empty() const { return Record->empty(); }
757   size_t size() const { return Record->size(); }
758   uint64_t &operator[](size_t N) { return (*Record)[N]; }
759   /// @}
760
761   /// \brief Emit the record to the stream, followed by its substatements, and
762   /// return its offset.
763   // FIXME: Allow record producers to suggest Abbrevs.
764   uint64_t Emit(unsigned Code, unsigned Abbrev = 0) {
765     uint64_t Offset = Writer->Stream.GetCurrentBitNo();
766     PrepareToEmit(Offset);
767     Writer->Stream.EmitRecord(Code, *Record, Abbrev);
768     FlushStmts();
769     return Offset;
770   }
771
772   /// \brief Emit the record to the stream, preceded by its substatements.
773   uint64_t EmitStmt(unsigned Code, unsigned Abbrev = 0) {
774     FlushSubStmts();
775     PrepareToEmit(Writer->Stream.GetCurrentBitNo());
776     Writer->Stream.EmitRecord(Code, *Record, Abbrev);
777     return Writer->Stream.GetCurrentBitNo();
778   }
779
780   /// \brief Add a bit offset into the record. This will be converted into an
781   /// offset relative to the current record when emitted.
782   void AddOffset(uint64_t BitOffset) {
783     OffsetIndices.push_back(Record->size());
784     Record->push_back(BitOffset);
785   }
786
787   /// \brief Add the given statement or expression to the queue of
788   /// statements to emit.
789   ///
790   /// This routine should be used when emitting types and declarations
791   /// that have expressions as part of their formulation. Once the
792   /// type or declaration has been written, Emit() will write
793   /// the corresponding statements just after the record.
794   void AddStmt(Stmt *S) {
795     StmtsToEmit.push_back(S);
796   }
797
798   /// \brief Add a definition for the given function to the queue of statements
799   /// to emit.
800   void AddFunctionDefinition(const FunctionDecl *FD);
801
802   /// \brief Emit a source location.
803   void AddSourceLocation(SourceLocation Loc) {
804     return Writer->AddSourceLocation(Loc, *Record);
805   }
806
807   /// \brief Emit a source range.
808   void AddSourceRange(SourceRange Range) {
809     return Writer->AddSourceRange(Range, *Record);
810   }
811
812   /// \brief Emit an integral value.
813   void AddAPInt(const llvm::APInt &Value);
814
815   /// \brief Emit a signed integral value.
816   void AddAPSInt(const llvm::APSInt &Value);
817
818   /// \brief Emit a floating-point value.
819   void AddAPFloat(const llvm::APFloat &Value);
820
821   /// \brief Emit a reference to an identifier.
822   void AddIdentifierRef(const IdentifierInfo *II) {
823     return Writer->AddIdentifierRef(II, *Record);
824   }
825
826   /// \brief Emit a Selector (which is a smart pointer reference).
827   void AddSelectorRef(Selector S);
828
829   /// \brief Emit a CXXTemporary.
830   void AddCXXTemporary(const CXXTemporary *Temp);
831
832   /// \brief Emit a C++ base specifier.
833   void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base);
834
835   /// \brief Emit a set of C++ base specifiers.
836   void AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases);
837
838   /// \brief Emit a reference to a type.
839   void AddTypeRef(QualType T) {
840     return Writer->AddTypeRef(T, *Record);
841   }
842
843   /// \brief Emits a reference to a declarator info.
844   void AddTypeSourceInfo(TypeSourceInfo *TInfo);
845
846   /// \brief Emits a type with source-location information.
847   void AddTypeLoc(TypeLoc TL);
848
849   /// \brief Emits a template argument location info.
850   void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
851                                   const TemplateArgumentLocInfo &Arg);
852
853   /// \brief Emits a template argument location.
854   void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg);
855
856   /// \brief Emits an AST template argument list info.
857   void AddASTTemplateArgumentListInfo(
858       const ASTTemplateArgumentListInfo *ASTTemplArgList);
859
860   /// \brief Emit a reference to a declaration.
861   void AddDeclRef(const Decl *D) {
862     return Writer->AddDeclRef(D, *Record);
863   }
864
865   /// \brief Emit a declaration name.
866   void AddDeclarationName(DeclarationName Name);
867
868   void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
869                              DeclarationName Name);
870   void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
871
872   void AddQualifierInfo(const QualifierInfo &Info);
873
874   /// \brief Emit a nested name specifier.
875   void AddNestedNameSpecifier(NestedNameSpecifier *NNS);
876
877   /// \brief Emit a nested name specifier with source-location information.
878   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
879
880   /// \brief Emit a template name.
881   void AddTemplateName(TemplateName Name);
882
883   /// \brief Emit a template argument.
884   void AddTemplateArgument(const TemplateArgument &Arg);
885
886   /// \brief Emit a template parameter list.
887   void AddTemplateParameterList(const TemplateParameterList *TemplateParams);
888
889   /// \brief Emit a template argument list.
890   void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs);
891
892   /// \brief Emit a UnresolvedSet structure.
893   void AddUnresolvedSet(const ASTUnresolvedSet &Set);
894
895   /// \brief Emit a CXXCtorInitializer array.
896   void AddCXXCtorInitializers(ArrayRef<CXXCtorInitializer*> CtorInits);
897
898   void AddCXXDefinitionData(const CXXRecordDecl *D);
899
900   /// \brief Emit a string.
901   void AddString(StringRef Str) {
902     return Writer->AddString(Str, *Record);
903   }
904
905   /// \brief Emit a path.
906   void AddPath(StringRef Path) {
907     return Writer->AddPath(Path, *Record);
908   }
909
910   /// \brief Emit a version tuple.
911   void AddVersionTuple(const VersionTuple &Version) {
912     return Writer->AddVersionTuple(Version, *Record);
913   }
914
915   /// \brief Emit a list of attributes.
916   void AddAttributes(ArrayRef<const Attr*> Attrs);
917 };
918
919 /// \brief AST and semantic-analysis consumer that generates a
920 /// precompiled header from the parsed source code.
921 class PCHGenerator : public SemaConsumer {
922   const Preprocessor &PP;
923   std::string OutputFile;
924   std::string isysroot;
925   Sema *SemaPtr;
926   std::shared_ptr<PCHBuffer> Buffer;
927   llvm::BitstreamWriter Stream;
928   ASTWriter Writer;
929   bool AllowASTWithErrors;
930
931 protected:
932   ASTWriter &getWriter() { return Writer; }
933   const ASTWriter &getWriter() const { return Writer; }
934   SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
935
936 public:
937   PCHGenerator(
938     const Preprocessor &PP, StringRef OutputFile,
939     StringRef isysroot,
940     std::shared_ptr<PCHBuffer> Buffer,
941     ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
942     bool AllowASTWithErrors = false,
943     bool IncludeTimestamps = true);
944   ~PCHGenerator() override;
945   void InitializeSema(Sema &S) override { SemaPtr = &S; }
946   void HandleTranslationUnit(ASTContext &Ctx) override;
947   ASTMutationListener *GetASTMutationListener() override;
948   ASTDeserializationListener *GetASTDeserializationListener() override;
949   bool hasEmittedPCH() const { return Buffer->IsComplete; }
950 };
951
952 } // end namespace clang
953
954 #endif