clang API Documentation

ASTWriter.h
Go to the documentation of this file.
00001 //===--- ASTWriter.h - AST File Writer --------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ASTWriter class, which writes an AST file
00011 //  containing a serialized representation of a translation unit.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #ifndef LLVM_CLANG_SERIALIZATION_ASTWRITER_H
00015 #define LLVM_CLANG_SERIALIZATION_ASTWRITER_H
00016 
00017 #include "clang/AST/ASTMutationListener.h"
00018 #include "clang/AST/Decl.h"
00019 #include "clang/AST/DeclarationName.h"
00020 #include "clang/AST/TemplateBase.h"
00021 #include "clang/Sema/SemaConsumer.h"
00022 #include "clang/Serialization/ASTBitCodes.h"
00023 #include "clang/Serialization/ASTDeserializationListener.h"
00024 #include "llvm/ADT/DenseMap.h"
00025 #include "llvm/ADT/DenseSet.h"
00026 #include "llvm/ADT/MapVector.h"
00027 #include "llvm/ADT/SetVector.h"
00028 #include "llvm/ADT/SmallPtrSet.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/Bitcode/BitstreamWriter.h"
00031 #include <map>
00032 #include <queue>
00033 #include <vector>
00034 
00035 namespace llvm {
00036   class APFloat;
00037   class APInt;
00038   class BitstreamWriter;
00039 }
00040 
00041 namespace clang {
00042 
00043 class ASTContext;
00044 class NestedNameSpecifier;
00045 class CXXBaseSpecifier;
00046 class CXXCtorInitializer;
00047 class FileEntry;
00048 class FPOptions;
00049 class HeaderSearch;
00050 class HeaderSearchOptions;
00051 class IdentifierResolver;
00052 class MacroDefinition;
00053 class MacroDirective;
00054 class MacroInfo;
00055 class OpaqueValueExpr;
00056 class OpenCLOptions;
00057 class ASTReader;
00058 class Module;
00059 class PreprocessedEntity;
00060 class PreprocessingRecord;
00061 class Preprocessor;
00062 class Sema;
00063 class SourceManager;
00064 class SwitchCase;
00065 class TargetInfo;
00066 class Token;
00067 class VersionTuple;
00068 class ASTUnresolvedSet;
00069 
00070 namespace SrcMgr { class SLocEntry; }
00071 
00072 /// \brief Writes an AST file containing the contents of a translation unit.
00073 ///
00074 /// The ASTWriter class produces a bitstream containing the serialized
00075 /// representation of a given abstract syntax tree and its supporting
00076 /// data structures. This bitstream can be de-serialized via an
00077 /// instance of the ASTReader class.
00078 class ASTWriter : public ASTDeserializationListener,
00079                   public ASTMutationListener {
00080 public:
00081   typedef SmallVector<uint64_t, 64> RecordData;
00082   typedef SmallVectorImpl<uint64_t> RecordDataImpl;
00083 
00084   friend class ASTDeclWriter;
00085   friend class ASTStmtWriter;
00086 private:
00087   /// \brief Map that provides the ID numbers of each type within the
00088   /// output stream, plus those deserialized from a chained PCH.
00089   ///
00090   /// The ID numbers of types are consecutive (in order of discovery)
00091   /// and start at 1. 0 is reserved for NULL. When types are actually
00092   /// stored in the stream, the ID number is shifted by 2 bits to
00093   /// allow for the const/volatile qualifiers.
00094   ///
00095   /// Keys in the map never have const/volatile qualifiers.
00096   typedef llvm::DenseMap<QualType, serialization::TypeIdx,
00097                          serialization::UnsafeQualTypeDenseMapInfo>
00098     TypeIdxMap;
00099 
00100   /// \brief The bitstream writer used to emit this precompiled header.
00101   llvm::BitstreamWriter &Stream;
00102 
00103   /// \brief The ASTContext we're writing.
00104   ASTContext *Context;
00105 
00106   /// \brief The preprocessor we're writing.
00107   Preprocessor *PP;
00108 
00109   /// \brief The reader of existing AST files, if we're chaining.
00110   ASTReader *Chain;
00111 
00112   /// \brief The module we're currently writing, if any.
00113   Module *WritingModule;
00114                     
00115   /// \brief Indicates when the AST writing is actively performing
00116   /// serialization, rather than just queueing updates.
00117   bool WritingAST;
00118 
00119   /// \brief Indicates that we are done serializing the collection of decls
00120   /// and types to emit.
00121   bool DoneWritingDeclsAndTypes;
00122 
00123   /// \brief Indicates that the AST contained compiler errors.
00124   bool ASTHasCompilerErrors;
00125 
00126   /// \brief Mapping from input file entries to the index into the
00127   /// offset table where information about that input file is stored.
00128   llvm::DenseMap<const FileEntry *, uint32_t> InputFileIDs;
00129 
00130   /// \brief Stores a declaration or a type to be written to the AST file.
00131   class DeclOrType {
00132   public:
00133     DeclOrType(Decl *D) : Stored(D), IsType(false) { }
00134     DeclOrType(QualType T) : Stored(T.getAsOpaquePtr()), IsType(true) { }
00135 
00136     bool isType() const { return IsType; }
00137     bool isDecl() const { return !IsType; }
00138 
00139     QualType getType() const {
00140       assert(isType() && "Not a type!");
00141       return QualType::getFromOpaquePtr(Stored);
00142     }
00143 
00144     Decl *getDecl() const {
00145       assert(isDecl() && "Not a decl!");
00146       return static_cast<Decl *>(Stored);
00147     }
00148 
00149   private:
00150     void *Stored;
00151     bool IsType;
00152   };
00153 
00154   /// \brief The declarations and types to emit.
00155   std::queue<DeclOrType> DeclTypesToEmit;
00156 
00157   /// \brief The first ID number we can use for our own declarations.
00158   serialization::DeclID FirstDeclID;
00159 
00160   /// \brief The decl ID that will be assigned to the next new decl.
00161   serialization::DeclID NextDeclID;
00162 
00163   /// \brief Map that provides the ID numbers of each declaration within
00164   /// the output stream, as well as those deserialized from a chained PCH.
00165   ///
00166   /// The ID numbers of declarations are consecutive (in order of
00167   /// discovery) and start at 2. 1 is reserved for the translation
00168   /// unit, while 0 is reserved for NULL.
00169   llvm::DenseMap<const Decl *, serialization::DeclID> DeclIDs;
00170 
00171   /// \brief Offset of each declaration in the bitstream, indexed by
00172   /// the declaration's ID.
00173   std::vector<serialization::DeclOffset> DeclOffsets;
00174 
00175   /// \brief Sorted (by file offset) vector of pairs of file offset/DeclID.
00176   typedef SmallVector<std::pair<unsigned, serialization::DeclID>, 64>
00177     LocDeclIDsTy;
00178   struct DeclIDInFileInfo {
00179     LocDeclIDsTy DeclIDs;
00180     /// \brief Set when the DeclIDs vectors from all files are joined, this
00181     /// indicates the index that this particular vector has in the global one.
00182     unsigned FirstDeclIndex;
00183   };
00184   typedef llvm::DenseMap<FileID, DeclIDInFileInfo *> FileDeclIDsTy;
00185 
00186   /// \brief Map from file SLocEntries to info about the file-level declarations
00187   /// that it contains.
00188   FileDeclIDsTy FileDeclIDs;
00189 
00190   void associateDeclWithFile(const Decl *D, serialization::DeclID);
00191 
00192   /// \brief The first ID number we can use for our own types.
00193   serialization::TypeID FirstTypeID;
00194 
00195   /// \brief The type ID that will be assigned to the next new type.
00196   serialization::TypeID NextTypeID;
00197 
00198   /// \brief Map that provides the ID numbers of each type within the
00199   /// output stream, plus those deserialized from a chained PCH.
00200   ///
00201   /// The ID numbers of types are consecutive (in order of discovery)
00202   /// and start at 1. 0 is reserved for NULL. When types are actually
00203   /// stored in the stream, the ID number is shifted by 2 bits to
00204   /// allow for the const/volatile qualifiers.
00205   ///
00206   /// Keys in the map never have const/volatile qualifiers.
00207   TypeIdxMap TypeIdxs;
00208 
00209   /// \brief Offset of each type in the bitstream, indexed by
00210   /// the type's ID.
00211   std::vector<uint32_t> TypeOffsets;
00212 
00213   /// \brief The first ID number we can use for our own identifiers.
00214   serialization::IdentID FirstIdentID;
00215 
00216   /// \brief The identifier ID that will be assigned to the next new identifier.
00217   serialization::IdentID NextIdentID;
00218 
00219   /// \brief Map that provides the ID numbers of each identifier in
00220   /// the output stream.
00221   ///
00222   /// The ID numbers for identifiers are consecutive (in order of
00223   /// discovery), starting at 1. An ID of zero refers to a NULL
00224   /// IdentifierInfo.
00225   llvm::DenseMap<const IdentifierInfo *, serialization::IdentID> IdentifierIDs;
00226 
00227   /// \brief The first ID number we can use for our own macros.
00228   serialization::MacroID FirstMacroID;
00229 
00230   /// \brief The identifier ID that will be assigned to the next new identifier.
00231   serialization::MacroID NextMacroID;
00232 
00233   /// \brief Map that provides the ID numbers of each macro.
00234   llvm::DenseMap<MacroInfo *, serialization::MacroID> MacroIDs;
00235 
00236   struct MacroInfoToEmitData {
00237     const IdentifierInfo *Name;
00238     MacroInfo *MI;
00239     serialization::MacroID ID;
00240   };
00241   /// \brief The macro infos to emit.
00242   std::vector<MacroInfoToEmitData> MacroInfosToEmit;
00243 
00244   llvm::DenseMap<const IdentifierInfo *, uint64_t> IdentMacroDirectivesOffsetMap;
00245 
00246   /// @name FlushStmt Caches
00247   /// @{
00248 
00249   /// \brief Set of parent Stmts for the currently serializing sub-stmt.
00250   llvm::DenseSet<Stmt *> ParentStmts;
00251 
00252   /// \brief Offsets of sub-stmts already serialized. The offset points
00253   /// just after the stmt record.
00254   llvm::DenseMap<Stmt *, uint64_t> SubStmtEntries;
00255 
00256   /// @}
00257 
00258   /// \brief Offsets of each of the identifier IDs into the identifier
00259   /// table.
00260   std::vector<uint32_t> IdentifierOffsets;
00261 
00262   /// \brief The first ID number we can use for our own submodules.
00263   serialization::SubmoduleID FirstSubmoduleID;
00264   
00265   /// \brief The submodule ID that will be assigned to the next new submodule.
00266   serialization::SubmoduleID NextSubmoduleID;
00267 
00268   /// \brief The first ID number we can use for our own selectors.
00269   serialization::SelectorID FirstSelectorID;
00270 
00271   /// \brief The selector ID that will be assigned to the next new selector.
00272   serialization::SelectorID NextSelectorID;
00273 
00274   /// \brief Map that provides the ID numbers of each Selector.
00275   llvm::DenseMap<Selector, serialization::SelectorID> SelectorIDs;
00276 
00277   /// \brief Offset of each selector within the method pool/selector
00278   /// table, indexed by the Selector ID (-1).
00279   std::vector<uint32_t> SelectorOffsets;
00280 
00281   /// \brief Mapping from macro definitions (as they occur in the preprocessing
00282   /// record) to the macro IDs.
00283   llvm::DenseMap<const MacroDefinition *, serialization::PreprocessedEntityID>
00284       MacroDefinitions;
00285 
00286   /// \brief Cache of indices of anonymous declarations within their lexical
00287   /// contexts.
00288   llvm::DenseMap<const Decl *, unsigned> AnonymousDeclarationNumbers;
00289 
00290   /// An update to a Decl.
00291   class DeclUpdate {
00292     /// A DeclUpdateKind.
00293     unsigned Kind;
00294     union {
00295       const Decl *Dcl;
00296       void *Type;
00297       unsigned Loc;
00298       unsigned Val;
00299     };
00300 
00301   public:
00302     DeclUpdate(unsigned Kind) : Kind(Kind), Dcl(nullptr) {}
00303     DeclUpdate(unsigned Kind, const Decl *Dcl) : Kind(Kind), Dcl(Dcl) {}
00304     DeclUpdate(unsigned Kind, QualType Type)
00305         : Kind(Kind), Type(Type.getAsOpaquePtr()) {}
00306     DeclUpdate(unsigned Kind, SourceLocation Loc)
00307         : Kind(Kind), Loc(Loc.getRawEncoding()) {}
00308     DeclUpdate(unsigned Kind, unsigned Val)
00309         : Kind(Kind), Val(Val) {}
00310 
00311     unsigned getKind() const { return Kind; }
00312     const Decl *getDecl() const { return Dcl; }
00313     QualType getType() const { return QualType::getFromOpaquePtr(Type); }
00314     SourceLocation getLoc() const {
00315       return SourceLocation::getFromRawEncoding(Loc);
00316     }
00317     unsigned getNumber() const { return Val; }
00318   };
00319 
00320   typedef SmallVector<DeclUpdate, 1> UpdateRecord;
00321   typedef llvm::DenseMap<const Decl *, UpdateRecord> DeclUpdateMap;
00322   /// \brief Mapping from declarations that came from a chained PCH to the
00323   /// record containing modifications to them.
00324   DeclUpdateMap DeclUpdates;
00325 
00326   typedef llvm::DenseMap<Decl *, Decl *> FirstLatestDeclMap;
00327   /// \brief Map of first declarations from a chained PCH that point to the
00328   /// most recent declarations in another PCH.
00329   FirstLatestDeclMap FirstLatestDecls;
00330 
00331   /// \brief Declarations encountered that might be external
00332   /// definitions.
00333   ///
00334   /// We keep track of external definitions and other 'interesting' declarations
00335   /// as we are emitting declarations to the AST file. The AST file contains a
00336   /// separate record for these declarations, which are provided to the AST
00337   /// consumer by the AST reader. This is behavior is required to properly cope with,
00338   /// e.g., tentative variable definitions that occur within
00339   /// headers. The declarations themselves are stored as declaration
00340   /// IDs, since they will be written out to an EAGERLY_DESERIALIZED_DECLS
00341   /// record.
00342   SmallVector<uint64_t, 16> EagerlyDeserializedDecls;
00343 
00344   /// \brief DeclContexts that have received extensions since their serialized
00345   /// form.
00346   ///
00347   /// For namespaces, when we're chaining and encountering a namespace, we check
00348   /// if its primary namespace comes from the chain. If it does, we add the
00349   /// primary to this set, so that we can write out lexical content updates for
00350   /// it.
00351   llvm::SmallPtrSet<const DeclContext *, 16> UpdatedDeclContexts;
00352 
00353   /// \brief Keeps track of visible decls that were added in DeclContexts
00354   /// coming from another AST file.
00355   SmallVector<const Decl *, 16> UpdatingVisibleDecls;
00356 
00357   typedef llvm::SmallPtrSet<const Decl *, 16> DeclsToRewriteTy;
00358   /// \brief Decls that will be replaced in the current dependent AST file.
00359   DeclsToRewriteTy DeclsToRewrite;
00360 
00361   /// \brief The set of Objective-C class that have categories we
00362   /// should serialize.
00363   llvm::SetVector<ObjCInterfaceDecl *> ObjCClassesWithCategories;
00364                     
00365   struct ReplacedDeclInfo {
00366     serialization::DeclID ID;
00367     uint64_t Offset;
00368     unsigned Loc;
00369 
00370     ReplacedDeclInfo() : ID(0), Offset(0), Loc(0) {}
00371     ReplacedDeclInfo(serialization::DeclID ID, uint64_t Offset,
00372                      SourceLocation Loc)
00373       : ID(ID), Offset(Offset), Loc(Loc.getRawEncoding()) {}
00374   };
00375 
00376   /// \brief Decls that have been replaced in the current dependent AST file.
00377   ///
00378   /// When a decl changes fundamentally after being deserialized (this shouldn't
00379   /// happen, but the ObjC AST nodes are designed this way), it will be
00380   /// serialized again. In this case, it is registered here, so that the reader
00381   /// knows to read the updated version.
00382   SmallVector<ReplacedDeclInfo, 16> ReplacedDecls;
00383                  
00384   /// \brief The set of declarations that may have redeclaration chains that
00385   /// need to be serialized.
00386   llvm::SetVector<Decl *, SmallVector<Decl *, 4>,
00387                   llvm::SmallPtrSet<Decl *, 4> > Redeclarations;
00388                                       
00389   /// \brief Statements that we've encountered while serializing a
00390   /// declaration or type.
00391   SmallVector<Stmt *, 16> StmtsToEmit;
00392 
00393   /// \brief Statements collection to use for ASTWriter::AddStmt().
00394   /// It will point to StmtsToEmit unless it is overriden.
00395   SmallVector<Stmt *, 16> *CollectedStmts;
00396 
00397   /// \brief Mapping from SwitchCase statements to IDs.
00398   llvm::DenseMap<SwitchCase *, unsigned> SwitchCaseIDs;
00399 
00400   /// \brief The number of statements written to the AST file.
00401   unsigned NumStatements;
00402 
00403   /// \brief The number of macros written to the AST file.
00404   unsigned NumMacros;
00405 
00406   /// \brief The number of lexical declcontexts written to the AST
00407   /// file.
00408   unsigned NumLexicalDeclContexts;
00409 
00410   /// \brief The number of visible declcontexts written to the AST
00411   /// file.
00412   unsigned NumVisibleDeclContexts;
00413 
00414   /// \brief The offset of each CXXBaseSpecifier set within the AST.
00415   SmallVector<uint32_t, 4> CXXBaseSpecifiersOffsets;
00416 
00417   /// \brief The first ID number we can use for our own base specifiers.
00418   serialization::CXXBaseSpecifiersID FirstCXXBaseSpecifiersID;
00419 
00420   /// \brief The base specifiers ID that will be assigned to the next new
00421   /// set of C++ base specifiers.
00422   serialization::CXXBaseSpecifiersID NextCXXBaseSpecifiersID;
00423 
00424   /// \brief A set of C++ base specifiers that is queued to be written into the
00425   /// AST file.
00426   struct QueuedCXXBaseSpecifiers {
00427     QueuedCXXBaseSpecifiers() : ID(), Bases(), BasesEnd() { }
00428 
00429     QueuedCXXBaseSpecifiers(serialization::CXXBaseSpecifiersID ID,
00430                             CXXBaseSpecifier const *Bases,
00431                             CXXBaseSpecifier const *BasesEnd)
00432       : ID(ID), Bases(Bases), BasesEnd(BasesEnd) { }
00433 
00434     serialization::CXXBaseSpecifiersID ID;
00435     CXXBaseSpecifier const * Bases;
00436     CXXBaseSpecifier const * BasesEnd;
00437   };
00438 
00439   /// \brief Queue of C++ base specifiers to be written to the AST file,
00440   /// in the order they should be written.
00441   SmallVector<QueuedCXXBaseSpecifiers, 2> CXXBaseSpecifiersToWrite;
00442 
00443   /// \brief A mapping from each known submodule to its ID number, which will
00444   /// be a positive integer.
00445   llvm::DenseMap<Module *, unsigned> SubmoduleIDs;
00446                     
00447   /// \brief Retrieve or create a submodule ID for this module.
00448   unsigned getSubmoduleID(Module *Mod);
00449                     
00450   /// \brief Write the given subexpression to the bitstream.
00451   void WriteSubStmt(Stmt *S,
00452                     llvm::DenseMap<Stmt *, uint64_t> &SubStmtEntries,
00453                     llvm::DenseSet<Stmt *> &ParentStmts);
00454 
00455   void WriteBlockInfoBlock();
00456   void WriteControlBlock(Preprocessor &PP, ASTContext &Context,
00457                          StringRef isysroot, const std::string &OutputFile);
00458   void WriteInputFiles(SourceManager &SourceMgr,
00459                        HeaderSearchOptions &HSOpts,
00460                        StringRef isysroot,
00461                        bool Modules);
00462   void WriteSourceManagerBlock(SourceManager &SourceMgr,
00463                                const Preprocessor &PP,
00464                                StringRef isysroot);
00465   void WritePreprocessor(const Preprocessor &PP, bool IsModule);
00466   void WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot);
00467   void WritePreprocessorDetail(PreprocessingRecord &PPRec);
00468   void WriteSubmodules(Module *WritingModule);
00469                                         
00470   void WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
00471                                      bool isModule);
00472   void WriteCXXBaseSpecifiersOffsets();
00473 
00474   unsigned TypeExtQualAbbrev;
00475   unsigned TypeFunctionProtoAbbrev;
00476   void WriteTypeAbbrevs();
00477   void WriteType(QualType T);
00478 
00479   uint32_t GenerateNameLookupTable(const DeclContext *DC,
00480                                    llvm::SmallVectorImpl<char> &LookupTable);
00481   uint64_t WriteDeclContextLexicalBlock(ASTContext &Context, DeclContext *DC);
00482   uint64_t WriteDeclContextVisibleBlock(ASTContext &Context, DeclContext *DC);
00483   void WriteTypeDeclOffsets();
00484   void WriteFileDeclIDsMap();
00485   void WriteComments();
00486   void WriteSelectors(Sema &SemaRef);
00487   void WriteReferencedSelectorsPool(Sema &SemaRef);
00488   void WriteIdentifierTable(Preprocessor &PP, IdentifierResolver &IdResolver,
00489                             bool IsModule);
00490   void WriteAttributes(ArrayRef<const Attr*> Attrs, RecordDataImpl &Record);
00491   void WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord);
00492   void WriteDeclReplacementsBlock();
00493   void WriteDeclContextVisibleUpdate(const DeclContext *DC);
00494   void WriteFPPragmaOptions(const FPOptions &Opts);
00495   void WriteOpenCLExtensions(Sema &SemaRef);
00496   void WriteObjCCategories();
00497   void WriteRedeclarations();
00498   void WriteMergedDecls();
00499   void WriteLateParsedTemplates(Sema &SemaRef);
00500   void WriteOptimizePragmaOptions(Sema &SemaRef);
00501 
00502   unsigned DeclParmVarAbbrev;
00503   unsigned DeclContextLexicalAbbrev;
00504   unsigned DeclContextVisibleLookupAbbrev;
00505   unsigned UpdateVisibleAbbrev;
00506   unsigned DeclRecordAbbrev;
00507   unsigned DeclTypedefAbbrev;
00508   unsigned DeclVarAbbrev;
00509   unsigned DeclFieldAbbrev;
00510   unsigned DeclEnumAbbrev;
00511   unsigned DeclObjCIvarAbbrev;
00512   unsigned DeclCXXMethodAbbrev;
00513 
00514   unsigned DeclRefExprAbbrev;
00515   unsigned CharacterLiteralAbbrev;
00516   unsigned IntegerLiteralAbbrev;
00517   unsigned ExprImplicitCastAbbrev;
00518 
00519   void WriteDeclAbbrevs();
00520   void WriteDecl(ASTContext &Context, Decl *D);
00521   void AddFunctionDefinition(const FunctionDecl *FD, RecordData &Record);
00522 
00523   void WriteASTCore(Sema &SemaRef,
00524                     StringRef isysroot, const std::string &OutputFile,
00525                     Module *WritingModule);
00526 
00527 public:
00528   /// \brief Create a new precompiled header writer that outputs to
00529   /// the given bitstream.
00530   ASTWriter(llvm::BitstreamWriter &Stream);
00531   ~ASTWriter();
00532 
00533   /// \brief Write a precompiled header for the given semantic analysis.
00534   ///
00535   /// \param SemaRef a reference to the semantic analysis object that processed
00536   /// the AST to be written into the precompiled header.
00537   ///
00538   /// \param WritingModule The module that we are writing. If null, we are
00539   /// writing a precompiled header.
00540   ///
00541   /// \param isysroot if non-empty, write a relocatable file whose headers
00542   /// are relative to the given system root.
00543   void WriteAST(Sema &SemaRef,
00544                 const std::string &OutputFile,
00545                 Module *WritingModule, StringRef isysroot,
00546                 bool hasErrors = false);
00547 
00548   /// \brief Emit a token.
00549   void AddToken(const Token &Tok, RecordDataImpl &Record);
00550 
00551   /// \brief Emit a source location.
00552   void AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record);
00553 
00554   /// \brief Emit a source range.
00555   void AddSourceRange(SourceRange Range, RecordDataImpl &Record);
00556 
00557   /// \brief Emit an integral value.
00558   void AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record);
00559 
00560   /// \brief Emit a signed integral value.
00561   void AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record);
00562 
00563   /// \brief Emit a floating-point value.
00564   void AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record);
00565 
00566   /// \brief Emit a reference to an identifier.
00567   void AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record);
00568 
00569   /// \brief Emit a Selector (which is a smart pointer reference).
00570   void AddSelectorRef(Selector, RecordDataImpl &Record);
00571 
00572   /// \brief Emit a CXXTemporary.
00573   void AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record);
00574 
00575   /// \brief Emit a set of C++ base specifiers to the record.
00576   void AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
00577                                CXXBaseSpecifier const *BasesEnd,
00578                                RecordDataImpl &Record);
00579 
00580   /// \brief Get the unique number used to refer to the given selector.
00581   serialization::SelectorID getSelectorRef(Selector Sel);
00582 
00583   /// \brief Get the unique number used to refer to the given identifier.
00584   serialization::IdentID getIdentifierRef(const IdentifierInfo *II);
00585 
00586   /// \brief Get the unique number used to refer to the given macro.
00587   serialization::MacroID getMacroRef(MacroInfo *MI, const IdentifierInfo *Name);
00588 
00589   /// \brief Determine the ID of an already-emitted macro.
00590   serialization::MacroID getMacroID(MacroInfo *MI);
00591 
00592   uint64_t getMacroDirectivesOffset(const IdentifierInfo *Name);
00593 
00594   /// \brief Emit a reference to a type.
00595   void AddTypeRef(QualType T, RecordDataImpl &Record);
00596 
00597   /// \brief Force a type to be emitted and get its ID.
00598   serialization::TypeID GetOrCreateTypeID(QualType T);
00599 
00600   /// \brief Determine the type ID of an already-emitted type.
00601   serialization::TypeID getTypeID(QualType T) const;
00602 
00603   /// \brief Force a type to be emitted and get its index.
00604   serialization::TypeIdx GetOrCreateTypeIdx( QualType T);
00605 
00606   /// \brief Determine the type index of an already-emitted type.
00607   serialization::TypeIdx getTypeIdx(QualType T) const;
00608 
00609   /// \brief Emits a reference to a declarator info.
00610   void AddTypeSourceInfo(TypeSourceInfo *TInfo, RecordDataImpl &Record);
00611 
00612   /// \brief Emits a type with source-location information.
00613   void AddTypeLoc(TypeLoc TL, RecordDataImpl &Record);
00614 
00615   /// \brief Emits a template argument location info.
00616   void AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
00617                                   const TemplateArgumentLocInfo &Arg,
00618                                   RecordDataImpl &Record);
00619 
00620   /// \brief Emits a template argument location.
00621   void AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
00622                               RecordDataImpl &Record);
00623 
00624   /// \brief Emits an AST template argument list info.
00625   void AddASTTemplateArgumentListInfo(
00626                           const ASTTemplateArgumentListInfo *ASTTemplArgList,
00627                           RecordDataImpl &Record);
00628 
00629   /// \brief Emit a reference to a declaration.
00630   void AddDeclRef(const Decl *D, RecordDataImpl &Record);
00631 
00632 
00633   /// \brief Force a declaration to be emitted and get its ID.
00634   serialization::DeclID GetDeclRef(const Decl *D);
00635 
00636   /// \brief Determine the declaration ID of an already-emitted
00637   /// declaration.
00638   serialization::DeclID getDeclID(const Decl *D);
00639 
00640   /// \brief Emit a declaration name.
00641   void AddDeclarationName(DeclarationName Name, RecordDataImpl &Record);
00642   void AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
00643                              DeclarationName Name, RecordDataImpl &Record);
00644   void AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
00645                               RecordDataImpl &Record);
00646   unsigned getAnonymousDeclarationNumber(const NamedDecl *D);
00647 
00648   void AddQualifierInfo(const QualifierInfo &Info, RecordDataImpl &Record);
00649 
00650   /// \brief Emit a nested name specifier.
00651   void AddNestedNameSpecifier(NestedNameSpecifier *NNS, RecordDataImpl &Record);
00652 
00653   /// \brief Emit a nested name specifier with source-location information.
00654   void AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
00655                                  RecordDataImpl &Record);
00656 
00657   /// \brief Emit a template name.
00658   void AddTemplateName(TemplateName Name, RecordDataImpl &Record);
00659 
00660   /// \brief Emit a template argument.
00661   void AddTemplateArgument(const TemplateArgument &Arg, RecordDataImpl &Record);
00662 
00663   /// \brief Emit a template parameter list.
00664   void AddTemplateParameterList(const TemplateParameterList *TemplateParams,
00665                                 RecordDataImpl &Record);
00666 
00667   /// \brief Emit a template argument list.
00668   void AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
00669                                 RecordDataImpl &Record);
00670 
00671   /// \brief Emit a UnresolvedSet structure.
00672   void AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record);
00673 
00674   /// \brief Emit a C++ base specifier.
00675   void AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
00676                            RecordDataImpl &Record);
00677 
00678   /// \brief Emit a CXXCtorInitializer array.
00679   void AddCXXCtorInitializers(
00680                              const CXXCtorInitializer * const *CtorInitializers,
00681                              unsigned NumCtorInitializers,
00682                              RecordDataImpl &Record);
00683 
00684   void AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record);
00685 
00686   /// \brief Add a string to the given record.
00687   void AddString(StringRef Str, RecordDataImpl &Record);
00688 
00689   /// \brief Add a version tuple to the given record
00690   void AddVersionTuple(const VersionTuple &Version, RecordDataImpl &Record);
00691 
00692   /// \brief Mark a declaration context as needing an update.
00693   void AddUpdatedDeclContext(const DeclContext *DC);
00694 
00695   void RewriteDecl(const Decl *D) {
00696     DeclsToRewrite.insert(D);
00697   }
00698 
00699   bool isRewritten(const Decl *D) const {
00700     return DeclsToRewrite.count(D);
00701   }
00702 
00703   /// \brief Infer the submodule ID that contains an entity at the given
00704   /// source location.
00705   serialization::SubmoduleID inferSubmoduleIDFromLocation(SourceLocation Loc);
00706 
00707   /// \brief Retrieve a submodule ID for this module.
00708   /// Returns 0 If no ID has been associated with the module.
00709   unsigned getExistingSubmoduleID(Module *Mod) const;
00710 
00711   /// \brief Note that the identifier II occurs at the given offset
00712   /// within the identifier table.
00713   void SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset);
00714 
00715   /// \brief Note that the selector Sel occurs at the given offset
00716   /// within the method pool/selector table.
00717   void SetSelectorOffset(Selector Sel, uint32_t Offset);
00718 
00719   /// \brief Add the given statement or expression to the queue of
00720   /// statements to emit.
00721   ///
00722   /// This routine should be used when emitting types and declarations
00723   /// that have expressions as part of their formulation. Once the
00724   /// type or declaration has been written, call FlushStmts() to write
00725   /// the corresponding statements just after the type or
00726   /// declaration.
00727   void AddStmt(Stmt *S) {
00728       CollectedStmts->push_back(S);
00729   }
00730 
00731   /// \brief Flush all of the statements and expressions that have
00732   /// been added to the queue via AddStmt().
00733   void FlushStmts();
00734 
00735   /// \brief Flush all of the C++ base specifier sets that have been added
00736   /// via \c AddCXXBaseSpecifiersRef().
00737   void FlushCXXBaseSpecifiers();
00738 
00739   /// \brief Record an ID for the given switch-case statement.
00740   unsigned RecordSwitchCaseID(SwitchCase *S);
00741 
00742   /// \brief Retrieve the ID for the given switch-case statement.
00743   unsigned getSwitchCaseID(SwitchCase *S);
00744 
00745   void ClearSwitchCaseIDs();
00746 
00747   unsigned getTypeExtQualAbbrev() const {
00748     return TypeExtQualAbbrev;
00749   }
00750   unsigned getTypeFunctionProtoAbbrev() const {
00751     return TypeFunctionProtoAbbrev;
00752   }
00753 
00754   unsigned getDeclParmVarAbbrev() const { return DeclParmVarAbbrev; }
00755   unsigned getDeclRecordAbbrev() const { return DeclRecordAbbrev; }
00756   unsigned getDeclTypedefAbbrev() const { return DeclTypedefAbbrev; }
00757   unsigned getDeclVarAbbrev() const { return DeclVarAbbrev; }
00758   unsigned getDeclFieldAbbrev() const { return DeclFieldAbbrev; }
00759   unsigned getDeclEnumAbbrev() const { return DeclEnumAbbrev; }
00760   unsigned getDeclObjCIvarAbbrev() const { return DeclObjCIvarAbbrev; }
00761   unsigned getDeclCXXMethodAbbrev() const { return DeclCXXMethodAbbrev; }
00762 
00763   unsigned getDeclRefExprAbbrev() const { return DeclRefExprAbbrev; }
00764   unsigned getCharacterLiteralAbbrev() const { return CharacterLiteralAbbrev; }
00765   unsigned getIntegerLiteralAbbrev() const { return IntegerLiteralAbbrev; }
00766   unsigned getExprImplicitCastAbbrev() const { return ExprImplicitCastAbbrev; }
00767 
00768   bool hasChain() const { return Chain; }
00769 
00770   // ASTDeserializationListener implementation
00771   void ReaderInitialized(ASTReader *Reader) override;
00772   void IdentifierRead(serialization::IdentID ID, IdentifierInfo *II) override;
00773   void MacroRead(serialization::MacroID ID, MacroInfo *MI) override;
00774   void TypeRead(serialization::TypeIdx Idx, QualType T) override;
00775   void SelectorRead(serialization::SelectorID ID, Selector Sel) override;
00776   void MacroDefinitionRead(serialization::PreprocessedEntityID ID,
00777                            MacroDefinition *MD) override;
00778   void ModuleRead(serialization::SubmoduleID ID, Module *Mod) override;
00779 
00780   // ASTMutationListener implementation.
00781   void CompletedTagDefinition(const TagDecl *D) override;
00782   void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
00783   void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
00784   void AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
00785                              const ClassTemplateSpecializationDecl *D) override;
00786   void AddedCXXTemplateSpecialization(const VarTemplateDecl *TD,
00787                                const VarTemplateSpecializationDecl *D) override;
00788   void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
00789                                       const FunctionDecl *D) override;
00790   void ResolvedExceptionSpec(const FunctionDecl *FD) override;
00791   void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override;
00792   void CompletedImplicitDefinition(const FunctionDecl *D) override;
00793   void StaticDataMemberInstantiated(const VarDecl *D) override;
00794   void FunctionDefinitionInstantiated(const FunctionDecl *D) override;
00795   void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
00796                                     const ObjCInterfaceDecl *IFD) override;
00797   void AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
00798                                     const ObjCPropertyDecl *OrigProp,
00799                                     const ObjCCategoryDecl *ClassExt) override;
00800   void DeclarationMarkedUsed(const Decl *D) override;
00801   void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override;
00802 };
00803 
00804 /// \brief AST and semantic-analysis consumer that generates a
00805 /// precompiled header from the parsed source code.
00806 class PCHGenerator : public SemaConsumer {
00807   const Preprocessor &PP;
00808   std::string OutputFile;
00809   clang::Module *Module;
00810   std::string isysroot;
00811   raw_ostream *Out;
00812   Sema *SemaPtr;
00813   SmallVector<char, 128> Buffer;
00814   llvm::BitstreamWriter Stream;
00815   ASTWriter Writer;
00816   bool AllowASTWithErrors;
00817   bool HasEmittedPCH;
00818 
00819 protected:
00820   ASTWriter &getWriter() { return Writer; }
00821   const ASTWriter &getWriter() const { return Writer; }
00822 
00823 public:
00824   PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
00825                clang::Module *Module,
00826                StringRef isysroot, raw_ostream *Out,
00827                bool AllowASTWithErrors = false);
00828   ~PCHGenerator();
00829   void InitializeSema(Sema &S) override { SemaPtr = &S; }
00830   void HandleTranslationUnit(ASTContext &Ctx) override;
00831   ASTMutationListener *GetASTMutationListener() override;
00832   ASTDeserializationListener *GetASTDeserializationListener() override;
00833 
00834   bool hasEmittedPCH() const { return HasEmittedPCH; }
00835 };
00836 
00837 } // end namespace clang
00838 
00839 #endif