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