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/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"
40 class DeclarationName;
43 class NestedNameSpecifier;
44 class CXXBaseSpecifier;
45 class CXXCtorInitializer;
49 class HeaderSearchOptions;
50 class IdentifierResolver;
51 class MacroDefinitionRecord;
54 class OpaqueValueExpr;
58 class ModuleFileExtension;
59 class ModuleFileExtensionWriter;
60 class PreprocessedEntity;
61 class PreprocessingRecord;
66 struct StoredDeclsList;
71 class ASTUnresolvedSet;
73 namespace SrcMgr { class SLocEntry; }
75 /// \brief Writes an AST file containing the contents of a translation unit.
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 {
84 typedef SmallVector<uint64_t, 64> RecordData;
85 typedef SmallVectorImpl<uint64_t> RecordDataImpl;
86 typedef ArrayRef<uint64_t> RecordDataRef;
88 friend class ASTDeclWriter;
89 friend class ASTStmtWriter;
90 friend class ASTTypeWriter;
91 friend class ASTRecordWriter;
93 /// \brief Map that provides the ID numbers of each type within the
94 /// output stream, plus those deserialized from a chained PCH.
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.
101 /// Keys in the map never have const/volatile qualifiers.
102 typedef llvm::DenseMap<QualType, serialization::TypeIdx,
103 serialization::UnsafeQualTypeDenseMapInfo>
106 /// \brief The bitstream writer used to emit this precompiled header.
107 llvm::BitstreamWriter &Stream;
109 /// \brief The ASTContext we're writing.
112 /// \brief The preprocessor we're writing.
115 /// \brief The reader of existing AST files, if we're chaining.
118 /// \brief The module we're currently writing, if any.
119 Module *WritingModule;
121 /// \brief The base directory for any relative paths we emit.
122 std::string BaseDirectory;
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;
130 /// \brief Indicates when the AST writing is actively performing
131 /// serialization, rather than just queueing updates.
134 /// \brief Indicates that we are done serializing the collection of decls
135 /// and types to emit.
136 bool DoneWritingDeclsAndTypes;
138 /// \brief Indicates that the AST contained compiler errors.
139 bool ASTHasCompilerErrors;
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;
145 /// \brief Stores a declaration or a type to be written to the AST file.
148 DeclOrType(Decl *D) : Stored(D), IsType(false) { }
149 DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
151 bool isType() const { return IsType; }
152 bool isDecl() const { return !IsType; }
154 QualType getType() const {
155 assert(isType() && "Not a type!");
156 return QualType::getFromOpaquePtr(Stored);
159 Decl *getDecl() const {
160 assert(isDecl() && "Not a decl!");
161 return static_cast<Decl *>(Stored);
169 /// \brief The declarations and types to emit.
170 std::queue<DeclOrType> DeclTypesToEmit;
172 /// \brief The first ID number we can use for our own declarations.
173 serialization::DeclID FirstDeclID;
175 /// \brief The decl ID that will be assigned to the next new decl.
176 serialization::DeclID NextDeclID;
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.
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;
186 /// \brief Offset of each declaration in the bitstream, indexed by
187 /// the declaration's ID.
188 std::vector<serialization::DeclOffset> DeclOffsets;
190 /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
191 typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
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;
199 typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
201 /// \brief Map from file SLocEntries to info about the file-level declarations
202 /// that it contains.
203 FileDeclIDsTy FileDeclIDs;
205 void associateDeclWithFile(const Decl *D, serialization::DeclID);
207 /// \brief The first ID number we can use for our own types.
208 serialization::TypeID FirstTypeID;
210 /// \brief The type ID that will be assigned to the next new type.
211 serialization::TypeID NextTypeID;
213 /// \brief Map that provides the ID numbers of each type within the
214 /// output stream, plus those deserialized from a chained PCH.
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.
221 /// Keys in the map never have const/volatile qualifiers.
224 /// \brief Offset of each type in the bitstream, indexed by
226 std::vector<uint32_t> TypeOffsets;
228 /// \brief The first ID number we can use for our own identifiers.
229 serialization::IdentID FirstIdentID;
231 /// \brief The identifier ID that will be assigned to the next new identifier.
232 serialization::IdentID NextIdentID;
234 /// \brief Map that provides the ID numbers of each identifier in
235 /// the output stream.
237 /// The ID numbers for identifiers are consecutive (in order of
238 /// discovery), starting at 1. An ID of zero refers to a NULL
240 llvm::MapVector<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
242 /// \brief The first ID number we can use for our own macros.
243 serialization::MacroID FirstMacroID;
245 /// \brief The identifier ID that will be assigned to the next new identifier.
246 serialization::MacroID NextMacroID;
248 /// \brief Map that provides the ID numbers of each macro.
249 llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
251 struct MacroInfoToEmitData {
252 const IdentifierInfo *Name;
254 serialization::MacroID ID;
256 /// \brief The macro infos to emit.
257 std::vector<MacroInfoToEmitData> MacroInfosToEmit;
259 llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
261 /// @name FlushStmt Caches
264 /// \brief Set of parent Stmts for the currently serializing sub-stmt.
265 llvm::DenseSet<Stmt *> ParentStmts;
267 /// \brief Offsets of sub-stmts already serialized. The offset points
268 /// just after the stmt record.
269 llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
273 /// \brief Offsets of each of the identifier IDs into the identifier
275 std::vector<uint32_t> IdentifierOffsets;
277 /// \brief The first ID number we can use for our own submodules.
278 serialization::SubmoduleID FirstSubmoduleID;
280 /// \brief The submodule ID that will be assigned to the next new submodule.
281 serialization::SubmoduleID NextSubmoduleID;
283 /// \brief The first ID number we can use for our own selectors.
284 serialization::SelectorID FirstSelectorID;
286 /// \brief The selector ID that will be assigned to the next new selector.
287 serialization::SelectorID NextSelectorID;
289 /// \brief Map that provides the ID numbers of each Selector.
290 llvm::MapVector<Selector, serialization::SelectorID> SelectorIDs;
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;
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;
301 /// \brief Cache of indices of anonymous declarations within their lexical
303 llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
305 /// An update to a Decl.
307 /// A DeclUpdateKind.
315 const Attr *Attribute;
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) {}
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);
338 unsigned getNumber() const { return Val; }
339 Module *getModule() const { return Mod; }
340 const Attr *getAttr() const { return Attribute; }
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;
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;
354 /// \brief Declarations encountered that might be external
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
365 SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
367 /// \brief DeclContexts that have received extensions since their serialized
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
374 llvm::SmallSetVector<const DeclContext *, 16> UpdatedDeclContexts;
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;
381 /// \brief The set of Objective-C class that have categories we
382 /// should serialize.
383 llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
385 /// \brief The set of declarations that may have redeclaration chains that
386 /// need to be serialized.
387 llvm::SmallVector<const Decl *, 16> Redeclarations;
389 /// \brief A cache of the first local declaration for "interesting"
390 /// redeclaration chains.
391 llvm::DenseMap<const Decl *, const Decl *> FirstLocalDeclCache;
393 /// \brief Mapping from SwitchCase statements to IDs.
394 llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
396 /// \brief The number of statements written to the AST file.
397 unsigned NumStatements;
399 /// \brief The number of macros written to the AST file.
402 /// \brief The number of lexical declcontexts written to the AST
404 unsigned NumLexicalDeclContexts;
406 /// \brief The number of visible declcontexts written to the AST
408 unsigned NumVisibleDeclContexts;
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;
414 /// \brief A list of the module file extension writers.
415 std::vector<std::unique_ptr<ModuleFileExtensionWriter>>
416 ModuleFileExtensionWriters;
418 /// \brief Retrieve or create a submodule ID for this module.
419 unsigned getSubmoduleID(Module *Mod);
421 /// \brief Write the given subexpression to the bitstream.
422 void WriteSubStmt(Stmt *S);
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,
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);
436 void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
439 unsigned TypeExtQualAbbrev;
440 unsigned TypeFunctionProtoAbbrev;
441 void WriteTypeAbbrevs();
442 void WriteType(QualType T);
444 bool isLookupResultExternal(StoredDeclsList &Result, DeclContext *DC);
445 bool isLookupResultEntirelyExternal(StoredDeclsList &Result, DeclContext *DC);
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,
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);
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;
485 unsigned DeclRefExprAbbrev;
486 unsigned CharacterLiteralAbbrev;
487 unsigned IntegerLiteralAbbrev;
488 unsigned ExprImplicitCastAbbrev;
490 void WriteDeclAbbrevs();
491 void WriteDecl(ASTContext &Context, Decl *D);
493 uint64_t WriteASTCore(Sema &SemaRef,
494 StringRef isysroot, const std::string &OutputFile,
495 Module *WritingModule);
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;
505 const LangOptions &getLangOpts() const;
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;
512 /// \brief Write a precompiled header for the given semantic analysis.
514 /// \param SemaRef a reference to the semantic analysis object that processed
515 /// the AST to be written into the precompiled header.
517 /// \param WritingModule The module that we are writing. If null, we are
518 /// writing a precompiled header.
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.
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);
530 /// \brief Emit a token.
531 void AddToken(const Token &Tok, RecordDataImpl &Record);
533 /// \brief Emit a source location.
534 void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
536 /// \brief Emit a source range.
537 void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
539 /// \brief Emit a reference to an identifier.
540 void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
542 /// \brief Get the unique number used to refer to the given selector.
543 serialization::SelectorID getSelectorRef(Selector Sel);
545 /// \brief Get the unique number used to refer to the given identifier.
546 serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
548 /// \brief Get the unique number used to refer to the given macro.
549 serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
551 /// \brief Determine the ID of an already-emitted macro.
552 serialization::MacroID getMacroID(MacroInfo *MI);
554 uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
556 /// \brief Emit a reference to a type.
557 void AddTypeRef(QualType T, RecordDataImpl &Record);
559 /// \brief Force a type to be emitted and get its ID.
560 serialization::TypeID GetOrCreateTypeID(QualType T);
562 /// \brief Determine the type ID of an already-emitted type.
563 serialization::TypeID getTypeID(QualType T) const;
565 /// \brief Find the first local declaration of a given local redeclarable
567 const Decl *getFirstLocalDecl(const Decl *D);
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())
575 auto I = DeclIDs.find(D);
576 return (I == DeclIDs.end() ||
577 I->second >= serialization::NUM_PREDEF_DECL_IDS);
580 /// \brief Emit a reference to a declaration.
581 void AddDeclRef(const Decl *D, RecordDataImpl &Record);
584 /// \brief Force a declaration to be emitted and get its ID.
585 serialization::DeclID GetDeclRef(const Decl *D);
587 /// \brief Determine the declaration ID of an already-emitted
589 serialization::DeclID getDeclID(const Decl *D);
591 unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
593 /// \brief Add a string to the given record.
594 void AddString(StringRef Str, RecordDataImpl &Record);
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);
600 /// \brief Add a path to the given record.
601 void AddPath(StringRef Path, RecordDataImpl &Record);
603 /// \brief Emit the current record with the given path as a blob.
604 void EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
607 /// \brief Add a version tuple to the given record
608 void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
610 /// \brief Infer the submodule ID that contains an entity at the given
612 serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
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);
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);
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);
627 /// \brief Record an ID for the given switch-case statement.
628 unsigned RecordSwitchCaseID(SwitchCase *S);
630 /// \brief Retrieve the ID for the given switch-case statement.
631 unsigned getSwitchCaseID(SwitchCase *S);
633 void ClearSwitchCaseIDs();
635 unsigned getTypeExtQualAbbrev() const {
636 return TypeExtQualAbbrev;
638 unsigned getTypeFunctionProtoAbbrev() const {
639 return TypeFunctionProtoAbbrev;
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; }
651 unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
652 unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
653 unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
654 unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
656 bool hasChain() const { return Chain; }
657 ASTReader *getChain() const { return Chain; }
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;
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;
702 /// \brief An object for streaming information to a record.
703 class ASTRecordWriter {
705 ASTWriter::RecordDataImpl *Record;
707 /// \brief Statements that we've encountered while serializing a
708 /// declaration or type.
709 SmallVector<Stmt *, 16> StmtsToEmit;
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;
716 /// \brief Flush all of the statements and expressions that have
717 /// been added to the queue via AddStmt().
719 void FlushSubStmts();
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");
727 StoredOffset = MyOffset - StoredOffset;
729 OffsetIndices.clear();
733 /// Construct a ASTRecordWriter that uses the default encoding scheme.
734 ASTRecordWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
735 : Writer(&Writer), Record(&Record) {}
737 /// Construct a ASTRecordWriter that uses the same encoding scheme as another
739 ASTRecordWriter(ASTRecordWriter &Parent, ASTWriter::RecordDataImpl &Record)
740 : Writer(Parent.Writer), Record(&Record) {}
742 /// Copying an ASTRecordWriter is almost certainly a bug.
743 ASTRecordWriter(const ASTRecordWriter&) = delete;
744 void operator=(const ASTRecordWriter&) = delete;
746 /// \brief Extract the underlying record storage.
747 ASTWriter::RecordDataImpl &getRecordData() const { return *Record; }
749 /// \brief Minimal vector-like interface.
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);
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]; }
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);
772 /// \brief Emit the record to the stream, preceded by its substatements.
773 uint64_t EmitStmt(unsigned Code, unsigned Abbrev = 0) {
775 PrepareToEmit(Writer->Stream.GetCurrentBitNo());
776 Writer->Stream.EmitRecord(Code, *Record, Abbrev);
777 return Writer->Stream.GetCurrentBitNo();
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);
787 /// \brief Add the given statement or expression to the queue of
788 /// statements to emit.
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);
798 /// \brief Add a definition for the given function to the queue of statements
800 void AddFunctionDefinition(const FunctionDecl *FD);
802 /// \brief Emit a source location.
803 void AddSourceLocation(SourceLocation Loc) {
804 return Writer->AddSourceLocation(Loc, *Record);
807 /// \brief Emit a source range.
808 void AddSourceRange(SourceRange Range) {
809 return Writer->AddSourceRange(Range, *Record);
812 /// \brief Emit an integral value.
813 void AddAPInt(const llvm::APInt &Value);
815 /// \brief Emit a signed integral value.
816 void AddAPSInt(const llvm::APSInt &Value);
818 /// \brief Emit a floating-point value.
819 void AddAPFloat(const llvm::APFloat &Value);
821 /// \brief Emit a reference to an identifier.
822 void AddIdentifierRef(const IdentifierInfo *II) {
823 return Writer->AddIdentifierRef(II, *Record);
826 /// \brief Emit a Selector (which is a smart pointer reference).
827 void AddSelectorRef(Selector S);
829 /// \brief Emit a CXXTemporary.
830 void AddCXXTemporary(const CXXTemporary *Temp);
832 /// \brief Emit a C++ base specifier.
833 void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base);
835 /// \brief Emit a set of C++ base specifiers.
836 void AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases);
838 /// \brief Emit a reference to a type.
839 void AddTypeRef(QualType T) {
840 return Writer->AddTypeRef(T, *Record);
843 /// \brief Emits a reference to a declarator info.
844 void AddTypeSourceInfo(TypeSourceInfo *TInfo);
846 /// \brief Emits a type with source-location information.
847 void AddTypeLoc(TypeLoc TL);
849 /// \brief Emits a template argument location info.
850 void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
851 const TemplateArgumentLocInfo &Arg);
853 /// \brief Emits a template argument location.
854 void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg);
856 /// \brief Emits an AST template argument list info.
857 void AddASTTemplateArgumentListInfo(
858 const ASTTemplateArgumentListInfo *ASTTemplArgList);
860 /// \brief Emit a reference to a declaration.
861 void AddDeclRef(const Decl *D) {
862 return Writer->AddDeclRef(D, *Record);
865 /// \brief Emit a declaration name.
866 void AddDeclarationName(DeclarationName Name);
868 void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
869 DeclarationName Name);
870 void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
872 void AddQualifierInfo(const QualifierInfo &Info);
874 /// \brief Emit a nested name specifier.
875 void AddNestedNameSpecifier(NestedNameSpecifier *NNS);
877 /// \brief Emit a nested name specifier with source-location information.
878 void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
880 /// \brief Emit a template name.
881 void AddTemplateName(TemplateName Name);
883 /// \brief Emit a template argument.
884 void AddTemplateArgument(const TemplateArgument &Arg);
886 /// \brief Emit a template parameter list.
887 void AddTemplateParameterList(const TemplateParameterList *TemplateParams);
889 /// \brief Emit a template argument list.
890 void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs);
892 /// \brief Emit a UnresolvedSet structure.
893 void AddUnresolvedSet(const ASTUnresolvedSet &Set);
895 /// \brief Emit a CXXCtorInitializer array.
896 void AddCXXCtorInitializers(ArrayRef<CXXCtorInitializer*> CtorInits);
898 void AddCXXDefinitionData(const CXXRecordDecl *D);
900 /// \brief Emit a string.
901 void AddString(StringRef Str) {
902 return Writer->AddString(Str, *Record);
905 /// \brief Emit a path.
906 void AddPath(StringRef Path) {
907 return Writer->AddPath(Path, *Record);
910 /// \brief Emit a version tuple.
911 void AddVersionTuple(const VersionTuple &Version) {
912 return Writer->AddVersionTuple(Version, *Record);
915 /// \brief Emit a list of attributes.
916 void AddAttributes(ArrayRef<const Attr*> Attrs);
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;
926 std::shared_ptr<PCHBuffer> Buffer;
927 llvm::BitstreamWriter Stream;
929 bool AllowASTWithErrors;
932 ASTWriter &getWriter() { return Writer; }
933 const ASTWriter &getWriter() const { return Writer; }
934 SmallVectorImpl<char> &getPCH() const { return Buffer->Data; }
938 const Preprocessor &PP, StringRef OutputFile,
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; }
952 } // end namespace clang