1 //===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTWriter class, which writes an AST file
11 // containing a serialized representation of a translation unit.
13 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_SERIALIZATION_ASTWRITER_H
15 #define LLVM_CLANG_SERIALIZATION_ASTWRITER_H
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"
39 class BitstreamWriter;
46 class NestedNameSpecifier;
47 class CXXBaseSpecifier;
48 class CXXCtorInitializer;
52 class HeaderSearchOptions;
53 class IdentifierResolver;
54 class MacroDefinitionRecord;
57 class OpaqueValueExpr;
61 class PreprocessedEntity;
62 class PreprocessingRecord;
67 struct StoredDeclsList;
72 class ASTUnresolvedSet;
74 namespace SrcMgr { class SLocEntry; }
76 /// \brief Writes an AST file containing the contents of a translation unit.
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 {
85 typedef SmallVector<uint64_t, 64> RecordData;
86 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
88 friend class ASTDeclWriter;
89 friend class ASTStmtWriter;
91 /// \brief Map that provides the ID numbers of each type within the
92 /// output stream, plus those deserialized from a chained PCH.
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.
99 /// Keys in the map never have const/volatile qualifiers.
100 typedef llvm::DenseMap<QualType, serialization::TypeIdx,
101 serialization::UnsafeQualTypeDenseMapInfo>
104 /// \brief The bitstream writer used to emit this precompiled header.
105 llvm::BitstreamWriter &Stream;
107 /// \brief The ASTContext we're writing.
110 /// \brief The preprocessor we're writing.
113 /// \brief The reader of existing AST files, if we're chaining.
116 /// \brief The module we're currently writing, if any.
117 Module *WritingModule;
119 /// \brief The base directory for any relative paths we emit.
120 std::string BaseDirectory;
122 /// \brief Indicates when the AST writing is actively performing
123 /// serialization, rather than just queueing updates.
126 /// \brief Indicates that we are done serializing the collection of decls
127 /// and types to emit.
128 bool DoneWritingDeclsAndTypes;
130 /// \brief Indicates that the AST contained compiler errors.
131 bool ASTHasCompilerErrors;
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;
137 /// \brief Stores a declaration or a type to be written to the AST file.
140 DeclOrType(Decl *D) : Stored(D), IsType(false) { }
141 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
143 bool isType() const { return IsType; }
144 bool isDecl() const { return !IsType; }
146 QualType getType() const {
147 assert(isType() && "Not a type!");
148 return QualType::getFromOpaquePtr(Stored);
151 Decl *getDecl() const {
152 assert(isDecl() && "Not a decl!");
153 return static_cast<Decl *>(Stored);
161 /// \brief The declarations and types to emit.
162 std::queue<DeclOrType> DeclTypesToEmit;
164 /// \brief The first ID number we can use for our own declarations.
165 serialization::DeclID FirstDeclID;
167 /// \brief The decl ID that will be assigned to the next new decl.
168 serialization::DeclID NextDeclID;
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.
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;
178 /// \brief Offset of each declaration in the bitstream, indexed by
179 /// the declaration's ID.
180 std::vector<serialization::DeclOffset> DeclOffsets;
182 /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
183 typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
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;
191 typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
193 /// \brief Map from file SLocEntries to info about the file-level declarations
194 /// that it contains.
195 FileDeclIDsTy FileDeclIDs;
197 void associateDeclWithFile(const Decl *D, serialization::DeclID);
199 /// \brief The first ID number we can use for our own types.
200 serialization::TypeID FirstTypeID;
202 /// \brief The type ID that will be assigned to the next new type.
203 serialization::TypeID NextTypeID;
205 /// \brief Map that provides the ID numbers of each type within the
206 /// output stream, plus those deserialized from a chained PCH.
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.
213 /// Keys in the map never have const/volatile qualifiers.
216 /// \brief Offset of each type in the bitstream, indexed by
218 std::vector<uint32_t> TypeOffsets;
220 /// \brief The first ID number we can use for our own identifiers.
221 serialization::IdentID FirstIdentID;
223 /// \brief The identifier ID that will be assigned to the next new identifier.
224 serialization::IdentID NextIdentID;
226 /// \brief Map that provides the ID numbers of each identifier in
227 /// the output stream.
229 /// The ID numbers for identifiers are consecutive (in order of
230 /// discovery), starting at 1. An ID of zero refers to a NULL
232 llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
234 /// \brief The first ID number we can use for our own macros.
235 serialization::MacroID FirstMacroID;
237 /// \brief The identifier ID that will be assigned to the next new identifier.
238 serialization::MacroID NextMacroID;
240 /// \brief Map that provides the ID numbers of each macro.
241 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
243 struct MacroInfoToEmitData {
244 const IdentifierInfo *Name;
246 serialization::MacroID ID;
248 /// \brief The macro infos to emit.
249 std::vector<MacroInfoToEmitData> MacroInfosToEmit;
251 llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
253 /// @name FlushStmt Caches
256 /// \brief Set of parent Stmts for the currently serializing sub-stmt.
257 llvm::DenseSet<Stmt *> ParentStmts;
259 /// \brief Offsets of sub-stmts already serialized. The offset points
260 /// just after the stmt record.
261 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
265 /// \brief Offsets of each of the identifier IDs into the identifier
267 std::vector<uint32_t> IdentifierOffsets;
269 /// \brief The first ID number we can use for our own submodules.
270 serialization::SubmoduleID FirstSubmoduleID;
272 /// \brief The submodule ID that will be assigned to the next new submodule.
273 serialization::SubmoduleID NextSubmoduleID;
275 /// \brief The first ID number we can use for our own selectors.
276 serialization::SelectorID FirstSelectorID;
278 /// \brief The selector ID that will be assigned to the next new selector.
279 serialization::SelectorID NextSelectorID;
281 /// \brief Map that provides the ID numbers of each Selector.
282 llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
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;
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;
293 /// \brief Cache of indices of anonymous declarations within their lexical
295 llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
297 /// An update to a Decl.
299 /// A DeclUpdateKind.
307 const Attr *Attribute;
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) {}
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);
330 unsigned getNumber() const { return Val; }
331 Module *getModule() const { return Mod; }
332 const Attr *getAttr() const { return Attribute; }
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;
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;
346 /// \brief Declarations encountered that might be external
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
357 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
359 /// \brief DeclContexts that have received extensions since their serialized
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
366 llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
368 /// \brief Keeps track of visible decls that were added in DeclContexts
369 /// coming from another AST file.
370 SmallVector<const Decl *, 16> UpdatingVisibleDecls;
372 typedef llvm::SmallSetVector<const Decl *, 16> DeclsToRewriteTy;
373 /// \brief Decls that will be replaced in the current dependent AST file.
374 DeclsToRewriteTy DeclsToRewrite;
376 /// \brief The set of Objective-C class that have categories we
377 /// should serialize.
378 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
380 struct ReplacedDeclInfo {
381 serialization::DeclID ID;
385 ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
386 ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
388 : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
391 /// \brief Decls that have been replaced in the current dependent AST file.
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;
399 /// \brief The set of declarations that may have redeclaration chains that
400 /// need to be serialized.
401 llvm::SmallVector<const Decl *, 16> Redeclarations;
403 /// \brief Statements that we've encountered while serializing a
404 /// declaration or type.
405 SmallVector<Stmt *, 16> StmtsToEmit;
407 /// \brief Statements collection to use for ASTWriter::AddStmt().
408 /// It will point to StmtsToEmit unless it is overriden.
409 SmallVector<Stmt *, 16> *CollectedStmts;
411 /// \brief Mapping from SwitchCase statements to IDs.
412 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
414 /// \brief The number of statements written to the AST file.
415 unsigned NumStatements;
417 /// \brief The number of macros written to the AST file.
420 /// \brief The number of lexical declcontexts written to the AST
422 unsigned NumLexicalDeclContexts;
424 /// \brief The number of visible declcontexts written to the AST
426 unsigned NumVisibleDeclContexts;
428 /// \brief The offset of each CXXBaseSpecifier set within the AST.
429 SmallVector<uint32_t, 16> CXXBaseSpecifiersOffsets;
431 /// \brief The first ID number we can use for our own base specifiers.
432 serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
434 /// \brief The base specifiers ID that will be assigned to the next new
435 /// set of C++ base specifiers.
436 serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
438 /// \brief A set of C++ base specifiers that is queued to be written into the
440 struct QueuedCXXBaseSpecifiers {
441 QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
443 QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
444 CXXBaseSpecifier const *Bases,
445 CXXBaseSpecifier const *BasesEnd)
446 : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
448 serialization::CXXBaseSpecifiersID ID;
449 CXXBaseSpecifier const * Bases;
450 CXXBaseSpecifier const * BasesEnd;
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;
457 /// \brief The offset of each CXXCtorInitializer list within the AST.
458 SmallVector<uint32_t, 16> CXXCtorInitializersOffsets;
460 /// \brief The first ID number we can use for our own ctor initializers.
461 serialization::CXXCtorInitializersID FirstCXXCtorInitializersID;
463 /// \brief The ctor initializers ID that will be assigned to the next new
464 /// list of C++ ctor initializers.
465 serialization::CXXCtorInitializersID NextCXXCtorInitializersID;
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() {}
472 QueuedCXXCtorInitializers(serialization::CXXCtorInitializersID ID,
473 ArrayRef<CXXCtorInitializer*> Inits)
474 : ID(ID), Inits(Inits) {}
476 serialization::CXXCtorInitializersID ID;
477 ArrayRef<CXXCtorInitializer*> Inits;
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;
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;
488 /// \brief Retrieve or create a submodule ID for this module.
489 unsigned getSubmoduleID(Module *Mod);
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);
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,
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);
509 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
511 void WriteCXXBaseSpecifiersOffsets();
512 void WriteCXXCtorInitializersOffsets();
514 unsigned TypeExtQualAbbrev;
515 unsigned TypeFunctionProtoAbbrev;
516 void WriteTypeAbbrevs();
517 void WriteType(QualType T);
519 bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
520 bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
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,
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);
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;
556 unsigned DeclRefExprAbbrev;
557 unsigned CharacterLiteralAbbrev;
558 unsigned IntegerLiteralAbbrev;
559 unsigned ExprImplicitCastAbbrev;
561 void WriteDeclAbbrevs();
562 void WriteDecl(ASTContext &Context, Decl *D);
563 void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record);
565 void WriteASTCore(Sema &SemaRef,
566 StringRef isysroot, const std::string &OutputFile,
567 Module *WritingModule);
570 /// \brief Create a new precompiled header writer that outputs to
571 /// the given bitstream.
572 ASTWriter(llvm::BitstreamWriter &Stream);
573 ~ASTWriter() override;
575 const LangOptions &getLangOpts() const;
577 /// \brief Write a precompiled header for the given semantic analysis.
579 /// \param SemaRef a reference to the semantic analysis object that processed
580 /// the AST to be written into the precompiled header.
582 /// \param WritingModule The module that we are writing. If null, we are
583 /// writing a precompiled header.
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);
593 /// \brief Emit a token.
594 void AddToken(const Token &Tok, RecordDataImpl &Record);
596 /// \brief Emit a source location.
597 void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
599 /// \brief Emit a source range.
600 void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
602 /// \brief Emit an integral value.
603 void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
605 /// \brief Emit a signed integral value.
606 void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
608 /// \brief Emit a floating-point value.
609 void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
611 /// \brief Emit a reference to an identifier.
612 void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
614 /// \brief Emit a Selector (which is a smart pointer reference).
615 void AddSelectorRef(Selector, RecordDataImpl &Record);
617 /// \brief Emit a CXXTemporary.
618 void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
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);
625 /// \brief Get the unique number used to refer to the given selector.
626 serialization::SelectorID getSelectorRef(Selector Sel);
628 /// \brief Get the unique number used to refer to the given identifier.
629 serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
631 /// \brief Get the unique number used to refer to the given macro.
632 serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
634 /// \brief Determine the ID of an already-emitted macro.
635 serialization::MacroID getMacroID(MacroInfo *MI);
637 uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
639 /// \brief Emit a reference to a type.
640 void AddTypeRef(QualType T, RecordDataImpl &Record);
642 /// \brief Force a type to be emitted and get its ID.
643 serialization::TypeID GetOrCreateTypeID(QualType T);
645 /// \brief Determine the type ID of an already-emitted type.
646 serialization::TypeID getTypeID(QualType T) const;
648 /// \brief Emits a reference to a declarator info.
649 void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
651 /// \brief Emits a type with source-location information.
652 void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
654 /// \brief Emits a template argument location info.
655 void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
656 const TemplateArgumentLocInfo &Arg,
657 RecordDataImpl &Record);
659 /// \brief Emits a template argument location.
660 void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
661 RecordDataImpl &Record);
663 /// \brief Emits an AST template argument list info.
664 void AddASTTemplateArgumentListInfo(
665 const ASTTemplateArgumentListInfo *ASTTemplArgList,
666 RecordDataImpl &Record);
668 /// \brief Emit a reference to a declaration.
669 void AddDeclRef(const Decl *D, RecordDataImpl &Record);
672 /// \brief Force a declaration to be emitted and get its ID.
673 serialization::DeclID GetDeclRef(const Decl *D);
675 /// \brief Determine the declaration ID of an already-emitted
677 serialization::DeclID getDeclID(const Decl *D);
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);
687 void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
689 /// \brief Emit a nested name specifier.
690 void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
692 /// \brief Emit a nested name specifier with source-location information.
693 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
694 RecordDataImpl &Record);
696 /// \brief Emit a template name.
697 void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
699 /// \brief Emit a template argument.
700 void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
702 /// \brief Emit a template parameter list.
703 void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
704 RecordDataImpl &Record);
706 /// \brief Emit a template argument list.
707 void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
708 RecordDataImpl &Record);
710 /// \brief Emit a UnresolvedSet structure.
711 void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record);
713 /// \brief Emit a C++ base specifier.
714 void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
715 RecordDataImpl &Record);
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);
722 /// \brief Emit a CXXCtorInitializer array.
723 void AddCXXCtorInitializers(
724 const CXXCtorInitializer * const *CtorInitializers,
725 unsigned NumCtorInitializers,
726 RecordDataImpl &Record);
728 void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
730 /// \brief Add a string to the given record.
731 void AddString(StringRef Str, RecordDataImpl &Record);
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);
737 /// \brief Add a path to the given record.
738 void AddPath(StringRef Path, RecordDataImpl &Record);
740 /// \brief Emit the current record with the given path as a blob.
741 void EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
744 /// \brief Add a version tuple to the given record
745 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
747 void RewriteDecl(const Decl *D) {
748 DeclsToRewrite.insert(D);
751 bool isRewritten(const Decl *D) const {
752 return DeclsToRewrite.count(D);
755 /// \brief Infer the submodule ID that contains an entity at the given
757 serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
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;
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);
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);
771 /// \brief Add the given statement or expression to the queue of
772 /// statements to emit.
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
779 void AddStmt(Stmt *S) {
780 CollectedStmts->push_back(S);
783 /// \brief Flush all of the statements and expressions that have
784 /// been added to the queue via AddStmt().
787 /// \brief Flush all of the C++ base specifier sets that have been added
788 /// via \c AddCXXBaseSpecifiersRef().
789 void FlushCXXBaseSpecifiers();
791 /// \brief Flush all of the C++ constructor initializer lists that have been
792 /// added via \c AddCXXCtorInitializersRef().
793 void FlushCXXCtorInitializers();
795 /// \brief Flush all pending records that are tacked onto the end of
796 /// decl and decl update records.
797 void FlushPendingAfterDecl() {
799 FlushCXXBaseSpecifiers();
800 FlushCXXCtorInitializers();
803 /// \brief Record an ID for the given switch-case statement.
804 unsigned RecordSwitchCaseID(SwitchCase *S);
806 /// \brief Retrieve the ID for the given switch-case statement.
807 unsigned getSwitchCaseID(SwitchCase *S);
809 void ClearSwitchCaseIDs();
811 unsigned getTypeExtQualAbbrev() const {
812 return TypeExtQualAbbrev;
814 unsigned getTypeFunctionProtoAbbrev() const {
815 return TypeFunctionProtoAbbrev;
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; }
827 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
828 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
829 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
830 unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
832 bool hasChain() const { return Chain; }
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;
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;
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;
881 std::shared_ptr<PCHBuffer> Buffer;
882 llvm::BitstreamWriter Stream;
884 bool AllowASTWithErrors;
887 ASTWriter &getWriter() { return Writer; }
888 const ASTWriter &getWriter() const { return Writer; }
889 SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
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; }
904 } // end namespace clang