clang API Documentation

ASTWriter.cpp
Go to the documentation of this file.
00001 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
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 AST files.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Serialization/ASTWriter.h"
00015 #include "ASTCommon.h"
00016 #include "clang/Sema/Sema.h"
00017 #include "clang/Sema/IdentifierResolver.h"
00018 #include "clang/AST/ASTContext.h"
00019 #include "clang/AST/Decl.h"
00020 #include "clang/AST/DeclContextInternals.h"
00021 #include "clang/AST/DeclTemplate.h"
00022 #include "clang/AST/DeclFriend.h"
00023 #include "clang/AST/Expr.h"
00024 #include "clang/AST/ExprCXX.h"
00025 #include "clang/AST/Type.h"
00026 #include "clang/AST/TypeLocVisitor.h"
00027 #include "clang/Serialization/ASTReader.h"
00028 #include "clang/Lex/MacroInfo.h"
00029 #include "clang/Lex/PreprocessingRecord.h"
00030 #include "clang/Lex/Preprocessor.h"
00031 #include "clang/Lex/HeaderSearch.h"
00032 #include "clang/Basic/FileManager.h"
00033 #include "clang/Basic/FileSystemStatCache.h"
00034 #include "clang/Basic/OnDiskHashTable.h"
00035 #include "clang/Basic/SourceManager.h"
00036 #include "clang/Basic/SourceManagerInternals.h"
00037 #include "clang/Basic/TargetInfo.h"
00038 #include "clang/Basic/Version.h"
00039 #include "clang/Basic/VersionTuple.h"
00040 #include "llvm/ADT/APFloat.h"
00041 #include "llvm/ADT/APInt.h"
00042 #include "llvm/ADT/StringExtras.h"
00043 #include "llvm/Bitcode/BitstreamWriter.h"
00044 #include "llvm/Support/FileSystem.h"
00045 #include "llvm/Support/MemoryBuffer.h"
00046 #include "llvm/Support/Path.h"
00047 #include <algorithm>
00048 #include <cstdio>
00049 #include <string.h>
00050 #include <utility>
00051 using namespace clang;
00052 using namespace clang::serialization;
00053 
00054 template <typename T, typename Allocator>
00055 static StringRef data(const std::vector<T, Allocator> &v) {
00056   if (v.empty()) return StringRef();
00057   return StringRef(reinterpret_cast<const char*>(&v[0]),
00058                          sizeof(T) * v.size());
00059 }
00060 
00061 template <typename T>
00062 static StringRef data(const SmallVectorImpl<T> &v) {
00063   return StringRef(reinterpret_cast<const char*>(v.data()),
00064                          sizeof(T) * v.size());
00065 }
00066 
00067 //===----------------------------------------------------------------------===//
00068 // Type serialization
00069 //===----------------------------------------------------------------------===//
00070 
00071 namespace {
00072   class ASTTypeWriter {
00073     ASTWriter &Writer;
00074     ASTWriter::RecordDataImpl &Record;
00075 
00076   public:
00077     /// \brief Type code that corresponds to the record generated.
00078     TypeCode Code;
00079 
00080     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
00081       : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
00082 
00083     void VisitArrayType(const ArrayType *T);
00084     void VisitFunctionType(const FunctionType *T);
00085     void VisitTagType(const TagType *T);
00086 
00087 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
00088 #define ABSTRACT_TYPE(Class, Base)
00089 #include "clang/AST/TypeNodes.def"
00090   };
00091 }
00092 
00093 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
00094   llvm_unreachable("Built-in types are never serialized");
00095 }
00096 
00097 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
00098   Writer.AddTypeRef(T->getElementType(), Record);
00099   Code = TYPE_COMPLEX;
00100 }
00101 
00102 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
00103   Writer.AddTypeRef(T->getPointeeType(), Record);
00104   Code = TYPE_POINTER;
00105 }
00106 
00107 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
00108   Writer.AddTypeRef(T->getPointeeType(), Record);
00109   Code = TYPE_BLOCK_POINTER;
00110 }
00111 
00112 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
00113   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
00114   Record.push_back(T->isSpelledAsLValue());
00115   Code = TYPE_LVALUE_REFERENCE;
00116 }
00117 
00118 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
00119   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
00120   Code = TYPE_RVALUE_REFERENCE;
00121 }
00122 
00123 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
00124   Writer.AddTypeRef(T->getPointeeType(), Record);
00125   Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
00126   Code = TYPE_MEMBER_POINTER;
00127 }
00128 
00129 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
00130   Writer.AddTypeRef(T->getElementType(), Record);
00131   Record.push_back(T->getSizeModifier()); // FIXME: stable values
00132   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
00133 }
00134 
00135 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
00136   VisitArrayType(T);
00137   Writer.AddAPInt(T->getSize(), Record);
00138   Code = TYPE_CONSTANT_ARRAY;
00139 }
00140 
00141 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
00142   VisitArrayType(T);
00143   Code = TYPE_INCOMPLETE_ARRAY;
00144 }
00145 
00146 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
00147   VisitArrayType(T);
00148   Writer.AddSourceLocation(T->getLBracketLoc(), Record);
00149   Writer.AddSourceLocation(T->getRBracketLoc(), Record);
00150   Writer.AddStmt(T->getSizeExpr());
00151   Code = TYPE_VARIABLE_ARRAY;
00152 }
00153 
00154 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
00155   Writer.AddTypeRef(T->getElementType(), Record);
00156   Record.push_back(T->getNumElements());
00157   Record.push_back(T->getVectorKind());
00158   Code = TYPE_VECTOR;
00159 }
00160 
00161 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
00162   VisitVectorType(T);
00163   Code = TYPE_EXT_VECTOR;
00164 }
00165 
00166 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
00167   Writer.AddTypeRef(T->getResultType(), Record);
00168   FunctionType::ExtInfo C = T->getExtInfo();
00169   Record.push_back(C.getNoReturn());
00170   Record.push_back(C.getHasRegParm());
00171   Record.push_back(C.getRegParm());
00172   // FIXME: need to stabilize encoding of calling convention...
00173   Record.push_back(C.getCC());
00174   Record.push_back(C.getProducesResult());
00175 }
00176 
00177 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
00178   VisitFunctionType(T);
00179   Code = TYPE_FUNCTION_NO_PROTO;
00180 }
00181 
00182 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
00183   VisitFunctionType(T);
00184   Record.push_back(T->getNumArgs());
00185   for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I)
00186     Writer.AddTypeRef(T->getArgType(I), Record);
00187   Record.push_back(T->isVariadic());
00188   Record.push_back(T->hasTrailingReturn());
00189   Record.push_back(T->getTypeQuals());
00190   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
00191   Record.push_back(T->getExceptionSpecType());
00192   if (T->getExceptionSpecType() == EST_Dynamic) {
00193     Record.push_back(T->getNumExceptions());
00194     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
00195       Writer.AddTypeRef(T->getExceptionType(I), Record);
00196   } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
00197     Writer.AddStmt(T->getNoexceptExpr());
00198   } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
00199     Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
00200     Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
00201   }
00202   Code = TYPE_FUNCTION_PROTO;
00203 }
00204 
00205 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
00206   Writer.AddDeclRef(T->getDecl(), Record);
00207   Code = TYPE_UNRESOLVED_USING;
00208 }
00209 
00210 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
00211   Writer.AddDeclRef(T->getDecl(), Record);
00212   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
00213   Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
00214   Code = TYPE_TYPEDEF;
00215 }
00216 
00217 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
00218   Writer.AddStmt(T->getUnderlyingExpr());
00219   Code = TYPE_TYPEOF_EXPR;
00220 }
00221 
00222 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
00223   Writer.AddTypeRef(T->getUnderlyingType(), Record);
00224   Code = TYPE_TYPEOF;
00225 }
00226 
00227 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
00228   Writer.AddTypeRef(T->getUnderlyingType(), Record);
00229   Writer.AddStmt(T->getUnderlyingExpr());
00230   Code = TYPE_DECLTYPE;
00231 }
00232 
00233 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
00234   Writer.AddTypeRef(T->getBaseType(), Record);
00235   Writer.AddTypeRef(T->getUnderlyingType(), Record);
00236   Record.push_back(T->getUTTKind());
00237   Code = TYPE_UNARY_TRANSFORM;
00238 }
00239 
00240 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
00241   Writer.AddTypeRef(T->getDeducedType(), Record);
00242   Code = TYPE_AUTO;
00243 }
00244 
00245 void ASTTypeWriter::VisitTagType(const TagType *T) {
00246   Record.push_back(T->isDependentType());
00247   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
00248   assert(!T->isBeingDefined() &&
00249          "Cannot serialize in the middle of a type definition");
00250 }
00251 
00252 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
00253   VisitTagType(T);
00254   Code = TYPE_RECORD;
00255 }
00256 
00257 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
00258   VisitTagType(T);
00259   Code = TYPE_ENUM;
00260 }
00261 
00262 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
00263   Writer.AddTypeRef(T->getModifiedType(), Record);
00264   Writer.AddTypeRef(T->getEquivalentType(), Record);
00265   Record.push_back(T->getAttrKind());
00266   Code = TYPE_ATTRIBUTED;
00267 }
00268 
00269 void
00270 ASTTypeWriter::VisitSubstTemplateTypeParmType(
00271                                         const SubstTemplateTypeParmType *T) {
00272   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
00273   Writer.AddTypeRef(T->getReplacementType(), Record);
00274   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
00275 }
00276 
00277 void
00278 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
00279                                       const SubstTemplateTypeParmPackType *T) {
00280   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
00281   Writer.AddTemplateArgument(T->getArgumentPack(), Record);
00282   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
00283 }
00284 
00285 void
00286 ASTTypeWriter::VisitTemplateSpecializationType(
00287                                        const TemplateSpecializationType *T) {
00288   Record.push_back(T->isDependentType());
00289   Writer.AddTemplateName(T->getTemplateName(), Record);
00290   Record.push_back(T->getNumArgs());
00291   for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
00292          ArgI != ArgE; ++ArgI)
00293     Writer.AddTemplateArgument(*ArgI, Record);
00294   Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
00295                     T->isCanonicalUnqualified() ? QualType()
00296                                                 : T->getCanonicalTypeInternal(),
00297                     Record);
00298   Code = TYPE_TEMPLATE_SPECIALIZATION;
00299 }
00300 
00301 void
00302 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
00303   VisitArrayType(T);
00304   Writer.AddStmt(T->getSizeExpr());
00305   Writer.AddSourceRange(T->getBracketsRange(), Record);
00306   Code = TYPE_DEPENDENT_SIZED_ARRAY;
00307 }
00308 
00309 void
00310 ASTTypeWriter::VisitDependentSizedExtVectorType(
00311                                         const DependentSizedExtVectorType *T) {
00312   // FIXME: Serialize this type (C++ only)
00313   llvm_unreachable("Cannot serialize dependent sized extended vector types");
00314 }
00315 
00316 void
00317 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
00318   Record.push_back(T->getDepth());
00319   Record.push_back(T->getIndex());
00320   Record.push_back(T->isParameterPack());
00321   Writer.AddDeclRef(T->getDecl(), Record);
00322   Code = TYPE_TEMPLATE_TYPE_PARM;
00323 }
00324 
00325 void
00326 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
00327   Record.push_back(T->getKeyword());
00328   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
00329   Writer.AddIdentifierRef(T->getIdentifier(), Record);
00330   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
00331                                                 : T->getCanonicalTypeInternal(),
00332                     Record);
00333   Code = TYPE_DEPENDENT_NAME;
00334 }
00335 
00336 void
00337 ASTTypeWriter::VisitDependentTemplateSpecializationType(
00338                                 const DependentTemplateSpecializationType *T) {
00339   Record.push_back(T->getKeyword());
00340   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
00341   Writer.AddIdentifierRef(T->getIdentifier(), Record);
00342   Record.push_back(T->getNumArgs());
00343   for (DependentTemplateSpecializationType::iterator
00344          I = T->begin(), E = T->end(); I != E; ++I)
00345     Writer.AddTemplateArgument(*I, Record);
00346   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
00347 }
00348 
00349 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
00350   Writer.AddTypeRef(T->getPattern(), Record);
00351   if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions())
00352     Record.push_back(*NumExpansions + 1);
00353   else
00354     Record.push_back(0);
00355   Code = TYPE_PACK_EXPANSION;
00356 }
00357 
00358 void ASTTypeWriter::VisitParenType(const ParenType *T) {
00359   Writer.AddTypeRef(T->getInnerType(), Record);
00360   Code = TYPE_PAREN;
00361 }
00362 
00363 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
00364   Record.push_back(T->getKeyword());
00365   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
00366   Writer.AddTypeRef(T->getNamedType(), Record);
00367   Code = TYPE_ELABORATED;
00368 }
00369 
00370 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
00371   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
00372   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
00373   Code = TYPE_INJECTED_CLASS_NAME;
00374 }
00375 
00376 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
00377   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
00378   Code = TYPE_OBJC_INTERFACE;
00379 }
00380 
00381 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
00382   Writer.AddTypeRef(T->getBaseType(), Record);
00383   Record.push_back(T->getNumProtocols());
00384   for (ObjCObjectType::qual_iterator I = T->qual_begin(),
00385        E = T->qual_end(); I != E; ++I)
00386     Writer.AddDeclRef(*I, Record);
00387   Code = TYPE_OBJC_OBJECT;
00388 }
00389 
00390 void
00391 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
00392   Writer.AddTypeRef(T->getPointeeType(), Record);
00393   Code = TYPE_OBJC_OBJECT_POINTER;
00394 }
00395 
00396 void
00397 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
00398   Writer.AddTypeRef(T->getValueType(), Record);
00399   Code = TYPE_ATOMIC;
00400 }
00401 
00402 namespace {
00403 
00404 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
00405   ASTWriter &Writer;
00406   ASTWriter::RecordDataImpl &Record;
00407 
00408 public:
00409   TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
00410     : Writer(Writer), Record(Record) { }
00411 
00412 #define ABSTRACT_TYPELOC(CLASS, PARENT)
00413 #define TYPELOC(CLASS, PARENT) \
00414     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
00415 #include "clang/AST/TypeLocNodes.def"
00416 
00417   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
00418   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
00419 };
00420 
00421 }
00422 
00423 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
00424   // nothing to do
00425 }
00426 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
00427   Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
00428   if (TL.needsExtraLocalData()) {
00429     Record.push_back(TL.getWrittenTypeSpec());
00430     Record.push_back(TL.getWrittenSignSpec());
00431     Record.push_back(TL.getWrittenWidthSpec());
00432     Record.push_back(TL.hasModeAttr());
00433   }
00434 }
00435 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
00436   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00437 }
00438 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
00439   Writer.AddSourceLocation(TL.getStarLoc(), Record);
00440 }
00441 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
00442   Writer.AddSourceLocation(TL.getCaretLoc(), Record);
00443 }
00444 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
00445   Writer.AddSourceLocation(TL.getAmpLoc(), Record);
00446 }
00447 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
00448   Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
00449 }
00450 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
00451   Writer.AddSourceLocation(TL.getStarLoc(), Record);
00452   Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
00453 }
00454 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
00455   Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
00456   Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
00457   Record.push_back(TL.getSizeExpr() ? 1 : 0);
00458   if (TL.getSizeExpr())
00459     Writer.AddStmt(TL.getSizeExpr());
00460 }
00461 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
00462   VisitArrayTypeLoc(TL);
00463 }
00464 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
00465   VisitArrayTypeLoc(TL);
00466 }
00467 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
00468   VisitArrayTypeLoc(TL);
00469 }
00470 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
00471                                             DependentSizedArrayTypeLoc TL) {
00472   VisitArrayTypeLoc(TL);
00473 }
00474 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
00475                                         DependentSizedExtVectorTypeLoc TL) {
00476   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00477 }
00478 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
00479   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00480 }
00481 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
00482   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00483 }
00484 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
00485   Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
00486   Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
00487   Record.push_back(TL.getTrailingReturn());
00488   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
00489     Writer.AddDeclRef(TL.getArg(i), Record);
00490 }
00491 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
00492   VisitFunctionTypeLoc(TL);
00493 }
00494 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
00495   VisitFunctionTypeLoc(TL);
00496 }
00497 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
00498   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00499 }
00500 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
00501   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00502 }
00503 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
00504   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
00505   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
00506   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
00507 }
00508 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
00509   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
00510   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
00511   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
00512   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
00513 }
00514 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
00515   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00516 }
00517 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
00518   Writer.AddSourceLocation(TL.getKWLoc(), Record);
00519   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
00520   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
00521   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
00522 }
00523 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
00524   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00525 }
00526 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
00527   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00528 }
00529 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
00530   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00531 }
00532 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
00533   Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
00534   if (TL.hasAttrOperand()) {
00535     SourceRange range = TL.getAttrOperandParensRange();
00536     Writer.AddSourceLocation(range.getBegin(), Record);
00537     Writer.AddSourceLocation(range.getEnd(), Record);
00538   }
00539   if (TL.hasAttrExprOperand()) {
00540     Expr *operand = TL.getAttrExprOperand();
00541     Record.push_back(operand ? 1 : 0);
00542     if (operand) Writer.AddStmt(operand);
00543   } else if (TL.hasAttrEnumOperand()) {
00544     Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
00545   }
00546 }
00547 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
00548   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00549 }
00550 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
00551                                             SubstTemplateTypeParmTypeLoc TL) {
00552   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00553 }
00554 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
00555                                           SubstTemplateTypeParmPackTypeLoc TL) {
00556   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00557 }
00558 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
00559                                            TemplateSpecializationTypeLoc TL) {
00560   Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
00561   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
00562   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
00563   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
00564   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
00565     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
00566                                       TL.getArgLoc(i).getLocInfo(), Record);
00567 }
00568 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
00569   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
00570   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
00571 }
00572 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
00573   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
00574   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
00575 }
00576 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
00577   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00578 }
00579 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
00580   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
00581   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
00582   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00583 }
00584 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
00585        DependentTemplateSpecializationTypeLoc TL) {
00586   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
00587   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
00588   Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
00589   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
00590   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
00591   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
00592   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
00593     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
00594                                       TL.getArgLoc(I).getLocInfo(), Record);
00595 }
00596 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
00597   Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
00598 }
00599 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
00600   Writer.AddSourceLocation(TL.getNameLoc(), Record);
00601 }
00602 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
00603   Record.push_back(TL.hasBaseTypeAsWritten());
00604   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
00605   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
00606   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
00607     Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
00608 }
00609 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
00610   Writer.AddSourceLocation(TL.getStarLoc(), Record);
00611 }
00612 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
00613   Writer.AddSourceLocation(TL.getKWLoc(), Record);
00614   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
00615   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
00616 }
00617 
00618 //===----------------------------------------------------------------------===//
00619 // ASTWriter Implementation
00620 //===----------------------------------------------------------------------===//
00621 
00622 static void EmitBlockID(unsigned ID, const char *Name,
00623                         llvm::BitstreamWriter &Stream,
00624                         ASTWriter::RecordDataImpl &Record) {
00625   Record.clear();
00626   Record.push_back(ID);
00627   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
00628 
00629   // Emit the block name if present.
00630   if (Name == 0 || Name[0] == 0) return;
00631   Record.clear();
00632   while (*Name)
00633     Record.push_back(*Name++);
00634   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
00635 }
00636 
00637 static void EmitRecordID(unsigned ID, const char *Name,
00638                          llvm::BitstreamWriter &Stream,
00639                          ASTWriter::RecordDataImpl &Record) {
00640   Record.clear();
00641   Record.push_back(ID);
00642   while (*Name)
00643     Record.push_back(*Name++);
00644   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
00645 }
00646 
00647 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
00648                           ASTWriter::RecordDataImpl &Record) {
00649 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
00650   RECORD(STMT_STOP);
00651   RECORD(STMT_NULL_PTR);
00652   RECORD(STMT_NULL);
00653   RECORD(STMT_COMPOUND);
00654   RECORD(STMT_CASE);
00655   RECORD(STMT_DEFAULT);
00656   RECORD(STMT_LABEL);
00657   RECORD(STMT_ATTRIBUTED);
00658   RECORD(STMT_IF);
00659   RECORD(STMT_SWITCH);
00660   RECORD(STMT_WHILE);
00661   RECORD(STMT_DO);
00662   RECORD(STMT_FOR);
00663   RECORD(STMT_GOTO);
00664   RECORD(STMT_INDIRECT_GOTO);
00665   RECORD(STMT_CONTINUE);
00666   RECORD(STMT_BREAK);
00667   RECORD(STMT_RETURN);
00668   RECORD(STMT_DECL);
00669   RECORD(STMT_ASM);
00670   RECORD(EXPR_PREDEFINED);
00671   RECORD(EXPR_DECL_REF);
00672   RECORD(EXPR_INTEGER_LITERAL);
00673   RECORD(EXPR_FLOATING_LITERAL);
00674   RECORD(EXPR_IMAGINARY_LITERAL);
00675   RECORD(EXPR_STRING_LITERAL);
00676   RECORD(EXPR_CHARACTER_LITERAL);
00677   RECORD(EXPR_PAREN);
00678   RECORD(EXPR_UNARY_OPERATOR);
00679   RECORD(EXPR_SIZEOF_ALIGN_OF);
00680   RECORD(EXPR_ARRAY_SUBSCRIPT);
00681   RECORD(EXPR_CALL);
00682   RECORD(EXPR_MEMBER);
00683   RECORD(EXPR_BINARY_OPERATOR);
00684   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
00685   RECORD(EXPR_CONDITIONAL_OPERATOR);
00686   RECORD(EXPR_IMPLICIT_CAST);
00687   RECORD(EXPR_CSTYLE_CAST);
00688   RECORD(EXPR_COMPOUND_LITERAL);
00689   RECORD(EXPR_EXT_VECTOR_ELEMENT);
00690   RECORD(EXPR_INIT_LIST);
00691   RECORD(EXPR_DESIGNATED_INIT);
00692   RECORD(EXPR_IMPLICIT_VALUE_INIT);
00693   RECORD(EXPR_VA_ARG);
00694   RECORD(EXPR_ADDR_LABEL);
00695   RECORD(EXPR_STMT);
00696   RECORD(EXPR_CHOOSE);
00697   RECORD(EXPR_GNU_NULL);
00698   RECORD(EXPR_SHUFFLE_VECTOR);
00699   RECORD(EXPR_BLOCK);
00700   RECORD(EXPR_GENERIC_SELECTION);
00701   RECORD(EXPR_OBJC_STRING_LITERAL);
00702   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
00703   RECORD(EXPR_OBJC_ARRAY_LITERAL);
00704   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
00705   RECORD(EXPR_OBJC_ENCODE);
00706   RECORD(EXPR_OBJC_SELECTOR_EXPR);
00707   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
00708   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
00709   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
00710   RECORD(EXPR_OBJC_KVC_REF_EXPR);
00711   RECORD(EXPR_OBJC_MESSAGE_EXPR);
00712   RECORD(STMT_OBJC_FOR_COLLECTION);
00713   RECORD(STMT_OBJC_CATCH);
00714   RECORD(STMT_OBJC_FINALLY);
00715   RECORD(STMT_OBJC_AT_TRY);
00716   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
00717   RECORD(STMT_OBJC_AT_THROW);
00718   RECORD(EXPR_OBJC_BOOL_LITERAL);
00719   RECORD(EXPR_CXX_OPERATOR_CALL);
00720   RECORD(EXPR_CXX_CONSTRUCT);
00721   RECORD(EXPR_CXX_STATIC_CAST);
00722   RECORD(EXPR_CXX_DYNAMIC_CAST);
00723   RECORD(EXPR_CXX_REINTERPRET_CAST);
00724   RECORD(EXPR_CXX_CONST_CAST);
00725   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
00726   RECORD(EXPR_USER_DEFINED_LITERAL);
00727   RECORD(EXPR_CXX_BOOL_LITERAL);
00728   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
00729   RECORD(EXPR_CXX_TYPEID_EXPR);
00730   RECORD(EXPR_CXX_TYPEID_TYPE);
00731   RECORD(EXPR_CXX_UUIDOF_EXPR);
00732   RECORD(EXPR_CXX_UUIDOF_TYPE);
00733   RECORD(EXPR_CXX_THIS);
00734   RECORD(EXPR_CXX_THROW);
00735   RECORD(EXPR_CXX_DEFAULT_ARG);
00736   RECORD(EXPR_CXX_BIND_TEMPORARY);
00737   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
00738   RECORD(EXPR_CXX_NEW);
00739   RECORD(EXPR_CXX_DELETE);
00740   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
00741   RECORD(EXPR_EXPR_WITH_CLEANUPS);
00742   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
00743   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
00744   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
00745   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
00746   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
00747   RECORD(EXPR_CXX_UNARY_TYPE_TRAIT);
00748   RECORD(EXPR_CXX_NOEXCEPT);
00749   RECORD(EXPR_OPAQUE_VALUE);
00750   RECORD(EXPR_BINARY_TYPE_TRAIT);
00751   RECORD(EXPR_PACK_EXPANSION);
00752   RECORD(EXPR_SIZEOF_PACK);
00753   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
00754   RECORD(EXPR_CUDA_KERNEL_CALL);
00755 #undef RECORD
00756 }
00757 
00758 void ASTWriter::WriteBlockInfoBlock() {
00759   RecordData Record;
00760   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
00761 
00762 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
00763 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
00764 
00765   // AST Top-Level Block.
00766   BLOCK(AST_BLOCK);
00767   RECORD(ORIGINAL_FILE_NAME);
00768   RECORD(ORIGINAL_FILE_ID);
00769   RECORD(TYPE_OFFSET);
00770   RECORD(DECL_OFFSET);
00771   RECORD(LANGUAGE_OPTIONS);
00772   RECORD(METADATA);
00773   RECORD(IDENTIFIER_OFFSET);
00774   RECORD(IDENTIFIER_TABLE);
00775   RECORD(EXTERNAL_DEFINITIONS);
00776   RECORD(SPECIAL_TYPES);
00777   RECORD(STATISTICS);
00778   RECORD(TENTATIVE_DEFINITIONS);
00779   RECORD(UNUSED_FILESCOPED_DECLS);
00780   RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS);
00781   RECORD(SELECTOR_OFFSETS);
00782   RECORD(METHOD_POOL);
00783   RECORD(PP_COUNTER_VALUE);
00784   RECORD(SOURCE_LOCATION_OFFSETS);
00785   RECORD(SOURCE_LOCATION_PRELOADS);
00786   RECORD(STAT_CACHE);
00787   RECORD(EXT_VECTOR_DECLS);
00788   RECORD(VERSION_CONTROL_BRANCH_REVISION);
00789   RECORD(PPD_ENTITIES_OFFSETS);
00790   RECORD(IMPORTS);
00791   RECORD(REFERENCED_SELECTOR_POOL);
00792   RECORD(TU_UPDATE_LEXICAL);
00793   RECORD(LOCAL_REDECLARATIONS_MAP);
00794   RECORD(SEMA_DECL_REFS);
00795   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
00796   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
00797   RECORD(DECL_REPLACEMENTS);
00798   RECORD(UPDATE_VISIBLE);
00799   RECORD(DECL_UPDATE_OFFSETS);
00800   RECORD(DECL_UPDATES);
00801   RECORD(CXX_BASE_SPECIFIER_OFFSETS);
00802   RECORD(DIAG_PRAGMA_MAPPINGS);
00803   RECORD(CUDA_SPECIAL_DECL_REFS);
00804   RECORD(HEADER_SEARCH_TABLE);
00805   RECORD(ORIGINAL_PCH_DIR);
00806   RECORD(FP_PRAGMA_OPTIONS);
00807   RECORD(OPENCL_EXTENSIONS);
00808   RECORD(DELEGATING_CTORS);
00809   RECORD(FILE_SOURCE_LOCATION_OFFSETS);
00810   RECORD(KNOWN_NAMESPACES);
00811   RECORD(MODULE_OFFSET_MAP);
00812   RECORD(SOURCE_MANAGER_LINE_TABLE);
00813   RECORD(OBJC_CATEGORIES_MAP);
00814   RECORD(FILE_SORTED_DECLS);
00815   RECORD(IMPORTED_MODULES);
00816   RECORD(MERGED_DECLARATIONS);
00817   RECORD(LOCAL_REDECLARATIONS);
00818   RECORD(OBJC_CATEGORIES);
00819 
00820   // SourceManager Block.
00821   BLOCK(SOURCE_MANAGER_BLOCK);
00822   RECORD(SM_SLOC_FILE_ENTRY);
00823   RECORD(SM_SLOC_BUFFER_ENTRY);
00824   RECORD(SM_SLOC_BUFFER_BLOB);
00825   RECORD(SM_SLOC_EXPANSION_ENTRY);
00826 
00827   // Preprocessor Block.
00828   BLOCK(PREPROCESSOR_BLOCK);
00829   RECORD(PP_MACRO_OBJECT_LIKE);
00830   RECORD(PP_MACRO_FUNCTION_LIKE);
00831   RECORD(PP_TOKEN);
00832   
00833   // Decls and Types block.
00834   BLOCK(DECLTYPES_BLOCK);
00835   RECORD(TYPE_EXT_QUAL);
00836   RECORD(TYPE_COMPLEX);
00837   RECORD(TYPE_POINTER);
00838   RECORD(TYPE_BLOCK_POINTER);
00839   RECORD(TYPE_LVALUE_REFERENCE);
00840   RECORD(TYPE_RVALUE_REFERENCE);
00841   RECORD(TYPE_MEMBER_POINTER);
00842   RECORD(TYPE_CONSTANT_ARRAY);
00843   RECORD(TYPE_INCOMPLETE_ARRAY);
00844   RECORD(TYPE_VARIABLE_ARRAY);
00845   RECORD(TYPE_VECTOR);
00846   RECORD(TYPE_EXT_VECTOR);
00847   RECORD(TYPE_FUNCTION_PROTO);
00848   RECORD(TYPE_FUNCTION_NO_PROTO);
00849   RECORD(TYPE_TYPEDEF);
00850   RECORD(TYPE_TYPEOF_EXPR);
00851   RECORD(TYPE_TYPEOF);
00852   RECORD(TYPE_RECORD);
00853   RECORD(TYPE_ENUM);
00854   RECORD(TYPE_OBJC_INTERFACE);
00855   RECORD(TYPE_OBJC_OBJECT);
00856   RECORD(TYPE_OBJC_OBJECT_POINTER);
00857   RECORD(TYPE_DECLTYPE);
00858   RECORD(TYPE_ELABORATED);
00859   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
00860   RECORD(TYPE_UNRESOLVED_USING);
00861   RECORD(TYPE_INJECTED_CLASS_NAME);
00862   RECORD(TYPE_OBJC_OBJECT);
00863   RECORD(TYPE_TEMPLATE_TYPE_PARM);
00864   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
00865   RECORD(TYPE_DEPENDENT_NAME);
00866   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
00867   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
00868   RECORD(TYPE_PAREN);
00869   RECORD(TYPE_PACK_EXPANSION);
00870   RECORD(TYPE_ATTRIBUTED);
00871   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
00872   RECORD(TYPE_ATOMIC);
00873   RECORD(DECL_TYPEDEF);
00874   RECORD(DECL_ENUM);
00875   RECORD(DECL_RECORD);
00876   RECORD(DECL_ENUM_CONSTANT);
00877   RECORD(DECL_FUNCTION);
00878   RECORD(DECL_OBJC_METHOD);
00879   RECORD(DECL_OBJC_INTERFACE);
00880   RECORD(DECL_OBJC_PROTOCOL);
00881   RECORD(DECL_OBJC_IVAR);
00882   RECORD(DECL_OBJC_AT_DEFS_FIELD);
00883   RECORD(DECL_OBJC_CATEGORY);
00884   RECORD(DECL_OBJC_CATEGORY_IMPL);
00885   RECORD(DECL_OBJC_IMPLEMENTATION);
00886   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
00887   RECORD(DECL_OBJC_PROPERTY);
00888   RECORD(DECL_OBJC_PROPERTY_IMPL);
00889   RECORD(DECL_FIELD);
00890   RECORD(DECL_VAR);
00891   RECORD(DECL_IMPLICIT_PARAM);
00892   RECORD(DECL_PARM_VAR);
00893   RECORD(DECL_FILE_SCOPE_ASM);
00894   RECORD(DECL_BLOCK);
00895   RECORD(DECL_CONTEXT_LEXICAL);
00896   RECORD(DECL_CONTEXT_VISIBLE);
00897   RECORD(DECL_NAMESPACE);
00898   RECORD(DECL_NAMESPACE_ALIAS);
00899   RECORD(DECL_USING);
00900   RECORD(DECL_USING_SHADOW);
00901   RECORD(DECL_USING_DIRECTIVE);
00902   RECORD(DECL_UNRESOLVED_USING_VALUE);
00903   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
00904   RECORD(DECL_LINKAGE_SPEC);
00905   RECORD(DECL_CXX_RECORD);
00906   RECORD(DECL_CXX_METHOD);
00907   RECORD(DECL_CXX_CONSTRUCTOR);
00908   RECORD(DECL_CXX_DESTRUCTOR);
00909   RECORD(DECL_CXX_CONVERSION);
00910   RECORD(DECL_ACCESS_SPEC);
00911   RECORD(DECL_FRIEND);
00912   RECORD(DECL_FRIEND_TEMPLATE);
00913   RECORD(DECL_CLASS_TEMPLATE);
00914   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
00915   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
00916   RECORD(DECL_FUNCTION_TEMPLATE);
00917   RECORD(DECL_TEMPLATE_TYPE_PARM);
00918   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
00919   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
00920   RECORD(DECL_STATIC_ASSERT);
00921   RECORD(DECL_CXX_BASE_SPECIFIERS);
00922   RECORD(DECL_INDIRECTFIELD);
00923   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
00924   
00925   // Statements and Exprs can occur in the Decls and Types block.
00926   AddStmtsExprs(Stream, Record);
00927 
00928   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
00929   RECORD(PPD_MACRO_EXPANSION);
00930   RECORD(PPD_MACRO_DEFINITION);
00931   RECORD(PPD_INCLUSION_DIRECTIVE);
00932   
00933 #undef RECORD
00934 #undef BLOCK
00935   Stream.ExitBlock();
00936 }
00937 
00938 /// \brief Adjusts the given filename to only write out the portion of the
00939 /// filename that is not part of the system root directory.
00940 ///
00941 /// \param Filename the file name to adjust.
00942 ///
00943 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
00944 /// the returned filename will be adjusted by this system root.
00945 ///
00946 /// \returns either the original filename (if it needs no adjustment) or the
00947 /// adjusted filename (which points into the @p Filename parameter).
00948 static const char *
00949 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
00950   assert(Filename && "No file name to adjust?");
00951 
00952   if (isysroot.empty())
00953     return Filename;
00954 
00955   // Verify that the filename and the system root have the same prefix.
00956   unsigned Pos = 0;
00957   for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
00958     if (Filename[Pos] != isysroot[Pos])
00959       return Filename; // Prefixes don't match.
00960 
00961   // We hit the end of the filename before we hit the end of the system root.
00962   if (!Filename[Pos])
00963     return Filename;
00964 
00965   // If the file name has a '/' at the current position, skip over the '/'.
00966   // We distinguish sysroot-based includes from absolute includes by the
00967   // absence of '/' at the beginning of sysroot-based includes.
00968   if (Filename[Pos] == '/')
00969     ++Pos;
00970 
00971   return Filename + Pos;
00972 }
00973 
00974 /// \brief Write the AST metadata (e.g., i686-apple-darwin9).
00975 void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot,
00976                               const std::string &OutputFile) {
00977   using namespace llvm;
00978 
00979   // Metadata
00980   const TargetInfo &Target = Context.getTargetInfo();
00981   BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev();
00982   MetaAbbrev->Add(BitCodeAbbrevOp(METADATA));
00983   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major
00984   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor
00985   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major
00986   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor
00987   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
00988   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Has errors
00989   MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple
00990   unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev);
00991 
00992   RecordData Record;
00993   Record.push_back(METADATA);
00994   Record.push_back(VERSION_MAJOR);
00995   Record.push_back(VERSION_MINOR);
00996   Record.push_back(CLANG_VERSION_MAJOR);
00997   Record.push_back(CLANG_VERSION_MINOR);
00998   Record.push_back(!isysroot.empty());
00999   Record.push_back(ASTHasCompilerErrors);
01000   const std::string &Triple = Target.getTriple().getTriple();
01001   Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple);
01002 
01003   if (Chain) {
01004     serialization::ModuleManager &Mgr = Chain->getModuleManager();
01005     llvm::SmallVector<char, 128> ModulePaths;
01006     Record.clear();
01007 
01008     for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
01009          M != MEnd; ++M) {
01010       // Skip modules that weren't directly imported.
01011       if (!(*M)->isDirectlyImported())
01012         continue;
01013 
01014       Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
01015       // FIXME: Write import location, once it matters.
01016       // FIXME: This writes the absolute path for AST files we depend on.
01017       const std::string &FileName = (*M)->FileName;
01018       Record.push_back(FileName.size());
01019       Record.append(FileName.begin(), FileName.end());
01020     }
01021     Stream.EmitRecord(IMPORTS, Record);
01022   }
01023 
01024   // Original file name and file ID
01025   SourceManager &SM = Context.getSourceManager();
01026   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
01027     BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
01028     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME));
01029     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
01030     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
01031 
01032     SmallString<128> MainFilePath(MainFile->getName());
01033 
01034     llvm::sys::fs::make_absolute(MainFilePath);
01035 
01036     const char *MainFileNameStr = MainFilePath.c_str();
01037     MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
01038                                                       isysroot);
01039     RecordData Record;
01040     Record.push_back(ORIGINAL_FILE_NAME);
01041     Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
01042     
01043     Record.clear();
01044     Record.push_back(SM.getMainFileID().getOpaqueValue());
01045     Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
01046   }
01047 
01048   // Original PCH directory
01049   if (!OutputFile.empty() && OutputFile != "-") {
01050     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01051     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
01052     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
01053     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
01054 
01055     SmallString<128> OutputPath(OutputFile);
01056 
01057     llvm::sys::fs::make_absolute(OutputPath);
01058     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
01059 
01060     RecordData Record;
01061     Record.push_back(ORIGINAL_PCH_DIR);
01062     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
01063   }
01064 
01065   // Repository branch/version information.
01066   BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev();
01067   RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION));
01068   RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
01069   unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev);
01070   Record.clear();
01071   Record.push_back(VERSION_CONTROL_BRANCH_REVISION);
01072   Stream.EmitRecordWithBlob(RepoAbbrevCode, Record,
01073                             getClangFullRepositoryVersion());
01074 }
01075 
01076 /// \brief Write the LangOptions structure.
01077 void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) {
01078   RecordData Record;
01079 #define LANGOPT(Name, Bits, Default, Description) \
01080   Record.push_back(LangOpts.Name);
01081 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
01082   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
01083 #include "clang/Basic/LangOptions.def"  
01084   
01085   Record.push_back(LangOpts.CurrentModule.size());
01086   Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
01087   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
01088 }
01089 
01090 //===----------------------------------------------------------------------===//
01091 // stat cache Serialization
01092 //===----------------------------------------------------------------------===//
01093 
01094 namespace {
01095 // Trait used for the on-disk hash table of stat cache results.
01096 class ASTStatCacheTrait {
01097 public:
01098   typedef const char * key_type;
01099   typedef key_type key_type_ref;
01100 
01101   typedef struct stat data_type;
01102   typedef const data_type &data_type_ref;
01103 
01104   static unsigned ComputeHash(const char *path) {
01105     return llvm::HashString(path);
01106   }
01107 
01108   std::pair<unsigned,unsigned>
01109     EmitKeyDataLength(raw_ostream& Out, const char *path,
01110                       data_type_ref Data) {
01111     unsigned StrLen = strlen(path);
01112     clang::io::Emit16(Out, StrLen);
01113     unsigned DataLen = 4 + 4 + 2 + 8 + 8;
01114     clang::io::Emit8(Out, DataLen);
01115     return std::make_pair(StrLen + 1, DataLen);
01116   }
01117 
01118   void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
01119     Out.write(path, KeyLen);
01120   }
01121 
01122   void EmitData(raw_ostream &Out, key_type_ref,
01123                 data_type_ref Data, unsigned DataLen) {
01124     using namespace clang::io;
01125     uint64_t Start = Out.tell(); (void)Start;
01126 
01127     Emit32(Out, (uint32_t) Data.st_ino);
01128     Emit32(Out, (uint32_t) Data.st_dev);
01129     Emit16(Out, (uint16_t) Data.st_mode);
01130     Emit64(Out, (uint64_t) Data.st_mtime);
01131     Emit64(Out, (uint64_t) Data.st_size);
01132 
01133     assert(Out.tell() - Start == DataLen && "Wrong data length");
01134   }
01135 };
01136 } // end anonymous namespace
01137 
01138 /// \brief Write the stat() system call cache to the AST file.
01139 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) {
01140   // Build the on-disk hash table containing information about every
01141   // stat() call.
01142   OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator;
01143   unsigned NumStatEntries = 0;
01144   for (MemorizeStatCalls::iterator Stat = StatCalls.begin(),
01145                                 StatEnd = StatCalls.end();
01146        Stat != StatEnd; ++Stat, ++NumStatEntries) {
01147     StringRef Filename = Stat->first();
01148     Generator.insert(Filename.data(), Stat->second);
01149   }
01150 
01151   // Create the on-disk hash table in a buffer.
01152   SmallString<4096> StatCacheData;
01153   uint32_t BucketOffset;
01154   {
01155     llvm::raw_svector_ostream Out(StatCacheData);
01156     // Make sure that no bucket is at offset 0
01157     clang::io::Emit32(Out, 0);
01158     BucketOffset = Generator.Emit(Out);
01159   }
01160 
01161   // Create a blob abbreviation
01162   using namespace llvm;
01163   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01164   Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE));
01165   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
01166   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
01167   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
01168   unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev);
01169 
01170   // Write the stat cache
01171   RecordData Record;
01172   Record.push_back(STAT_CACHE);
01173   Record.push_back(BucketOffset);
01174   Record.push_back(NumStatEntries);
01175   Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str());
01176 }
01177 
01178 //===----------------------------------------------------------------------===//
01179 // Source Manager Serialization
01180 //===----------------------------------------------------------------------===//
01181 
01182 /// \brief Create an abbreviation for the SLocEntry that refers to a
01183 /// file.
01184 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
01185   using namespace llvm;
01186   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01187   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
01188   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
01189   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
01190   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
01191   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
01192   // FileEntry fields.
01193   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
01194   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
01195   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden
01196   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
01197   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
01198   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
01199   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
01200   return Stream.EmitAbbrev(Abbrev);
01201 }
01202 
01203 /// \brief Create an abbreviation for the SLocEntry that refers to a
01204 /// buffer.
01205 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
01206   using namespace llvm;
01207   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01208   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
01209   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
01210   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
01211   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
01212   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
01213   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
01214   return Stream.EmitAbbrev(Abbrev);
01215 }
01216 
01217 /// \brief Create an abbreviation for the SLocEntry that refers to a
01218 /// buffer's blob.
01219 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
01220   using namespace llvm;
01221   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01222   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
01223   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
01224   return Stream.EmitAbbrev(Abbrev);
01225 }
01226 
01227 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
01228 /// expansion.
01229 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
01230   using namespace llvm;
01231   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01232   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
01233   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
01234   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
01235   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
01236   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
01237   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
01238   return Stream.EmitAbbrev(Abbrev);
01239 }
01240 
01241 namespace {
01242   // Trait used for the on-disk hash table of header search information.
01243   class HeaderFileInfoTrait {
01244     ASTWriter &Writer;
01245     const HeaderSearch &HS;
01246     
01247     // Keep track of the framework names we've used during serialization.
01248     SmallVector<char, 128> FrameworkStringData;
01249     llvm::StringMap<unsigned> FrameworkNameOffset;
01250     
01251   public:
01252     HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS) 
01253       : Writer(Writer), HS(HS) { }
01254     
01255     typedef const char *key_type;
01256     typedef key_type key_type_ref;
01257     
01258     typedef HeaderFileInfo data_type;
01259     typedef const data_type &data_type_ref;
01260     
01261     static unsigned ComputeHash(const char *path) {
01262       // The hash is based only on the filename portion of the key, so that the
01263       // reader can match based on filenames when symlinking or excess path
01264       // elements ("foo/../", "../") change the form of the name. However,
01265       // complete path is still the key.
01266       return llvm::HashString(llvm::sys::path::filename(path));
01267     }
01268     
01269     std::pair<unsigned,unsigned>
01270     EmitKeyDataLength(raw_ostream& Out, const char *path,
01271                       data_type_ref Data) {
01272       unsigned StrLen = strlen(path);
01273       clang::io::Emit16(Out, StrLen);
01274       unsigned DataLen = 1 + 2 + 4 + 4;
01275       clang::io::Emit8(Out, DataLen);
01276       return std::make_pair(StrLen + 1, DataLen);
01277     }
01278     
01279     void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) {
01280       Out.write(path, KeyLen);
01281     }
01282     
01283     void EmitData(raw_ostream &Out, key_type_ref,
01284                   data_type_ref Data, unsigned DataLen) {
01285       using namespace clang::io;
01286       uint64_t Start = Out.tell(); (void)Start;
01287       
01288       unsigned char Flags = (Data.isImport << 5)
01289                           | (Data.isPragmaOnce << 4)
01290                           | (Data.DirInfo << 2)
01291                           | (Data.Resolved << 1)
01292                           | Data.IndexHeaderMapHeader;
01293       Emit8(Out, (uint8_t)Flags);
01294       Emit16(Out, (uint16_t) Data.NumIncludes);
01295       
01296       if (!Data.ControllingMacro)
01297         Emit32(Out, (uint32_t)Data.ControllingMacroID);
01298       else
01299         Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro));
01300       
01301       unsigned Offset = 0;
01302       if (!Data.Framework.empty()) {
01303         // If this header refers into a framework, save the framework name.
01304         llvm::StringMap<unsigned>::iterator Pos
01305           = FrameworkNameOffset.find(Data.Framework);
01306         if (Pos == FrameworkNameOffset.end()) {
01307           Offset = FrameworkStringData.size() + 1;
01308           FrameworkStringData.append(Data.Framework.begin(), 
01309                                      Data.Framework.end());
01310           FrameworkStringData.push_back(0);
01311           
01312           FrameworkNameOffset[Data.Framework] = Offset;
01313         } else
01314           Offset = Pos->second;
01315       }
01316       Emit32(Out, Offset);
01317       
01318       assert(Out.tell() - Start == DataLen && "Wrong data length");
01319     }
01320     
01321     const char *strings_begin() const { return FrameworkStringData.begin(); }
01322     const char *strings_end() const { return FrameworkStringData.end(); }
01323   };
01324 } // end anonymous namespace
01325 
01326 /// \brief Write the header search block for the list of files that 
01327 ///
01328 /// \param HS The header search structure to save.
01329 ///
01330 /// \param Chain Whether we're creating a chained AST file.
01331 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
01332   SmallVector<const FileEntry *, 16> FilesByUID;
01333   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
01334   
01335   if (FilesByUID.size() > HS.header_file_size())
01336     FilesByUID.resize(HS.header_file_size());
01337   
01338   HeaderFileInfoTrait GeneratorTrait(*this, HS);
01339   OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;  
01340   SmallVector<const char *, 4> SavedStrings;
01341   unsigned NumHeaderSearchEntries = 0;
01342   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
01343     const FileEntry *File = FilesByUID[UID];
01344     if (!File)
01345       continue;
01346 
01347     // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
01348     // from the external source if it was not provided already.
01349     const HeaderFileInfo &HFI = HS.getFileInfo(File);
01350     if (HFI.External && Chain)
01351       continue;
01352 
01353     // Turn the file name into an absolute path, if it isn't already.
01354     const char *Filename = File->getName();
01355     Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
01356       
01357     // If we performed any translation on the file name at all, we need to
01358     // save this string, since the generator will refer to it later.
01359     if (Filename != File->getName()) {
01360       Filename = strdup(Filename);
01361       SavedStrings.push_back(Filename);
01362     }
01363     
01364     Generator.insert(Filename, HFI, GeneratorTrait);
01365     ++NumHeaderSearchEntries;
01366   }
01367   
01368   // Create the on-disk hash table in a buffer.
01369   SmallString<4096> TableData;
01370   uint32_t BucketOffset;
01371   {
01372     llvm::raw_svector_ostream Out(TableData);
01373     // Make sure that no bucket is at offset 0
01374     clang::io::Emit32(Out, 0);
01375     BucketOffset = Generator.Emit(Out, GeneratorTrait);
01376   }
01377 
01378   // Create a blob abbreviation
01379   using namespace llvm;
01380   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01381   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
01382   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
01383   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
01384   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
01385   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
01386   unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
01387   
01388   // Write the header search table
01389   RecordData Record;
01390   Record.push_back(HEADER_SEARCH_TABLE);
01391   Record.push_back(BucketOffset);
01392   Record.push_back(NumHeaderSearchEntries);
01393   Record.push_back(TableData.size());
01394   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
01395   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
01396   
01397   // Free all of the strings we had to duplicate.
01398   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
01399     free((void*)SavedStrings[I]);
01400 }
01401 
01402 /// \brief Writes the block containing the serialized form of the
01403 /// source manager.
01404 ///
01405 /// TODO: We should probably use an on-disk hash table (stored in a
01406 /// blob), indexed based on the file name, so that we only create
01407 /// entries for files that we actually need. In the common case (no
01408 /// errors), we probably won't have to create file entries for any of
01409 /// the files in the AST.
01410 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
01411                                         const Preprocessor &PP,
01412                                         StringRef isysroot) {
01413   RecordData Record;
01414 
01415   // Enter the source manager block.
01416   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
01417 
01418   // Abbreviations for the various kinds of source-location entries.
01419   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
01420   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
01421   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
01422   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
01423 
01424   // Write out the source location entry table. We skip the first
01425   // entry, which is always the same dummy entry.
01426   std::vector<uint32_t> SLocEntryOffsets;
01427   // Write out the offsets of only source location file entries.
01428   // We will go through them in ASTReader::validateFileEntries().
01429   std::vector<uint32_t> SLocFileEntryOffsets;
01430   RecordData PreloadSLocs;
01431   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
01432   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
01433        I != N; ++I) {
01434     // Get this source location entry.
01435     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
01436 
01437     // Record the offset of this source-location entry.
01438     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
01439 
01440     // Figure out which record code to use.
01441     unsigned Code;
01442     if (SLoc->isFile()) {
01443       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
01444       if (Cache->OrigEntry) {
01445         Code = SM_SLOC_FILE_ENTRY;
01446         SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo());
01447       } else
01448         Code = SM_SLOC_BUFFER_ENTRY;
01449     } else
01450       Code = SM_SLOC_EXPANSION_ENTRY;
01451     Record.clear();
01452     Record.push_back(Code);
01453 
01454     // Starting offset of this entry within this module, so skip the dummy.
01455     Record.push_back(SLoc->getOffset() - 2);
01456     if (SLoc->isFile()) {
01457       const SrcMgr::FileInfo &File = SLoc->getFile();
01458       Record.push_back(File.getIncludeLoc().getRawEncoding());
01459       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
01460       Record.push_back(File.hasLineDirectives());
01461 
01462       const SrcMgr::ContentCache *Content = File.getContentCache();
01463       if (Content->OrigEntry) {
01464         assert(Content->OrigEntry == Content->ContentsEntry &&
01465                "Writing to AST an overridden file is not supported");
01466 
01467         // The source location entry is a file. The blob associated
01468         // with this entry is the file name.
01469 
01470         // Emit size/modification time for this file.
01471         Record.push_back(Content->OrigEntry->getSize());
01472         Record.push_back(Content->OrigEntry->getModificationTime());
01473         Record.push_back(Content->BufferOverridden);
01474         Record.push_back(File.NumCreatedFIDs);
01475         
01476         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc);
01477         if (FDI != FileDeclIDs.end()) {
01478           Record.push_back(FDI->second->FirstDeclIndex);
01479           Record.push_back(FDI->second->DeclIDs.size());
01480         } else {
01481           Record.push_back(0);
01482           Record.push_back(0);
01483         }
01484         
01485         // Turn the file name into an absolute path, if it isn't already.
01486         const char *Filename = Content->OrigEntry->getName();
01487         SmallString<128> FilePath(Filename);
01488 
01489         // Ask the file manager to fixup the relative path for us. This will 
01490         // honor the working directory.
01491         SourceMgr.getFileManager().FixupRelativePath(FilePath);
01492 
01493         // FIXME: This call to make_absolute shouldn't be necessary, the
01494         // call to FixupRelativePath should always return an absolute path.
01495         llvm::sys::fs::make_absolute(FilePath);
01496         Filename = FilePath.c_str();
01497 
01498         Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
01499         Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename);
01500         
01501         if (Content->BufferOverridden) {
01502           Record.clear();
01503           Record.push_back(SM_SLOC_BUFFER_BLOB);
01504           const llvm::MemoryBuffer *Buffer
01505             = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
01506           Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
01507                                     StringRef(Buffer->getBufferStart(),
01508                                               Buffer->getBufferSize() + 1));          
01509         }
01510       } else {
01511         // The source location entry is a buffer. The blob associated
01512         // with this entry contains the contents of the buffer.
01513 
01514         // We add one to the size so that we capture the trailing NULL
01515         // that is required by llvm::MemoryBuffer::getMemBuffer (on
01516         // the reader side).
01517         const llvm::MemoryBuffer *Buffer
01518           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
01519         const char *Name = Buffer->getBufferIdentifier();
01520         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
01521                                   StringRef(Name, strlen(Name) + 1));
01522         Record.clear();
01523         Record.push_back(SM_SLOC_BUFFER_BLOB);
01524         Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
01525                                   StringRef(Buffer->getBufferStart(),
01526                                                   Buffer->getBufferSize() + 1));
01527 
01528         if (strcmp(Name, "<built-in>") == 0) {
01529           PreloadSLocs.push_back(SLocEntryOffsets.size());
01530         }
01531       }
01532     } else {
01533       // The source location entry is a macro expansion.
01534       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
01535       Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
01536       Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
01537       Record.push_back(Expansion.isMacroArgExpansion() ? 0
01538                              : Expansion.getExpansionLocEnd().getRawEncoding());
01539 
01540       // Compute the token length for this macro expansion.
01541       unsigned NextOffset = SourceMgr.getNextLocalOffset();
01542       if (I + 1 != N)
01543         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
01544       Record.push_back(NextOffset - SLoc->getOffset() - 1);
01545       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
01546     }
01547   }
01548 
01549   Stream.ExitBlock();
01550 
01551   if (SLocEntryOffsets.empty())
01552     return;
01553 
01554   // Write the source-location offsets table into the AST block. This
01555   // table is used for lazily loading source-location information.
01556   using namespace llvm;
01557   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01558   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
01559   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
01560   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
01561   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
01562   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
01563 
01564   Record.clear();
01565   Record.push_back(SOURCE_LOCATION_OFFSETS);
01566   Record.push_back(SLocEntryOffsets.size());
01567   Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
01568   Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
01569 
01570   Abbrev = new BitCodeAbbrev();
01571   Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS));
01572   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
01573   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
01574   unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
01575 
01576   Record.clear();
01577   Record.push_back(FILE_SOURCE_LOCATION_OFFSETS);
01578   Record.push_back(SLocFileEntryOffsets.size());
01579   Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record,
01580                             data(SLocFileEntryOffsets));
01581 
01582   // Write the source location entry preloads array, telling the AST
01583   // reader which source locations entries it should load eagerly.
01584   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
01585 
01586   // Write the line table. It depends on remapping working, so it must come
01587   // after the source location offsets.
01588   if (SourceMgr.hasLineTable()) {
01589     LineTableInfo &LineTable = SourceMgr.getLineTable();
01590 
01591     Record.clear();
01592     // Emit the file names
01593     Record.push_back(LineTable.getNumFilenames());
01594     for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
01595       // Emit the file name
01596       const char *Filename = LineTable.getFilename(I);
01597       Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
01598       unsigned FilenameLen = Filename? strlen(Filename) : 0;
01599       Record.push_back(FilenameLen);
01600       if (FilenameLen)
01601         Record.insert(Record.end(), Filename, Filename + FilenameLen);
01602     }
01603 
01604     // Emit the line entries
01605     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
01606          L != LEnd; ++L) {
01607       // Only emit entries for local files.
01608       if (L->first < 0)
01609         continue;
01610 
01611       // Emit the file ID
01612       Record.push_back(L->first);
01613 
01614       // Emit the line entries
01615       Record.push_back(L->second.size());
01616       for (std::vector<LineEntry>::iterator LE = L->second.begin(),
01617                                          LEEnd = L->second.end();
01618            LE != LEEnd; ++LE) {
01619         Record.push_back(LE->FileOffset);
01620         Record.push_back(LE->LineNo);
01621         Record.push_back(LE->FilenameID);
01622         Record.push_back((unsigned)LE->FileKind);
01623         Record.push_back(LE->IncludeOffset);
01624       }
01625     }
01626     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
01627   }
01628 }
01629 
01630 //===----------------------------------------------------------------------===//
01631 // Preprocessor Serialization
01632 //===----------------------------------------------------------------------===//
01633 
01634 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) {
01635   const std::pair<const IdentifierInfo *, MacroInfo *> &X =
01636     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr;
01637   const std::pair<const IdentifierInfo *, MacroInfo *> &Y =
01638     *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr;
01639   return X.first->getName().compare(Y.first->getName());
01640 }
01641 
01642 /// \brief Writes the block containing the serialized form of the
01643 /// preprocessor.
01644 ///
01645 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
01646   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
01647   if (PPRec)
01648     WritePreprocessorDetail(*PPRec);
01649 
01650   RecordData Record;
01651 
01652   // If the preprocessor __COUNTER__ value has been bumped, remember it.
01653   if (PP.getCounterValue() != 0) {
01654     Record.push_back(PP.getCounterValue());
01655     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
01656     Record.clear();
01657   }
01658 
01659   // Enter the preprocessor block.
01660   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
01661 
01662   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
01663   // FIXME: use diagnostics subsystem for localization etc.
01664   if (PP.SawDateOrTime())
01665     fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
01666 
01667 
01668   // Loop over all the macro definitions that are live at the end of the file,
01669   // emitting each to the PP section.
01670 
01671   // Construct the list of macro definitions that need to be serialized.
01672   SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 
01673     MacrosToEmit;
01674   llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen;
01675   for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 
01676                                     E = PP.macro_end(Chain == 0);
01677        I != E; ++I) {
01678     const IdentifierInfo *Name = I->first;
01679     if (!IsModule || I->second->isPublic()) {
01680       MacroDefinitionsSeen.insert(Name);
01681       MacrosToEmit.push_back(std::make_pair(I->first, I->second));
01682     }
01683   }
01684   
01685   // Sort the set of macro definitions that need to be serialized by the
01686   // name of the macro, to provide a stable ordering.
01687   llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 
01688                        &compareMacroDefinitions);
01689   
01690   // Resolve any identifiers that defined macros at the time they were
01691   // deserialized, adding them to the list of macros to emit (if appropriate).
01692   for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) {
01693     IdentifierInfo *Name
01694       = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]);
01695     if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name))
01696       MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name)));
01697   }
01698   
01699   for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) {
01700     const IdentifierInfo *Name = MacrosToEmit[I].first;
01701     MacroInfo *MI = MacrosToEmit[I].second;
01702     if (!MI)
01703       continue;
01704     
01705     // Don't emit builtin macros like __LINE__ to the AST file unless they have
01706     // been redefined by the header (in which case they are not isBuiltinMacro).
01707     // Also skip macros from a AST file if we're chaining.
01708 
01709     // FIXME: There is a (probably minor) optimization we could do here, if
01710     // the macro comes from the original PCH but the identifier comes from a
01711     // chained PCH, by storing the offset into the original PCH rather than
01712     // writing the macro definition a second time.
01713     if (MI->isBuiltinMacro() ||
01714         (Chain && 
01715          Name->isFromAST() && !Name->hasChangedSinceDeserialization() && 
01716          MI->isFromAST() && !MI->hasChangedAfterLoad()))
01717       continue;
01718 
01719     AddIdentifierRef(Name, Record);
01720     MacroOffsets[Name] = Stream.GetCurrentBitNo();
01721     Record.push_back(MI->getDefinitionLoc().getRawEncoding());
01722     Record.push_back(MI->isUsed());
01723     Record.push_back(MI->isPublic());
01724     AddSourceLocation(MI->getVisibilityLocation(), Record);
01725     unsigned Code;
01726     if (MI->isObjectLike()) {
01727       Code = PP_MACRO_OBJECT_LIKE;
01728     } else {
01729       Code = PP_MACRO_FUNCTION_LIKE;
01730 
01731       Record.push_back(MI->isC99Varargs());
01732       Record.push_back(MI->isGNUVarargs());
01733       Record.push_back(MI->getNumArgs());
01734       for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
01735            I != E; ++I)
01736         AddIdentifierRef(*I, Record);
01737     }
01738 
01739     // If we have a detailed preprocessing record, record the macro definition
01740     // ID that corresponds to this macro.
01741     if (PPRec)
01742       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
01743 
01744     Stream.EmitRecord(Code, Record);
01745     Record.clear();
01746 
01747     // Emit the tokens array.
01748     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
01749       // Note that we know that the preprocessor does not have any annotation
01750       // tokens in it because they are created by the parser, and thus can't be
01751       // in a macro definition.
01752       const Token &Tok = MI->getReplacementToken(TokNo);
01753 
01754       Record.push_back(Tok.getLocation().getRawEncoding());
01755       Record.push_back(Tok.getLength());
01756 
01757       // FIXME: When reading literal tokens, reconstruct the literal pointer if
01758       // it is needed.
01759       AddIdentifierRef(Tok.getIdentifierInfo(), Record);
01760       // FIXME: Should translate token kind to a stable encoding.
01761       Record.push_back(Tok.getKind());
01762       // FIXME: Should translate token flags to a stable encoding.
01763       Record.push_back(Tok.getFlags());
01764 
01765       Stream.EmitRecord(PP_TOKEN, Record);
01766       Record.clear();
01767     }
01768     ++NumMacros;
01769   }
01770   Stream.ExitBlock();
01771 }
01772 
01773 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
01774   if (PPRec.local_begin() == PPRec.local_end())
01775     return;
01776 
01777   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
01778 
01779   // Enter the preprocessor block.
01780   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
01781 
01782   // If the preprocessor has a preprocessing record, emit it.
01783   unsigned NumPreprocessingRecords = 0;
01784   using namespace llvm;
01785   
01786   // Set up the abbreviation for 
01787   unsigned InclusionAbbrev = 0;
01788   {
01789     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01790     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
01791     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
01792     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
01793     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
01794     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
01795     InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
01796   }
01797   
01798   unsigned FirstPreprocessorEntityID 
01799     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 
01800     + NUM_PREDEF_PP_ENTITY_IDS;
01801   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
01802   RecordData Record;
01803   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
01804                                   EEnd = PPRec.local_end();
01805        E != EEnd; 
01806        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
01807     Record.clear();
01808 
01809     PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
01810                                                      Stream.GetCurrentBitNo()));
01811 
01812     if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
01813       // Record this macro definition's ID.
01814       MacroDefinitions[MD] = NextPreprocessorEntityID;
01815       
01816       AddIdentifierRef(MD->getName(), Record);
01817       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
01818       continue;
01819     }
01820 
01821     if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
01822       Record.push_back(ME->isBuiltinMacro());
01823       if (ME->isBuiltinMacro())
01824         AddIdentifierRef(ME->getName(), Record);
01825       else
01826         Record.push_back(MacroDefinitions[ME->getDefinition()]);
01827       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
01828       continue;
01829     }
01830 
01831     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
01832       Record.push_back(PPD_INCLUSION_DIRECTIVE);
01833       Record.push_back(ID->getFileName().size());
01834       Record.push_back(ID->wasInQuotes());
01835       Record.push_back(static_cast<unsigned>(ID->getKind()));
01836       SmallString<64> Buffer;
01837       Buffer += ID->getFileName();
01838       // Check that the FileEntry is not null because it was not resolved and
01839       // we create a PCH even with compiler errors.
01840       if (ID->getFile())
01841         Buffer += ID->getFile()->getName();
01842       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
01843       continue;
01844     }
01845     
01846     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
01847   }
01848   Stream.ExitBlock();
01849 
01850   // Write the offsets table for the preprocessing record.
01851   if (NumPreprocessingRecords > 0) {
01852     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
01853 
01854     // Write the offsets table for identifier IDs.
01855     using namespace llvm;
01856     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01857     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
01858     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
01859     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
01860     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
01861 
01862     Record.clear();
01863     Record.push_back(PPD_ENTITIES_OFFSETS);
01864     Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
01865     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
01866                               data(PreprocessedEntityOffsets));
01867   }
01868 }
01869 
01870 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
01871   llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
01872   if (Known != SubmoduleIDs.end())
01873     return Known->second;
01874   
01875   return SubmoduleIDs[Mod] = NextSubmoduleID++;
01876 }
01877 
01878 /// \brief Compute the number of modules within the given tree (including the
01879 /// given module).
01880 static unsigned getNumberOfModules(Module *Mod) {
01881   unsigned ChildModules = 0;
01882   for (Module::submodule_iterator Sub = Mod->submodule_begin(),
01883                                SubEnd = Mod->submodule_end();
01884        Sub != SubEnd; ++Sub)
01885     ChildModules += getNumberOfModules(*Sub);
01886   
01887   return ChildModules + 1;
01888 }
01889 
01890 void ASTWriter::WriteSubmodules(Module *WritingModule) {
01891   // Determine the dependencies of our module and each of it's submodules.
01892   // FIXME: This feels like it belongs somewhere else, but there are no
01893   // other consumers of this information.
01894   SourceManager &SrcMgr = PP->getSourceManager();
01895   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
01896   for (ASTContext::import_iterator I = Context->local_import_begin(),
01897                                 IEnd = Context->local_import_end();
01898        I != IEnd; ++I) {
01899     if (Module *ImportedFrom
01900           = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(), 
01901                                                          SrcMgr))) {
01902       ImportedFrom->Imports.push_back(I->getImportedModule());
01903     }
01904   }
01905   
01906   // Enter the submodule description block.
01907   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
01908   
01909   // Write the abbreviations needed for the submodules block.
01910   using namespace llvm;
01911   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
01912   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
01913   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
01914   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
01915   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
01916   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
01917   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem  
01918   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
01919   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
01920   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
01921   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
01922   unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
01923 
01924   Abbrev = new BitCodeAbbrev();
01925   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
01926   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
01927   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
01928 
01929   Abbrev = new BitCodeAbbrev();
01930   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
01931   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
01932   unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
01933 
01934   Abbrev = new BitCodeAbbrev();
01935   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
01936   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
01937   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
01938 
01939   Abbrev = new BitCodeAbbrev();
01940   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
01941   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
01942   unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
01943 
01944   // Write the submodule metadata block.
01945   RecordData Record;
01946   Record.push_back(getNumberOfModules(WritingModule));
01947   Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
01948   Stream.EmitRecord(SUBMODULE_METADATA, Record);
01949   
01950   // Write all of the submodules.
01951   std::queue<Module *> Q;
01952   Q.push(WritingModule);
01953   while (!Q.empty()) {
01954     Module *Mod = Q.front();
01955     Q.pop();
01956     unsigned ID = getSubmoduleID(Mod);
01957     
01958     // Emit the definition of the block.
01959     Record.clear();
01960     Record.push_back(SUBMODULE_DEFINITION);
01961     Record.push_back(ID);
01962     if (Mod->Parent) {
01963       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
01964       Record.push_back(SubmoduleIDs[Mod->Parent]);
01965     } else {
01966       Record.push_back(0);
01967     }
01968     Record.push_back(Mod->IsFramework);
01969     Record.push_back(Mod->IsExplicit);
01970     Record.push_back(Mod->IsSystem);
01971     Record.push_back(Mod->InferSubmodules);
01972     Record.push_back(Mod->InferExplicitSubmodules);
01973     Record.push_back(Mod->InferExportWildcard);
01974     Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
01975     
01976     // Emit the requirements.
01977     for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) {
01978       Record.clear();
01979       Record.push_back(SUBMODULE_REQUIRES);
01980       Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
01981                                 Mod->Requires[I].data(),
01982                                 Mod->Requires[I].size());
01983     }
01984 
01985     // Emit the umbrella header, if there is one.
01986     if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
01987       Record.clear();
01988       Record.push_back(SUBMODULE_UMBRELLA_HEADER);
01989       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 
01990                                 UmbrellaHeader->getName());
01991     } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
01992       Record.clear();
01993       Record.push_back(SUBMODULE_UMBRELLA_DIR);
01994       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 
01995                                 UmbrellaDir->getName());      
01996     }
01997     
01998     // Emit the headers.
01999     for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) {
02000       Record.clear();
02001       Record.push_back(SUBMODULE_HEADER);
02002       Stream.EmitRecordWithBlob(HeaderAbbrev, Record, 
02003                                 Mod->Headers[I]->getName());
02004     }
02005 
02006     // Emit the imports. 
02007     if (!Mod->Imports.empty()) {
02008       Record.clear();
02009       for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
02010         unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
02011         assert(ImportedID && "Unknown submodule!");                                           
02012         Record.push_back(ImportedID);
02013       }
02014       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
02015     }
02016 
02017     // Emit the exports. 
02018     if (!Mod->Exports.empty()) {
02019       Record.clear();
02020       for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
02021         if (Module *Exported = Mod->Exports[I].getPointer()) {
02022           unsigned ExportedID = SubmoduleIDs[Exported];
02023           assert(ExportedID > 0 && "Unknown submodule ID?");
02024           Record.push_back(ExportedID);
02025         } else {
02026           Record.push_back(0);
02027         }
02028         
02029         Record.push_back(Mod->Exports[I].getInt());
02030       }
02031       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
02032     }
02033     
02034     // Queue up the submodules of this module.
02035     for (Module::submodule_iterator Sub = Mod->submodule_begin(),
02036                                  SubEnd = Mod->submodule_end();
02037          Sub != SubEnd; ++Sub)
02038       Q.push(*Sub);
02039   }
02040   
02041   Stream.ExitBlock();
02042   
02043   assert((NextSubmoduleID - FirstSubmoduleID
02044             == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
02045 }
02046 
02047 serialization::SubmoduleID 
02048 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
02049   if (Loc.isInvalid() || !WritingModule)
02050     return 0; // No submodule
02051     
02052   // Find the module that owns this location.
02053   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
02054   Module *OwningMod 
02055     = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
02056   if (!OwningMod)
02057     return 0;
02058   
02059   // Check whether this submodule is part of our own module.
02060   if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
02061     return 0;
02062   
02063   return getSubmoduleID(OwningMod);
02064 }
02065 
02066 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) {
02067   RecordData Record;
02068   for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
02069          I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
02070          I != E; ++I) {
02071     const DiagnosticsEngine::DiagStatePoint &point = *I; 
02072     if (point.Loc.isInvalid())
02073       continue;
02074 
02075     Record.push_back(point.Loc.getRawEncoding());
02076     for (DiagnosticsEngine::DiagState::const_iterator
02077            I = point.State->begin(), E = point.State->end(); I != E; ++I) {
02078       if (I->second.isPragma()) {
02079         Record.push_back(I->first);
02080         Record.push_back(I->second.getMapping());
02081       }
02082     }
02083     Record.push_back(-1); // mark the end of the diag/map pairs for this
02084                           // location.
02085   }
02086 
02087   if (!Record.empty())
02088     Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
02089 }
02090 
02091 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
02092   if (CXXBaseSpecifiersOffsets.empty())
02093     return;
02094 
02095   RecordData Record;
02096 
02097   // Create a blob abbreviation for the C++ base specifiers offsets.
02098   using namespace llvm;
02099     
02100   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02101   Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
02102   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
02103   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02104   unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
02105   
02106   // Write the base specifier offsets table.
02107   Record.clear();
02108   Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
02109   Record.push_back(CXXBaseSpecifiersOffsets.size());
02110   Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
02111                             data(CXXBaseSpecifiersOffsets));
02112 }
02113 
02114 //===----------------------------------------------------------------------===//
02115 // Type Serialization
02116 //===----------------------------------------------------------------------===//
02117 
02118 /// \brief Write the representation of a type to the AST stream.
02119 void ASTWriter::WriteType(QualType T) {
02120   TypeIdx &Idx = TypeIdxs[T];
02121   if (Idx.getIndex() == 0) // we haven't seen this type before.
02122     Idx = TypeIdx(NextTypeID++);
02123 
02124   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
02125 
02126   // Record the offset for this type.
02127   unsigned Index = Idx.getIndex() - FirstTypeID;
02128   if (TypeOffsets.size() == Index)
02129     TypeOffsets.push_back(Stream.GetCurrentBitNo());
02130   else if (TypeOffsets.size() < Index) {
02131     TypeOffsets.resize(Index + 1);
02132     TypeOffsets[Index] = Stream.GetCurrentBitNo();
02133   }
02134 
02135   RecordData Record;
02136 
02137   // Emit the type's representation.
02138   ASTTypeWriter W(*this, Record);
02139 
02140   if (T.hasLocalNonFastQualifiers()) {
02141     Qualifiers Qs = T.getLocalQualifiers();
02142     AddTypeRef(T.getLocalUnqualifiedType(), Record);
02143     Record.push_back(Qs.getAsOpaqueValue());
02144     W.Code = TYPE_EXT_QUAL;
02145   } else {
02146     switch (T->getTypeClass()) {
02147       // For all of the concrete, non-dependent types, call the
02148       // appropriate visitor function.
02149 #define TYPE(Class, Base) \
02150     case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
02151 #define ABSTRACT_TYPE(Class, Base)
02152 #include "clang/AST/TypeNodes.def"
02153     }
02154   }
02155 
02156   // Emit the serialized record.
02157   Stream.EmitRecord(W.Code, Record);
02158 
02159   // Flush any expressions that were written as part of this type.
02160   FlushStmts();
02161 }
02162 
02163 //===----------------------------------------------------------------------===//
02164 // Declaration Serialization
02165 //===----------------------------------------------------------------------===//
02166 
02167 /// \brief Write the block containing all of the declaration IDs
02168 /// lexically declared within the given DeclContext.
02169 ///
02170 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
02171 /// bistream, or 0 if no block was written.
02172 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
02173                                                  DeclContext *DC) {
02174   if (DC->decls_empty())
02175     return 0;
02176 
02177   uint64_t Offset = Stream.GetCurrentBitNo();
02178   RecordData Record;
02179   Record.push_back(DECL_CONTEXT_LEXICAL);
02180   SmallVector<KindDeclIDPair, 64> Decls;
02181   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
02182          D != DEnd; ++D)
02183     Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D)));
02184 
02185   ++NumLexicalDeclContexts;
02186   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
02187   return Offset;
02188 }
02189 
02190 void ASTWriter::WriteTypeDeclOffsets() {
02191   using namespace llvm;
02192   RecordData Record;
02193 
02194   // Write the type offsets array
02195   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02196   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
02197   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
02198   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
02199   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
02200   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
02201   Record.clear();
02202   Record.push_back(TYPE_OFFSET);
02203   Record.push_back(TypeOffsets.size());
02204   Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
02205   Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
02206 
02207   // Write the declaration offsets array
02208   Abbrev = new BitCodeAbbrev();
02209   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
02210   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
02211   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
02212   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
02213   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
02214   Record.clear();
02215   Record.push_back(DECL_OFFSET);
02216   Record.push_back(DeclOffsets.size());
02217   Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
02218   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
02219 }
02220 
02221 void ASTWriter::WriteFileDeclIDsMap() {
02222   using namespace llvm;
02223   RecordData Record;
02224 
02225   // Join the vectors of DeclIDs from all files.
02226   SmallVector<DeclID, 256> FileSortedIDs;
02227   for (FileDeclIDsTy::iterator
02228          FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
02229     DeclIDInFileInfo &Info = *FI->second;
02230     Info.FirstDeclIndex = FileSortedIDs.size();
02231     for (LocDeclIDsTy::iterator
02232            DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
02233       FileSortedIDs.push_back(DI->second);
02234   }
02235 
02236   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02237   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
02238   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02239   unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
02240   Record.push_back(FILE_SORTED_DECLS);
02241   Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
02242 }
02243 
02244 //===----------------------------------------------------------------------===//
02245 // Global Method Pool and Selector Serialization
02246 //===----------------------------------------------------------------------===//
02247 
02248 namespace {
02249 // Trait used for the on-disk hash table used in the method pool.
02250 class ASTMethodPoolTrait {
02251   ASTWriter &Writer;
02252 
02253 public:
02254   typedef Selector key_type;
02255   typedef key_type key_type_ref;
02256 
02257   struct data_type {
02258     SelectorID ID;
02259     ObjCMethodList Instance, Factory;
02260   };
02261   typedef const data_type& data_type_ref;
02262 
02263   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
02264 
02265   static unsigned ComputeHash(Selector Sel) {
02266     return serialization::ComputeHash(Sel);
02267   }
02268 
02269   std::pair<unsigned,unsigned>
02270     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
02271                       data_type_ref Methods) {
02272     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
02273     clang::io::Emit16(Out, KeyLen);
02274     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
02275     for (const ObjCMethodList *Method = &Methods.Instance; Method;
02276          Method = Method->Next)
02277       if (Method->Method)
02278         DataLen += 4;
02279     for (const ObjCMethodList *Method = &Methods.Factory; Method;
02280          Method = Method->Next)
02281       if (Method->Method)
02282         DataLen += 4;
02283     clang::io::Emit16(Out, DataLen);
02284     return std::make_pair(KeyLen, DataLen);
02285   }
02286 
02287   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
02288     uint64_t Start = Out.tell();
02289     assert((Start >> 32) == 0 && "Selector key offset too large");
02290     Writer.SetSelectorOffset(Sel, Start);
02291     unsigned N = Sel.getNumArgs();
02292     clang::io::Emit16(Out, N);
02293     if (N == 0)
02294       N = 1;
02295     for (unsigned I = 0; I != N; ++I)
02296       clang::io::Emit32(Out,
02297                     Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
02298   }
02299 
02300   void EmitData(raw_ostream& Out, key_type_ref,
02301                 data_type_ref Methods, unsigned DataLen) {
02302     uint64_t Start = Out.tell(); (void)Start;
02303     clang::io::Emit32(Out, Methods.ID);
02304     unsigned NumInstanceMethods = 0;
02305     for (const ObjCMethodList *Method = &Methods.Instance; Method;
02306          Method = Method->Next)
02307       if (Method->Method)
02308         ++NumInstanceMethods;
02309 
02310     unsigned NumFactoryMethods = 0;
02311     for (const ObjCMethodList *Method = &Methods.Factory; Method;
02312          Method = Method->Next)
02313       if (Method->Method)
02314         ++NumFactoryMethods;
02315 
02316     clang::io::Emit16(Out, NumInstanceMethods);
02317     clang::io::Emit16(Out, NumFactoryMethods);
02318     for (const ObjCMethodList *Method = &Methods.Instance; Method;
02319          Method = Method->Next)
02320       if (Method->Method)
02321         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
02322     for (const ObjCMethodList *Method = &Methods.Factory; Method;
02323          Method = Method->Next)
02324       if (Method->Method)
02325         clang::io::Emit32(Out, Writer.getDeclID(Method->Method));
02326 
02327     assert(Out.tell() - Start == DataLen && "Data length is wrong");
02328   }
02329 };
02330 } // end anonymous namespace
02331 
02332 /// \brief Write ObjC data: selectors and the method pool.
02333 ///
02334 /// The method pool contains both instance and factory methods, stored
02335 /// in an on-disk hash table indexed by the selector. The hash table also
02336 /// contains an empty entry for every other selector known to Sema.
02337 void ASTWriter::WriteSelectors(Sema &SemaRef) {
02338   using namespace llvm;
02339 
02340   // Do we have to do anything at all?
02341   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
02342     return;
02343   unsigned NumTableEntries = 0;
02344   // Create and write out the blob that contains selectors and the method pool.
02345   {
02346     OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
02347     ASTMethodPoolTrait Trait(*this);
02348 
02349     // Create the on-disk hash table representation. We walk through every
02350     // selector we've seen and look it up in the method pool.
02351     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
02352     for (llvm::DenseMap<Selector, SelectorID>::iterator
02353              I = SelectorIDs.begin(), E = SelectorIDs.end();
02354          I != E; ++I) {
02355       Selector S = I->first;
02356       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
02357       ASTMethodPoolTrait::data_type Data = {
02358         I->second,
02359         ObjCMethodList(),
02360         ObjCMethodList()
02361       };
02362       if (F != SemaRef.MethodPool.end()) {
02363         Data.Instance = F->second.first;
02364         Data.Factory = F->second.second;
02365       }
02366       // Only write this selector if it's not in an existing AST or something
02367       // changed.
02368       if (Chain && I->second < FirstSelectorID) {
02369         // Selector already exists. Did it change?
02370         bool changed = false;
02371         for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
02372              M = M->Next) {
02373           if (!M->Method->isFromASTFile())
02374             changed = true;
02375         }
02376         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
02377              M = M->Next) {
02378           if (!M->Method->isFromASTFile())
02379             changed = true;
02380         }
02381         if (!changed)
02382           continue;
02383       } else if (Data.Instance.Method || Data.Factory.Method) {
02384         // A new method pool entry.
02385         ++NumTableEntries;
02386       }
02387       Generator.insert(S, Data, Trait);
02388     }
02389 
02390     // Create the on-disk hash table in a buffer.
02391     SmallString<4096> MethodPool;
02392     uint32_t BucketOffset;
02393     {
02394       ASTMethodPoolTrait Trait(*this);
02395       llvm::raw_svector_ostream Out(MethodPool);
02396       // Make sure that no bucket is at offset 0
02397       clang::io::Emit32(Out, 0);
02398       BucketOffset = Generator.Emit(Out, Trait);
02399     }
02400 
02401     // Create a blob abbreviation
02402     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02403     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
02404     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
02405     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
02406     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02407     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
02408 
02409     // Write the method pool
02410     RecordData Record;
02411     Record.push_back(METHOD_POOL);
02412     Record.push_back(BucketOffset);
02413     Record.push_back(NumTableEntries);
02414     Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
02415 
02416     // Create a blob abbreviation for the selector table offsets.
02417     Abbrev = new BitCodeAbbrev();
02418     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
02419     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
02420     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
02421     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02422     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
02423 
02424     // Write the selector offsets table.
02425     Record.clear();
02426     Record.push_back(SELECTOR_OFFSETS);
02427     Record.push_back(SelectorOffsets.size());
02428     Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
02429     Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
02430                               data(SelectorOffsets));
02431   }
02432 }
02433 
02434 /// \brief Write the selectors referenced in @selector expression into AST file.
02435 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
02436   using namespace llvm;
02437   if (SemaRef.ReferencedSelectors.empty())
02438     return;
02439 
02440   RecordData Record;
02441 
02442   // Note: this writes out all references even for a dependent AST. But it is
02443   // very tricky to fix, and given that @selector shouldn't really appear in
02444   // headers, probably not worth it. It's not a correctness issue.
02445   for (DenseMap<Selector, SourceLocation>::iterator S =
02446        SemaRef.ReferencedSelectors.begin(),
02447        E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
02448     Selector Sel = (*S).first;
02449     SourceLocation Loc = (*S).second;
02450     AddSelectorRef(Sel, Record);
02451     AddSourceLocation(Loc, Record);
02452   }
02453   Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
02454 }
02455 
02456 //===----------------------------------------------------------------------===//
02457 // Identifier Table Serialization
02458 //===----------------------------------------------------------------------===//
02459 
02460 namespace {
02461 class ASTIdentifierTableTrait {
02462   ASTWriter &Writer;
02463   Preprocessor &PP;
02464   IdentifierResolver &IdResolver;
02465   bool IsModule;
02466   
02467   /// \brief Determines whether this is an "interesting" identifier
02468   /// that needs a full IdentifierInfo structure written into the hash
02469   /// table.
02470   bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) {
02471     if (II->isPoisoned() ||
02472         II->isExtensionToken() ||
02473         II->getObjCOrBuiltinID() ||
02474         II->hasRevertedTokenIDToIdentifier() ||
02475         II->getFETokenInfo<void>())
02476       return true;
02477 
02478     return hasMacroDefinition(II, Macro);
02479   }
02480   
02481   bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) {
02482     if (!II->hasMacroDefinition())
02483       return false;
02484     
02485     if (Macro || (Macro = PP.getMacroInfo(II)))
02486       return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic());
02487     
02488     return false;    
02489   }
02490 
02491 public:
02492   typedef IdentifierInfo* key_type;
02493   typedef key_type  key_type_ref;
02494 
02495   typedef IdentID data_type;
02496   typedef data_type data_type_ref;
02497 
02498   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 
02499                           IdentifierResolver &IdResolver, bool IsModule)
02500     : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
02501 
02502   static unsigned ComputeHash(const IdentifierInfo* II) {
02503     return llvm::HashString(II->getName());
02504   }
02505 
02506   std::pair<unsigned,unsigned>
02507   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
02508     unsigned KeyLen = II->getLength() + 1;
02509     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
02510     MacroInfo *Macro = 0;
02511     if (isInterestingIdentifier(II, Macro)) {
02512       DataLen += 2; // 2 bytes for builtin ID, flags
02513       if (hasMacroDefinition(II, Macro))
02514         DataLen += 8;
02515       
02516       for (IdentifierResolver::iterator D = IdResolver.begin(II),
02517                                      DEnd = IdResolver.end();
02518            D != DEnd; ++D)
02519         DataLen += sizeof(DeclID);
02520     }
02521     clang::io::Emit16(Out, DataLen);
02522     // We emit the key length after the data length so that every
02523     // string is preceded by a 16-bit length. This matches the PTH
02524     // format for storing identifiers.
02525     clang::io::Emit16(Out, KeyLen);
02526     return std::make_pair(KeyLen, DataLen);
02527   }
02528 
02529   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
02530                unsigned KeyLen) {
02531     // Record the location of the key data.  This is used when generating
02532     // the mapping from persistent IDs to strings.
02533     Writer.SetIdentifierOffset(II, Out.tell());
02534     Out.write(II->getNameStart(), KeyLen);
02535   }
02536 
02537   void EmitData(raw_ostream& Out, IdentifierInfo* II,
02538                 IdentID ID, unsigned) {
02539     MacroInfo *Macro = 0;
02540     if (!isInterestingIdentifier(II, Macro)) {
02541       clang::io::Emit32(Out, ID << 1);
02542       return;
02543     }
02544 
02545     clang::io::Emit32(Out, (ID << 1) | 0x01);
02546     uint32_t Bits = 0;
02547     bool HasMacroDefinition = hasMacroDefinition(II, Macro);
02548     Bits = (uint32_t)II->getObjCOrBuiltinID();
02549     assert((Bits & 0x7ff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
02550     Bits = (Bits << 1) | unsigned(HasMacroDefinition);
02551     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
02552     Bits = (Bits << 1) | unsigned(II->isPoisoned());
02553     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
02554     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
02555     clang::io::Emit16(Out, Bits);
02556 
02557     if (HasMacroDefinition) {
02558       clang::io::Emit32(Out, Writer.getMacroOffset(II));
02559       clang::io::Emit32(Out, 
02560         Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc()));
02561     }
02562     
02563     // Emit the declaration IDs in reverse order, because the
02564     // IdentifierResolver provides the declarations as they would be
02565     // visible (e.g., the function "stat" would come before the struct
02566     // "stat"), but the ASTReader adds declarations to the end of the list 
02567     // (so we need to see the struct "status" before the function "status").
02568     // Only emit declarations that aren't from a chained PCH, though.
02569     SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
02570                                   IdResolver.end());
02571     for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(),
02572                                                 DEnd = Decls.rend();
02573          D != DEnd; ++D)
02574       clang::io::Emit32(Out, Writer.getDeclID(*D));
02575   }
02576 };
02577 } // end anonymous namespace
02578 
02579 /// \brief Write the identifier table into the AST file.
02580 ///
02581 /// The identifier table consists of a blob containing string data
02582 /// (the actual identifiers themselves) and a separate "offsets" index
02583 /// that maps identifier IDs to locations within the blob.
02584 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 
02585                                      IdentifierResolver &IdResolver,
02586                                      bool IsModule) {
02587   using namespace llvm;
02588 
02589   // Create and write out the blob that contains the identifier
02590   // strings.
02591   {
02592     OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
02593     ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
02594 
02595     // Look for any identifiers that were named while processing the
02596     // headers, but are otherwise not needed. We add these to the hash
02597     // table to enable checking of the predefines buffer in the case
02598     // where the user adds new macro definitions when building the AST
02599     // file.
02600     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
02601                                 IDEnd = PP.getIdentifierTable().end();
02602          ID != IDEnd; ++ID)
02603       getIdentifierRef(ID->second);
02604 
02605     // Create the on-disk hash table representation. We only store offsets
02606     // for identifiers that appear here for the first time.
02607     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
02608     for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
02609            ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
02610          ID != IDEnd; ++ID) {
02611       assert(ID->first && "NULL identifier in identifier table");
02612       if (!Chain || !ID->first->isFromAST() || 
02613           ID->first->hasChangedSinceDeserialization())
02614         Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 
02615                          Trait);
02616     }
02617 
02618     // Create the on-disk hash table in a buffer.
02619     SmallString<4096> IdentifierTable;
02620     uint32_t BucketOffset;
02621     {
02622       ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
02623       llvm::raw_svector_ostream Out(IdentifierTable);
02624       // Make sure that no bucket is at offset 0
02625       clang::io::Emit32(Out, 0);
02626       BucketOffset = Generator.Emit(Out, Trait);
02627     }
02628 
02629     // Create a blob abbreviation
02630     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02631     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
02632     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
02633     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02634     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
02635 
02636     // Write the identifier table
02637     RecordData Record;
02638     Record.push_back(IDENTIFIER_TABLE);
02639     Record.push_back(BucketOffset);
02640     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
02641   }
02642 
02643   // Write the offsets table for identifier IDs.
02644   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02645   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
02646   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
02647   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
02648   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02649   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
02650 
02651   RecordData Record;
02652   Record.push_back(IDENTIFIER_OFFSET);
02653   Record.push_back(IdentifierOffsets.size());
02654   Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
02655   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
02656                             data(IdentifierOffsets));
02657 }
02658 
02659 //===----------------------------------------------------------------------===//
02660 // DeclContext's Name Lookup Table Serialization
02661 //===----------------------------------------------------------------------===//
02662 
02663 namespace {
02664 // Trait used for the on-disk hash table used in the method pool.
02665 class ASTDeclContextNameLookupTrait {
02666   ASTWriter &Writer;
02667 
02668 public:
02669   typedef DeclarationName key_type;
02670   typedef key_type key_type_ref;
02671 
02672   typedef DeclContext::lookup_result data_type;
02673   typedef const data_type& data_type_ref;
02674 
02675   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
02676 
02677   unsigned ComputeHash(DeclarationName Name) {
02678     llvm::FoldingSetNodeID ID;
02679     ID.AddInteger(Name.getNameKind());
02680 
02681     switch (Name.getNameKind()) {
02682     case DeclarationName::Identifier:
02683       ID.AddString(Name.getAsIdentifierInfo()->getName());
02684       break;
02685     case DeclarationName::ObjCZeroArgSelector:
02686     case DeclarationName::ObjCOneArgSelector:
02687     case DeclarationName::ObjCMultiArgSelector:
02688       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
02689       break;
02690     case DeclarationName::CXXConstructorName:
02691     case DeclarationName::CXXDestructorName:
02692     case DeclarationName::CXXConversionFunctionName:
02693       break;
02694     case DeclarationName::CXXOperatorName:
02695       ID.AddInteger(Name.getCXXOverloadedOperator());
02696       break;
02697     case DeclarationName::CXXLiteralOperatorName:
02698       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
02699     case DeclarationName::CXXUsingDirective:
02700       break;
02701     }
02702 
02703     return ID.ComputeHash();
02704   }
02705 
02706   std::pair<unsigned,unsigned>
02707     EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
02708                       data_type_ref Lookup) {
02709     unsigned KeyLen = 1;
02710     switch (Name.getNameKind()) {
02711     case DeclarationName::Identifier:
02712     case DeclarationName::ObjCZeroArgSelector:
02713     case DeclarationName::ObjCOneArgSelector:
02714     case DeclarationName::ObjCMultiArgSelector:
02715     case DeclarationName::CXXLiteralOperatorName:
02716       KeyLen += 4;
02717       break;
02718     case DeclarationName::CXXOperatorName:
02719       KeyLen += 1;
02720       break;
02721     case DeclarationName::CXXConstructorName:
02722     case DeclarationName::CXXDestructorName:
02723     case DeclarationName::CXXConversionFunctionName:
02724     case DeclarationName::CXXUsingDirective:
02725       break;
02726     }
02727     clang::io::Emit16(Out, KeyLen);
02728 
02729     // 2 bytes for num of decls and 4 for each DeclID.
02730     unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first);
02731     clang::io::Emit16(Out, DataLen);
02732 
02733     return std::make_pair(KeyLen, DataLen);
02734   }
02735 
02736   void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
02737     using namespace clang::io;
02738 
02739     assert(Name.getNameKind() < 0x100 && "Invalid name kind ?");
02740     Emit8(Out, Name.getNameKind());
02741     switch (Name.getNameKind()) {
02742     case DeclarationName::Identifier:
02743       Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
02744       break;
02745     case DeclarationName::ObjCZeroArgSelector:
02746     case DeclarationName::ObjCOneArgSelector:
02747     case DeclarationName::ObjCMultiArgSelector:
02748       Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector()));
02749       break;
02750     case DeclarationName::CXXOperatorName:
02751       assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?");
02752       Emit8(Out, Name.getCXXOverloadedOperator());
02753       break;
02754     case DeclarationName::CXXLiteralOperatorName:
02755       Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
02756       break;
02757     case DeclarationName::CXXConstructorName:
02758     case DeclarationName::CXXDestructorName:
02759     case DeclarationName::CXXConversionFunctionName:
02760     case DeclarationName::CXXUsingDirective:
02761       break;
02762     }
02763   }
02764 
02765   void EmitData(raw_ostream& Out, key_type_ref,
02766                 data_type Lookup, unsigned DataLen) {
02767     uint64_t Start = Out.tell(); (void)Start;
02768     clang::io::Emit16(Out, Lookup.second - Lookup.first);
02769     for (; Lookup.first != Lookup.second; ++Lookup.first)
02770       clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first));
02771 
02772     assert(Out.tell() - Start == DataLen && "Data length is wrong");
02773   }
02774 };
02775 } // end anonymous namespace
02776 
02777 /// \brief Write the block containing all of the declaration IDs
02778 /// visible from the given DeclContext.
02779 ///
02780 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
02781 /// bitstream, or 0 if no block was written.
02782 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
02783                                                  DeclContext *DC) {
02784   if (DC->getPrimaryContext() != DC)
02785     return 0;
02786 
02787   // Since there is no name lookup into functions or methods, don't bother to
02788   // build a visible-declarations table for these entities.
02789   if (DC->isFunctionOrMethod())
02790     return 0;
02791 
02792   // If not in C++, we perform name lookup for the translation unit via the
02793   // IdentifierInfo chains, don't bother to build a visible-declarations table.
02794   // FIXME: In C++ we need the visible declarations in order to "see" the
02795   // friend declarations, is there a way to do this without writing the table ?
02796   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
02797     return 0;
02798 
02799   // Serialize the contents of the mapping used for lookup. Note that,
02800   // although we have two very different code paths, the serialized
02801   // representation is the same for both cases: a declaration name,
02802   // followed by a size, followed by references to the visible
02803   // declarations that have that name.
02804   uint64_t Offset = Stream.GetCurrentBitNo();
02805   StoredDeclsMap *Map = DC->buildLookup();
02806   if (!Map || Map->empty())
02807     return 0;
02808 
02809   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
02810   ASTDeclContextNameLookupTrait Trait(*this);
02811 
02812   // Create the on-disk hash table representation.
02813   DeclarationName ConversionName;
02814   llvm::SmallVector<NamedDecl *, 4> ConversionDecls;
02815   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
02816        D != DEnd; ++D) {
02817     DeclarationName Name = D->first;
02818     DeclContext::lookup_result Result = D->second.getLookupResult();
02819     if (Result.first != Result.second) {
02820       if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
02821         // Hash all conversion function names to the same name. The actual
02822         // type information in conversion function name is not used in the
02823         // key (since such type information is not stable across different
02824         // modules), so the intended effect is to coalesce all of the conversion
02825         // functions under a single key.
02826         if (!ConversionName)
02827           ConversionName = Name;
02828         ConversionDecls.append(Result.first, Result.second);
02829         continue;
02830       }
02831       
02832       Generator.insert(Name, Result, Trait);
02833     }
02834   }
02835 
02836   // Add the conversion functions
02837   if (!ConversionDecls.empty()) {
02838     Generator.insert(ConversionName, 
02839                      DeclContext::lookup_result(ConversionDecls.begin(),
02840                                                 ConversionDecls.end()),
02841                      Trait);
02842   }
02843   
02844   // Create the on-disk hash table in a buffer.
02845   SmallString<4096> LookupTable;
02846   uint32_t BucketOffset;
02847   {
02848     llvm::raw_svector_ostream Out(LookupTable);
02849     // Make sure that no bucket is at offset 0
02850     clang::io::Emit32(Out, 0);
02851     BucketOffset = Generator.Emit(Out, Trait);
02852   }
02853 
02854   // Write the lookup table
02855   RecordData Record;
02856   Record.push_back(DECL_CONTEXT_VISIBLE);
02857   Record.push_back(BucketOffset);
02858   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
02859                             LookupTable.str());
02860 
02861   Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
02862   ++NumVisibleDeclContexts;
02863   return Offset;
02864 }
02865 
02866 /// \brief Write an UPDATE_VISIBLE block for the given context.
02867 ///
02868 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
02869 /// DeclContext in a dependent AST file. As such, they only exist for the TU
02870 /// (in C++), for namespaces, and for classes with forward-declared unscoped
02871 /// enumeration members (in C++11).
02872 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
02873   StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr());
02874   if (!Map || Map->empty())
02875     return;
02876 
02877   OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator;
02878   ASTDeclContextNameLookupTrait Trait(*this);
02879 
02880   // Create the hash table.
02881   for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
02882        D != DEnd; ++D) {
02883     DeclarationName Name = D->first;
02884     DeclContext::lookup_result Result = D->second.getLookupResult();
02885     // For any name that appears in this table, the results are complete, i.e.
02886     // they overwrite results from previous PCHs. Merging is always a mess.
02887     if (Result.first != Result.second)
02888       Generator.insert(Name, Result, Trait);
02889   }
02890 
02891   // Create the on-disk hash table in a buffer.
02892   SmallString<4096> LookupTable;
02893   uint32_t BucketOffset;
02894   {
02895     llvm::raw_svector_ostream Out(LookupTable);
02896     // Make sure that no bucket is at offset 0
02897     clang::io::Emit32(Out, 0);
02898     BucketOffset = Generator.Emit(Out, Trait);
02899   }
02900 
02901   // Write the lookup table
02902   RecordData Record;
02903   Record.push_back(UPDATE_VISIBLE);
02904   Record.push_back(getDeclID(cast<Decl>(DC)));
02905   Record.push_back(BucketOffset);
02906   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
02907 }
02908 
02909 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
02910 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
02911   RecordData Record;
02912   Record.push_back(Opts.fp_contract);
02913   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
02914 }
02915 
02916 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
02917 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
02918   if (!SemaRef.Context.getLangOpts().OpenCL)
02919     return;
02920 
02921   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
02922   RecordData Record;
02923 #define OPENCLEXT(nm)  Record.push_back(Opts.nm);
02924 #include "clang/Basic/OpenCLExtensions.def"
02925   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
02926 }
02927 
02928 void ASTWriter::WriteRedeclarations() {
02929   RecordData LocalRedeclChains;
02930   SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
02931 
02932   for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
02933     Decl *First = Redeclarations[I];
02934     assert(First->getPreviousDecl() == 0 && "Not the first declaration?");
02935     
02936     Decl *MostRecent = First->getMostRecentDecl();
02937     
02938     // If we only have a single declaration, there is no point in storing
02939     // a redeclaration chain.
02940     if (First == MostRecent)
02941       continue;
02942     
02943     unsigned Offset = LocalRedeclChains.size();
02944     unsigned Size = 0;
02945     LocalRedeclChains.push_back(0); // Placeholder for the size.
02946     
02947     // Collect the set of local redeclarations of this declaration.
02948     for (Decl *Prev = MostRecent; Prev != First; 
02949          Prev = Prev->getPreviousDecl()) { 
02950       if (!Prev->isFromASTFile()) {
02951         AddDeclRef(Prev, LocalRedeclChains);
02952         ++Size;
02953       }
02954     }
02955     LocalRedeclChains[Offset] = Size;
02956     
02957     // Reverse the set of local redeclarations, so that we store them in
02958     // order (since we found them in reverse order).
02959     std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
02960     
02961     // Add the mapping from the first ID to the set of local declarations.
02962     LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
02963     LocalRedeclsMap.push_back(Info);
02964     
02965     assert(N == Redeclarations.size() && 
02966            "Deserialized a declaration we shouldn't have");
02967   }
02968   
02969   if (LocalRedeclChains.empty())
02970     return;
02971   
02972   // Sort the local redeclarations map by the first declaration ID,
02973   // since the reader will be performing binary searches on this information.
02974   llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
02975   
02976   // Emit the local redeclarations map.
02977   using namespace llvm;
02978   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
02979   Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
02980   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
02981   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
02982   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
02983   
02984   RecordData Record;
02985   Record.push_back(LOCAL_REDECLARATIONS_MAP);
02986   Record.push_back(LocalRedeclsMap.size());
02987   Stream.EmitRecordWithBlob(AbbrevID, Record, 
02988     reinterpret_cast<char*>(LocalRedeclsMap.data()),
02989     LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
02990 
02991   // Emit the redeclaration chains.
02992   Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
02993 }
02994 
02995 void ASTWriter::WriteObjCCategories() {
02996   llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
02997   RecordData Categories;
02998   
02999   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
03000     unsigned Size = 0;
03001     unsigned StartIndex = Categories.size();
03002     
03003     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
03004     
03005     // Allocate space for the size.
03006     Categories.push_back(0);
03007     
03008     // Add the categories.
03009     for (ObjCCategoryDecl *Cat = Class->getCategoryList();
03010          Cat; Cat = Cat->getNextClassCategory(), ++Size) {
03011       assert(getDeclID(Cat) != 0 && "Bogus category");
03012       AddDeclRef(Cat, Categories);
03013     }
03014     
03015     // Update the size.
03016     Categories[StartIndex] = Size;
03017     
03018     // Record this interface -> category map.
03019     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
03020     CategoriesMap.push_back(CatInfo);
03021   }
03022 
03023   // Sort the categories map by the definition ID, since the reader will be
03024   // performing binary searches on this information.
03025   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
03026 
03027   // Emit the categories map.
03028   using namespace llvm;
03029   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
03030   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
03031   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
03032   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
03033   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
03034   
03035   RecordData Record;
03036   Record.push_back(OBJC_CATEGORIES_MAP);
03037   Record.push_back(CategoriesMap.size());
03038   Stream.EmitRecordWithBlob(AbbrevID, Record, 
03039                             reinterpret_cast<char*>(CategoriesMap.data()),
03040                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
03041   
03042   // Emit the category lists.
03043   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
03044 }
03045 
03046 void ASTWriter::WriteMergedDecls() {
03047   if (!Chain || Chain->MergedDecls.empty())
03048     return;
03049   
03050   RecordData Record;
03051   for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
03052                                         IEnd = Chain->MergedDecls.end();
03053        I != IEnd; ++I) {
03054     DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
03055                                               : getDeclID(I->first);
03056     assert(CanonID && "Merged declaration not known?");
03057     
03058     Record.push_back(CanonID);
03059     Record.push_back(I->second.size());
03060     Record.append(I->second.begin(), I->second.end());
03061   }
03062   Stream.EmitRecord(MERGED_DECLARATIONS, Record);
03063 }
03064 
03065 //===----------------------------------------------------------------------===//
03066 // General Serialization Routines
03067 //===----------------------------------------------------------------------===//
03068 
03069 /// \brief Write a record containing the given attributes.
03070 void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) {
03071   Record.push_back(Attrs.size());
03072   for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){
03073     const Attr * A = *i;
03074     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
03075     AddSourceRange(A->getRange(), Record);
03076 
03077 #include "clang/Serialization/AttrPCHWrite.inc"
03078 
03079   }
03080 }
03081 
03082 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
03083   Record.push_back(Str.size());
03084   Record.insert(Record.end(), Str.begin(), Str.end());
03085 }
03086 
03087 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
03088                                 RecordDataImpl &Record) {
03089   Record.push_back(Version.getMajor());
03090   if (llvm::Optional<unsigned> Minor = Version.getMinor())
03091     Record.push_back(*Minor + 1);
03092   else
03093     Record.push_back(0);
03094   if (llvm::Optional<unsigned> Subminor = Version.getSubminor())
03095     Record.push_back(*Subminor + 1);
03096   else
03097     Record.push_back(0);
03098 }
03099 
03100 /// \brief Note that the identifier II occurs at the given offset
03101 /// within the identifier table.
03102 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
03103   IdentID ID = IdentifierIDs[II];
03104   // Only store offsets new to this AST file. Other identifier names are looked
03105   // up earlier in the chain and thus don't need an offset.
03106   if (ID >= FirstIdentID)
03107     IdentifierOffsets[ID - FirstIdentID] = Offset;
03108 }
03109 
03110 /// \brief Note that the selector Sel occurs at the given offset
03111 /// within the method pool/selector table.
03112 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
03113   unsigned ID = SelectorIDs[Sel];
03114   assert(ID && "Unknown selector");
03115   // Don't record offsets for selectors that are also available in a different
03116   // file.
03117   if (ID < FirstSelectorID)
03118     return;
03119   SelectorOffsets[ID - FirstSelectorID] = Offset;
03120 }
03121 
03122 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
03123   : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0),
03124     WritingAST(false), ASTHasCompilerErrors(false),
03125     FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
03126     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
03127     FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 
03128     FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS), 
03129     NextSubmoduleID(FirstSubmoduleID),
03130     FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
03131     CollectedStmts(&StmtsToEmit),
03132     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
03133     NumVisibleDeclContexts(0),
03134     NextCXXBaseSpecifiersID(1),
03135     DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
03136     DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
03137     DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
03138     DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
03139     DeclTypedefAbbrev(0),
03140     DeclVarAbbrev(0), DeclFieldAbbrev(0),
03141     DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
03142 {
03143 }
03144 
03145 ASTWriter::~ASTWriter() {
03146   for (FileDeclIDsTy::iterator
03147          I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I)
03148     delete I->second;
03149 }
03150 
03151 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls,
03152                          const std::string &OutputFile,
03153                          Module *WritingModule, StringRef isysroot,
03154                          bool hasErrors) {
03155   WritingAST = true;
03156   
03157   ASTHasCompilerErrors = hasErrors;
03158   
03159   // Emit the file header.
03160   Stream.Emit((unsigned)'C', 8);
03161   Stream.Emit((unsigned)'P', 8);
03162   Stream.Emit((unsigned)'C', 8);
03163   Stream.Emit((unsigned)'H', 8);
03164 
03165   WriteBlockInfoBlock();
03166 
03167   Context = &SemaRef.Context;
03168   PP = &SemaRef.PP;
03169   this->WritingModule = WritingModule;
03170   WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule);
03171   Context = 0;
03172   PP = 0;
03173   this->WritingModule = 0;
03174   
03175   WritingAST = false;
03176 }
03177 
03178 template<typename Vector>
03179 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
03180                                ASTWriter::RecordData &Record) {
03181   for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end();
03182        I != E; ++I)  {
03183     Writer.AddDeclRef(*I, Record);
03184   }
03185 }
03186 
03187 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls,
03188                              StringRef isysroot,
03189                              const std::string &OutputFile, 
03190                              Module *WritingModule) {
03191   using namespace llvm;
03192 
03193   // Make sure that the AST reader knows to finalize itself.
03194   if (Chain)
03195     Chain->finalizeForWriting();
03196   
03197   ASTContext &Context = SemaRef.Context;
03198   Preprocessor &PP = SemaRef.PP;
03199 
03200   // Set up predefined declaration IDs.
03201   DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
03202   if (Context.ObjCIdDecl)
03203     DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
03204   if (Context.ObjCSelDecl)
03205     DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
03206   if (Context.ObjCClassDecl)
03207     DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
03208   if (Context.ObjCProtocolClassDecl)
03209     DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
03210   if (Context.Int128Decl)
03211     DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
03212   if (Context.UInt128Decl)
03213     DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
03214   if (Context.ObjCInstanceTypeDecl)
03215     DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
03216   
03217   if (!Chain) {
03218     // Make sure that we emit IdentifierInfos (and any attached
03219     // declarations) for builtins. We don't need to do this when we're
03220     // emitting chained PCH files, because all of the builtins will be
03221     // in the original PCH file.
03222     // FIXME: Modules won't like this at all.
03223     IdentifierTable &Table = PP.getIdentifierTable();
03224     SmallVector<const char *, 32> BuiltinNames;
03225     Context.BuiltinInfo.GetBuiltinNames(BuiltinNames,
03226                                         Context.getLangOpts().NoBuiltin);
03227     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
03228       getIdentifierRef(&Table.get(BuiltinNames[I]));
03229   }
03230 
03231   // If there are any out-of-date identifiers, bring them up to date.
03232   if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
03233     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
03234                                 IDEnd = PP.getIdentifierTable().end();
03235          ID != IDEnd; ++ID)
03236       if (ID->second->isOutOfDate())
03237         ExtSource->updateOutOfDateIdentifier(*ID->second);
03238   }
03239 
03240   // Build a record containing all of the tentative definitions in this file, in
03241   // TentativeDefinitions order.  Generally, this record will be empty for
03242   // headers.
03243   RecordData TentativeDefinitions;
03244   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
03245   
03246   // Build a record containing all of the file scoped decls in this file.
03247   RecordData UnusedFileScopedDecls;
03248   AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 
03249                      UnusedFileScopedDecls);
03250 
03251   // Build a record containing all of the delegating constructors we still need
03252   // to resolve.
03253   RecordData DelegatingCtorDecls;
03254   AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
03255 
03256   // Write the set of weak, undeclared identifiers. We always write the
03257   // entire table, since later PCH files in a PCH chain are only interested in
03258   // the results at the end of the chain.
03259   RecordData WeakUndeclaredIdentifiers;
03260   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
03261     for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
03262          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
03263          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
03264       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
03265       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
03266       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
03267       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
03268     }
03269   }
03270 
03271   // Build a record containing all of the locally-scoped external
03272   // declarations in this header file. Generally, this record will be
03273   // empty.
03274   RecordData LocallyScopedExternalDecls;
03275   // FIXME: This is filling in the AST file in densemap order which is
03276   // nondeterminstic!
03277   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
03278          TD = SemaRef.LocallyScopedExternalDecls.begin(),
03279          TDEnd = SemaRef.LocallyScopedExternalDecls.end();
03280        TD != TDEnd; ++TD) {
03281     if (!TD->second->isFromASTFile())
03282       AddDeclRef(TD->second, LocallyScopedExternalDecls);
03283   }
03284   
03285   // Build a record containing all of the ext_vector declarations.
03286   RecordData ExtVectorDecls;
03287   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
03288 
03289   // Build a record containing all of the VTable uses information.
03290   RecordData VTableUses;
03291   if (!SemaRef.VTableUses.empty()) {
03292     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
03293       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
03294       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
03295       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
03296     }
03297   }
03298 
03299   // Build a record containing all of dynamic classes declarations.
03300   RecordData DynamicClasses;
03301   AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
03302 
03303   // Build a record containing all of pending implicit instantiations.
03304   RecordData PendingInstantiations;
03305   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
03306          I = SemaRef.PendingInstantiations.begin(),
03307          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
03308     AddDeclRef(I->first, PendingInstantiations);
03309     AddSourceLocation(I->second, PendingInstantiations);
03310   }
03311   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
03312          "There are local ones at end of translation unit!");
03313 
03314   // Build a record containing some declaration references.
03315   RecordData SemaDeclRefs;
03316   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
03317     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
03318     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
03319   }
03320 
03321   RecordData CUDASpecialDeclRefs;
03322   if (Context.getcudaConfigureCallDecl()) {
03323     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
03324   }
03325 
03326   // Build a record containing all of the known namespaces.
03327   RecordData KnownNamespaces;
03328   for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 
03329             I = SemaRef.KnownNamespaces.begin(),
03330          IEnd = SemaRef.KnownNamespaces.end();
03331        I != IEnd; ++I) {
03332     if (!I->second)
03333       AddDeclRef(I->first, KnownNamespaces);
03334   }
03335   
03336   // Write the remaining AST contents.
03337   RecordData Record;
03338   Stream.EnterSubblock(AST_BLOCK_ID, 5);
03339   WriteMetadata(Context, isysroot, OutputFile);
03340   WriteLanguageOptions(Context.getLangOpts());
03341   if (StatCalls && isysroot.empty())
03342     WriteStatCache(*StatCalls);
03343 
03344   // Create a lexical update block containing all of the declarations in the
03345   // translation unit that do not come from other AST files.
03346   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
03347   SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
03348   for (DeclContext::decl_iterator I = TU->noload_decls_begin(),
03349                                   E = TU->noload_decls_end();
03350        I != E; ++I) {
03351     if (!(*I)->isFromASTFile())
03352       NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I)));
03353   }
03354   
03355   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
03356   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
03357   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
03358   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
03359   Record.clear();
03360   Record.push_back(TU_UPDATE_LEXICAL);
03361   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
03362                             data(NewGlobalDecls));
03363   
03364   // And a visible updates block for the translation unit.
03365   Abv = new llvm::BitCodeAbbrev();
03366   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
03367   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
03368   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
03369   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
03370   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
03371   WriteDeclContextVisibleUpdate(TU);
03372   
03373   // If the translation unit has an anonymous namespace, and we don't already
03374   // have an update block for it, write it as an update block.
03375   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
03376     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
03377     if (Record.empty()) {
03378       Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
03379       Record.push_back(reinterpret_cast<uint64_t>(NS));
03380     }
03381   }
03382   
03383   // Resolve any declaration pointers within the declaration updates block.
03384   ResolveDeclUpdatesBlocks();
03385   
03386   // Form the record of special types.
03387   RecordData SpecialTypes;
03388   AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes);
03389   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
03390   AddTypeRef(Context.getFILEType(), SpecialTypes);
03391   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
03392   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
03393   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
03394   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
03395   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
03396   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
03397 
03398   // Keep writing types and declarations until all types and
03399   // declarations have been written.
03400   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
03401   WriteDeclsBlockAbbrevs();
03402   for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 
03403                                   E = DeclsToRewrite.end(); 
03404        I != E; ++I)
03405     DeclTypesToEmit.push(const_cast<Decl*>(*I));
03406   while (!DeclTypesToEmit.empty()) {
03407     DeclOrType DOT = DeclTypesToEmit.front();
03408     DeclTypesToEmit.pop();
03409     if (DOT.isType())
03410       WriteType(DOT.getType());
03411     else
03412       WriteDecl(Context, DOT.getDecl());
03413   }
03414   Stream.ExitBlock();
03415 
03416   WriteFileDeclIDsMap();
03417   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
03418   
03419   if (Chain) {
03420     // Write the mapping information describing our module dependencies and how
03421     // each of those modules were mapped into our own offset/ID space, so that
03422     // the reader can build the appropriate mapping to its own offset/ID space.
03423     // The map consists solely of a blob with the following format:
03424     // *(module-name-len:i16 module-name:len*i8
03425     //   source-location-offset:i32
03426     //   identifier-id:i32
03427     //   preprocessed-entity-id:i32
03428     //   macro-definition-id:i32
03429     //   submodule-id:i32
03430     //   selector-id:i32
03431     //   declaration-id:i32
03432     //   c++-base-specifiers-id:i32
03433     //   type-id:i32)
03434     // 
03435     llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
03436     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
03437     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
03438     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
03439     SmallString<2048> Buffer;
03440     {
03441       llvm::raw_svector_ostream Out(Buffer);
03442       for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
03443                                            MEnd = Chain->ModuleMgr.end();
03444            M != MEnd; ++M) {
03445         StringRef FileName = (*M)->FileName;
03446         io::Emit16(Out, FileName.size());
03447         Out.write(FileName.data(), FileName.size());
03448         io::Emit32(Out, (*M)->SLocEntryBaseOffset);
03449         io::Emit32(Out, (*M)->BaseIdentifierID);
03450         io::Emit32(Out, (*M)->BasePreprocessedEntityID);
03451         io::Emit32(Out, (*M)->BaseSubmoduleID);
03452         io::Emit32(Out, (*M)->BaseSelectorID);
03453         io::Emit32(Out, (*M)->BaseDeclID);
03454         io::Emit32(Out, (*M)->BaseTypeIndex);
03455       }
03456     }
03457     Record.clear();
03458     Record.push_back(MODULE_OFFSET_MAP);
03459     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
03460                               Buffer.data(), Buffer.size());
03461   }
03462   WritePreprocessor(PP, WritingModule != 0);
03463   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
03464   WriteSelectors(SemaRef);
03465   WriteReferencedSelectorsPool(SemaRef);
03466   WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0);
03467   WriteFPPragmaOptions(SemaRef.getFPOptions());
03468   WriteOpenCLExtensions(SemaRef);
03469 
03470   WriteTypeDeclOffsets();
03471   WritePragmaDiagnosticMappings(Context.getDiagnostics());
03472 
03473   WriteCXXBaseSpecifiersOffsets();
03474   
03475   // If we're emitting a module, write out the submodule information.  
03476   if (WritingModule)
03477     WriteSubmodules(WritingModule);
03478 
03479   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
03480 
03481   // Write the record containing external, unnamed definitions.
03482   if (!ExternalDefinitions.empty())
03483     Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions);
03484 
03485   // Write the record containing tentative definitions.
03486   if (!TentativeDefinitions.empty())
03487     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
03488 
03489   // Write the record containing unused file scoped decls.
03490   if (!UnusedFileScopedDecls.empty())
03491     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
03492 
03493   // Write the record containing weak undeclared identifiers.
03494   if (!WeakUndeclaredIdentifiers.empty())
03495     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
03496                       WeakUndeclaredIdentifiers);
03497 
03498   // Write the record containing locally-scoped external definitions.
03499   if (!LocallyScopedExternalDecls.empty())
03500     Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS,
03501                       LocallyScopedExternalDecls);
03502 
03503   // Write the record containing ext_vector type names.
03504   if (!ExtVectorDecls.empty())
03505     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
03506 
03507   // Write the record containing VTable uses information.
03508   if (!VTableUses.empty())
03509     Stream.EmitRecord(VTABLE_USES, VTableUses);
03510 
03511   // Write the record containing dynamic classes declarations.
03512   if (!DynamicClasses.empty())
03513     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
03514 
03515   // Write the record containing pending implicit instantiations.
03516   if (!PendingInstantiations.empty())
03517     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
03518 
03519   // Write the record containing declaration references of Sema.
03520   if (!SemaDeclRefs.empty())
03521     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
03522 
03523   // Write the record containing CUDA-specific declaration references.
03524   if (!CUDASpecialDeclRefs.empty())
03525     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
03526   
03527   // Write the delegating constructors.
03528   if (!DelegatingCtorDecls.empty())
03529     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
03530 
03531   // Write the known namespaces.
03532   if (!KnownNamespaces.empty())
03533     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
03534   
03535   // Write the visible updates to DeclContexts.
03536   for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator
03537        I = UpdatedDeclContexts.begin(),
03538        E = UpdatedDeclContexts.end();
03539        I != E; ++I)
03540     WriteDeclContextVisibleUpdate(*I);
03541 
03542   if (!WritingModule) {
03543     // Write the submodules that were imported, if any.
03544     RecordData ImportedModules;
03545     for (ASTContext::import_iterator I = Context.local_import_begin(),
03546                                   IEnd = Context.local_import_end();
03547          I != IEnd; ++I) {
03548       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
03549       ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]);
03550     }
03551     if (!ImportedModules.empty()) {
03552       // Sort module IDs.
03553       llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end());
03554       
03555       // Unique module IDs.
03556       ImportedModules.erase(std::unique(ImportedModules.begin(), 
03557                                         ImportedModules.end()),
03558                             ImportedModules.end());
03559       
03560       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
03561     }
03562   }
03563   
03564   WriteDeclUpdatesBlocks();
03565   WriteDeclReplacementsBlock();
03566   WriteMergedDecls();
03567   WriteRedeclarations();
03568   WriteObjCCategories();
03569   
03570   // Some simple statistics
03571   Record.clear();
03572   Record.push_back(NumStatements);
03573   Record.push_back(NumMacros);
03574   Record.push_back(NumLexicalDeclContexts);
03575   Record.push_back(NumVisibleDeclContexts);
03576   Stream.EmitRecord(STATISTICS, Record);
03577   Stream.ExitBlock();
03578 }
03579 
03580 /// \brief Go through the declaration update blocks and resolve declaration
03581 /// pointers into declaration IDs.
03582 void ASTWriter::ResolveDeclUpdatesBlocks() {
03583   for (DeclUpdateMap::iterator
03584        I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
03585     const Decl *D = I->first;
03586     UpdateRecord &URec = I->second;
03587     
03588     if (isRewritten(D))
03589       continue; // The decl will be written completely
03590 
03591     unsigned Idx = 0, N = URec.size();
03592     while (Idx < N) {
03593       switch ((DeclUpdateKind)URec[Idx++]) {
03594       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
03595       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
03596       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
03597         URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx]));
03598         ++Idx;
03599         break;
03600           
03601       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
03602         ++Idx;
03603         break;
03604       }
03605     }
03606   }
03607 }
03608 
03609 void ASTWriter::WriteDeclUpdatesBlocks() {
03610   if (DeclUpdates.empty())
03611     return;
03612 
03613   RecordData OffsetsRecord;
03614   Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
03615   for (DeclUpdateMap::iterator
03616          I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) {
03617     const Decl *D = I->first;
03618     UpdateRecord &URec = I->second;
03619 
03620     if (isRewritten(D))
03621       continue; // The decl will be written completely,no need to store updates.
03622 
03623     uint64_t Offset = Stream.GetCurrentBitNo();
03624     Stream.EmitRecord(DECL_UPDATES, URec);
03625 
03626     OffsetsRecord.push_back(GetDeclRef(D));
03627     OffsetsRecord.push_back(Offset);
03628   }
03629   Stream.ExitBlock();
03630   Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord);
03631 }
03632 
03633 void ASTWriter::WriteDeclReplacementsBlock() {
03634   if (ReplacedDecls.empty())
03635     return;
03636 
03637   RecordData Record;
03638   for (SmallVector<ReplacedDeclInfo, 16>::iterator
03639            I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
03640     Record.push_back(I->ID);
03641     Record.push_back(I->Offset);
03642     Record.push_back(I->Loc);
03643   }
03644   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
03645 }
03646 
03647 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
03648   Record.push_back(Loc.getRawEncoding());
03649 }
03650 
03651 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
03652   AddSourceLocation(Range.getBegin(), Record);
03653   AddSourceLocation(Range.getEnd(), Record);
03654 }
03655 
03656 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
03657   Record.push_back(Value.getBitWidth());
03658   const uint64_t *Words = Value.getRawData();
03659   Record.append(Words, Words + Value.getNumWords());
03660 }
03661 
03662 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
03663   Record.push_back(Value.isUnsigned());
03664   AddAPInt(Value, Record);
03665 }
03666 
03667 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
03668   AddAPInt(Value.bitcastToAPInt(), Record);
03669 }
03670 
03671 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
03672   Record.push_back(getIdentifierRef(II));
03673 }
03674 
03675 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
03676   if (II == 0)
03677     return 0;
03678 
03679   IdentID &ID = IdentifierIDs[II];
03680   if (ID == 0)
03681     ID = NextIdentID++;
03682   return ID;
03683 }
03684 
03685 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
03686   Record.push_back(getSelectorRef(SelRef));
03687 }
03688 
03689 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
03690   if (Sel.getAsOpaquePtr() == 0) {
03691     return 0;
03692   }
03693 
03694   SelectorID &SID = SelectorIDs[Sel];
03695   if (SID == 0 && Chain) {
03696     // This might trigger a ReadSelector callback, which will set the ID for
03697     // this selector.
03698     Chain->LoadSelector(Sel);
03699   }
03700   if (SID == 0) {
03701     SID = NextSelectorID++;
03702   }
03703   return SID;
03704 }
03705 
03706 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
03707   AddDeclRef(Temp->getDestructor(), Record);
03708 }
03709 
03710 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
03711                                       CXXBaseSpecifier const *BasesEnd,
03712                                         RecordDataImpl &Record) {
03713   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
03714   CXXBaseSpecifiersToWrite.push_back(
03715                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
03716                                                         Bases, BasesEnd));
03717   Record.push_back(NextCXXBaseSpecifiersID++);
03718 }
03719 
03720 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
03721                                            const TemplateArgumentLocInfo &Arg,
03722                                            RecordDataImpl &Record) {
03723   switch (Kind) {
03724   case TemplateArgument::Expression:
03725     AddStmt(Arg.getAsExpr());
03726     break;
03727   case TemplateArgument::Type:
03728     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
03729     break;
03730   case TemplateArgument::Template:
03731     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
03732     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
03733     break;
03734   case TemplateArgument::TemplateExpansion:
03735     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
03736     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
03737     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
03738     break;
03739   case TemplateArgument::Null:
03740   case TemplateArgument::Integral:
03741   case TemplateArgument::Declaration:
03742   case TemplateArgument::Pack:
03743     break;
03744   }
03745 }
03746 
03747 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
03748                                        RecordDataImpl &Record) {
03749   AddTemplateArgument(Arg.getArgument(), Record);
03750 
03751   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
03752     bool InfoHasSameExpr
03753       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
03754     Record.push_back(InfoHasSameExpr);
03755     if (InfoHasSameExpr)
03756       return; // Avoid storing the same expr twice.
03757   }
03758   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
03759                              Record);
03760 }
03761 
03762 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 
03763                                   RecordDataImpl &Record) {
03764   if (TInfo == 0) {
03765     AddTypeRef(QualType(), Record);
03766     return;
03767   }
03768 
03769   AddTypeLoc(TInfo->getTypeLoc(), Record);
03770 }
03771 
03772 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
03773   AddTypeRef(TL.getType(), Record);
03774 
03775   TypeLocWriter TLW(*this, Record);
03776   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
03777     TLW.Visit(TL);
03778 }
03779 
03780 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
03781   Record.push_back(GetOrCreateTypeID(T));
03782 }
03783 
03784 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
03785   return MakeTypeID(*Context, T,
03786               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
03787 }
03788 
03789 TypeID ASTWriter::getTypeID(QualType T) const {
03790   return MakeTypeID(*Context, T,
03791               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
03792 }
03793 
03794 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
03795   if (T.isNull())
03796     return TypeIdx();
03797   assert(!T.getLocalFastQualifiers());
03798 
03799   TypeIdx &Idx = TypeIdxs[T];
03800   if (Idx.getIndex() == 0) {
03801     // We haven't seen this type before. Assign it a new ID and put it
03802     // into the queue of types to emit.
03803     Idx = TypeIdx(NextTypeID++);
03804     DeclTypesToEmit.push(T);
03805   }
03806   return Idx;
03807 }
03808 
03809 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
03810   if (T.isNull())
03811     return TypeIdx();
03812   assert(!T.getLocalFastQualifiers());
03813 
03814   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
03815   assert(I != TypeIdxs.end() && "Type not emitted!");
03816   return I->second;
03817 }
03818 
03819 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
03820   Record.push_back(GetDeclRef(D));
03821 }
03822 
03823 DeclID ASTWriter::GetDeclRef(const Decl *D) {
03824   assert(WritingAST && "Cannot request a declaration ID before AST writing");
03825   
03826   if (D == 0) {
03827     return 0;
03828   }
03829   
03830   // If D comes from an AST file, its declaration ID is already known and
03831   // fixed.
03832   if (D->isFromASTFile())
03833     return D->getGlobalID();
03834   
03835   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
03836   DeclID &ID = DeclIDs[D];
03837   if (ID == 0) {
03838     // We haven't seen this declaration before. Give it a new ID and
03839     // enqueue it in the list of declarations to emit.
03840     ID = NextDeclID++;
03841     DeclTypesToEmit.push(const_cast<Decl *>(D));
03842   }
03843 
03844   return ID;
03845 }
03846 
03847 DeclID ASTWriter::getDeclID(const Decl *D) {
03848   if (D == 0)
03849     return 0;
03850 
03851   // If D comes from an AST file, its declaration ID is already known and
03852   // fixed.
03853   if (D->isFromASTFile())
03854     return D->getGlobalID();
03855 
03856   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
03857   return DeclIDs[D];
03858 }
03859 
03860 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L,
03861                                std::pair<unsigned, serialization::DeclID> R) {
03862   return L.first < R.first;
03863 }
03864 
03865 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
03866   assert(ID);
03867   assert(D);
03868 
03869   SourceLocation Loc = D->getLocation();
03870   if (Loc.isInvalid())
03871     return;
03872 
03873   // We only keep track of the file-level declarations of each file.
03874   if (!D->getLexicalDeclContext()->isFileContext())
03875     return;
03876   // FIXME: ParmVarDecls that are part of a function type of a parameter of
03877   // a function/objc method, should not have TU as lexical context.
03878   if (isa<ParmVarDecl>(D))
03879     return;
03880 
03881   SourceManager &SM = Context->getSourceManager();
03882   SourceLocation FileLoc = SM.getFileLoc(Loc);
03883   assert(SM.isLocalSourceLocation(FileLoc));
03884   FileID FID;
03885   unsigned Offset;
03886   llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
03887   if (FID.isInvalid())
03888     return;
03889   const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID);
03890   assert(Entry->isFile());
03891 
03892   DeclIDInFileInfo *&Info = FileDeclIDs[Entry];
03893   if (!Info)
03894     Info = new DeclIDInFileInfo();
03895 
03896   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
03897   LocDeclIDsTy &Decls = Info->DeclIDs;
03898 
03899   if (Decls.empty() || Decls.back().first <= Offset) {
03900     Decls.push_back(LocDecl);
03901     return;
03902   }
03903 
03904   LocDeclIDsTy::iterator
03905     I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl);
03906 
03907   Decls.insert(I, LocDecl);
03908 }
03909 
03910 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
03911   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
03912   Record.push_back(Name.getNameKind());
03913   switch (Name.getNameKind()) {
03914   case DeclarationName::Identifier:
03915     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
03916     break;
03917 
03918   case DeclarationName::ObjCZeroArgSelector:
03919   case DeclarationName::ObjCOneArgSelector:
03920   case DeclarationName::ObjCMultiArgSelector:
03921     AddSelectorRef(Name.getObjCSelector(), Record);
03922     break;
03923 
03924   case DeclarationName::CXXConstructorName:
03925   case DeclarationName::CXXDestructorName:
03926   case DeclarationName::CXXConversionFunctionName:
03927     AddTypeRef(Name.getCXXNameType(), Record);
03928     break;
03929 
03930   case DeclarationName::CXXOperatorName:
03931     Record.push_back(Name.getCXXOverloadedOperator());
03932     break;
03933 
03934   case DeclarationName::CXXLiteralOperatorName:
03935     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
03936     break;
03937 
03938   case DeclarationName::CXXUsingDirective:
03939     // No extra data to emit
03940     break;
03941   }
03942 }
03943 
03944 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
03945                                      DeclarationName Name, RecordDataImpl &Record) {
03946   switch (Name.getNameKind()) {
03947   case DeclarationName::CXXConstructorName:
03948   case DeclarationName::CXXDestructorName:
03949   case DeclarationName::CXXConversionFunctionName:
03950     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
03951     break;
03952 
03953   case DeclarationName::CXXOperatorName:
03954     AddSourceLocation(
03955        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
03956        Record);
03957     AddSourceLocation(
03958         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
03959         Record);
03960     break;
03961 
03962   case DeclarationName::CXXLiteralOperatorName:
03963     AddSourceLocation(
03964      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
03965      Record);
03966     break;
03967 
03968   case DeclarationName::Identifier:
03969   case DeclarationName::ObjCZeroArgSelector:
03970   case DeclarationName::ObjCOneArgSelector:
03971   case DeclarationName::ObjCMultiArgSelector:
03972   case DeclarationName::CXXUsingDirective:
03973     break;
03974   }
03975 }
03976 
03977 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
03978                                        RecordDataImpl &Record) {
03979   AddDeclarationName(NameInfo.getName(), Record);
03980   AddSourceLocation(NameInfo.getLoc(), Record);
03981   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
03982 }
03983 
03984 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
03985                                  RecordDataImpl &Record) {
03986   AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
03987   Record.push_back(Info.NumTemplParamLists);
03988   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
03989     AddTemplateParameterList(Info.TemplParamLists[i], Record);
03990 }
03991 
03992 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
03993                                        RecordDataImpl &Record) {
03994   // Nested name specifiers usually aren't too long. I think that 8 would
03995   // typically accommodate the vast majority.
03996   SmallVector<NestedNameSpecifier *, 8> NestedNames;
03997 
03998   // Push each of the NNS's onto a stack for serialization in reverse order.
03999   while (NNS) {
04000     NestedNames.push_back(NNS);
04001     NNS = NNS->getPrefix();
04002   }
04003 
04004   Record.push_back(NestedNames.size());
04005   while(!NestedNames.empty()) {
04006     NNS = NestedNames.pop_back_val();
04007     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
04008     Record.push_back(Kind);
04009     switch (Kind) {
04010     case NestedNameSpecifier::Identifier:
04011       AddIdentifierRef(NNS->getAsIdentifier(), Record);
04012       break;
04013 
04014     case NestedNameSpecifier::Namespace:
04015       AddDeclRef(NNS->getAsNamespace(), Record);
04016       break;
04017 
04018     case NestedNameSpecifier::NamespaceAlias:
04019       AddDeclRef(NNS->getAsNamespaceAlias(), Record);
04020       break;
04021 
04022     case NestedNameSpecifier::TypeSpec:
04023     case NestedNameSpecifier::TypeSpecWithTemplate:
04024       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
04025       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
04026       break;
04027 
04028     case NestedNameSpecifier::Global:
04029       // Don't need to write an associated value.
04030       break;
04031     }
04032   }
04033 }
04034 
04035 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
04036                                           RecordDataImpl &Record) {
04037   // Nested name specifiers usually aren't too long. I think that 8 would
04038   // typically accommodate the vast majority.
04039   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
04040 
04041   // Push each of the nested-name-specifiers's onto a stack for
04042   // serialization in reverse order.
04043   while (NNS) {
04044     NestedNames.push_back(NNS);
04045     NNS = NNS.getPrefix();
04046   }
04047 
04048   Record.push_back(NestedNames.size());
04049   while(!NestedNames.empty()) {
04050     NNS = NestedNames.pop_back_val();
04051     NestedNameSpecifier::SpecifierKind Kind
04052       = NNS.getNestedNameSpecifier()->getKind();
04053     Record.push_back(Kind);
04054     switch (Kind) {
04055     case NestedNameSpecifier::Identifier:
04056       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
04057       AddSourceRange(NNS.getLocalSourceRange(), Record);
04058       break;
04059 
04060     case NestedNameSpecifier::Namespace:
04061       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
04062       AddSourceRange(NNS.getLocalSourceRange(), Record);
04063       break;
04064 
04065     case NestedNameSpecifier::NamespaceAlias:
04066       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
04067       AddSourceRange(NNS.getLocalSourceRange(), Record);
04068       break;
04069 
04070     case NestedNameSpecifier::TypeSpec:
04071     case NestedNameSpecifier::TypeSpecWithTemplate:
04072       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
04073       AddTypeLoc(NNS.getTypeLoc(), Record);
04074       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
04075       break;
04076 
04077     case NestedNameSpecifier::Global:
04078       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
04079       break;
04080     }
04081   }
04082 }
04083 
04084 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
04085   TemplateName::NameKind Kind = Name.getKind();
04086   Record.push_back(Kind);
04087   switch (Kind) {
04088   case TemplateName::Template:
04089     AddDeclRef(Name.getAsTemplateDecl(), Record);
04090     break;
04091 
04092   case TemplateName::OverloadedTemplate: {
04093     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
04094     Record.push_back(OvT->size());
04095     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
04096            I != E; ++I)
04097       AddDeclRef(*I, Record);
04098     break;
04099   }
04100 
04101   case TemplateName::QualifiedTemplate: {
04102     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
04103     AddNestedNameSpecifier(QualT->getQualifier(), Record);
04104     Record.push_back(QualT->hasTemplateKeyword());
04105     AddDeclRef(QualT->getTemplateDecl(), Record);
04106     break;
04107   }
04108 
04109   case TemplateName::DependentTemplate: {
04110     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
04111     AddNestedNameSpecifier(DepT->getQualifier(), Record);
04112     Record.push_back(DepT->isIdentifier());
04113     if (DepT->isIdentifier())
04114       AddIdentifierRef(DepT->getIdentifier(), Record);
04115     else
04116       Record.push_back(DepT->getOperator());
04117     break;
04118   }
04119 
04120   case TemplateName::SubstTemplateTemplateParm: {
04121     SubstTemplateTemplateParmStorage *subst
04122       = Name.getAsSubstTemplateTemplateParm();
04123     AddDeclRef(subst->getParameter(), Record);
04124     AddTemplateName(subst->getReplacement(), Record);
04125     break;
04126   }
04127       
04128   case TemplateName::SubstTemplateTemplateParmPack: {
04129     SubstTemplateTemplateParmPackStorage *SubstPack
04130       = Name.getAsSubstTemplateTemplateParmPack();
04131     AddDeclRef(SubstPack->getParameterPack(), Record);
04132     AddTemplateArgument(SubstPack->getArgumentPack(), Record);
04133     break;
04134   }
04135   }
04136 }
04137 
04138 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
04139                                     RecordDataImpl &Record) {
04140   Record.push_back(Arg.getKind());
04141   switch (Arg.getKind()) {
04142   case TemplateArgument::Null:
04143     break;
04144   case TemplateArgument::Type:
04145     AddTypeRef(Arg.getAsType(), Record);
04146     break;
04147   case TemplateArgument::Declaration:
04148     AddDeclRef(Arg.getAsDecl(), Record);
04149     break;
04150   case TemplateArgument::Integral:
04151     AddAPSInt(*Arg.getAsIntegral(), Record);
04152     AddTypeRef(Arg.getIntegralType(), Record);
04153     break;
04154   case TemplateArgument::Template:
04155     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
04156     break;
04157   case TemplateArgument::TemplateExpansion:
04158     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
04159     if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
04160       Record.push_back(*NumExpansions + 1);
04161     else
04162       Record.push_back(0);
04163     break;
04164   case TemplateArgument::Expression:
04165     AddStmt(Arg.getAsExpr());
04166     break;
04167   case TemplateArgument::Pack:
04168     Record.push_back(Arg.pack_size());
04169     for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end();
04170            I != E; ++I)
04171       AddTemplateArgument(*I, Record);
04172     break;
04173   }
04174 }
04175 
04176 void
04177 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
04178                                     RecordDataImpl &Record) {
04179   assert(TemplateParams && "No TemplateParams!");
04180   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
04181   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
04182   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
04183   Record.push_back(TemplateParams->size());
04184   for (TemplateParameterList::const_iterator
04185          P = TemplateParams->begin(), PEnd = TemplateParams->end();
04186          P != PEnd; ++P)
04187     AddDeclRef(*P, Record);
04188 }
04189 
04190 /// \brief Emit a template argument list.
04191 void
04192 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
04193                                    RecordDataImpl &Record) {
04194   assert(TemplateArgs && "No TemplateArgs!");
04195   Record.push_back(TemplateArgs->size());
04196   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
04197     AddTemplateArgument(TemplateArgs->get(i), Record);
04198 }
04199 
04200 
04201 void
04202 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) {
04203   Record.push_back(Set.size());
04204   for (UnresolvedSetImpl::const_iterator
04205          I = Set.begin(), E = Set.end(); I != E; ++I) {
04206     AddDeclRef(I.getDecl(), Record);
04207     Record.push_back(I.getAccess());
04208   }
04209 }
04210 
04211 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
04212                                     RecordDataImpl &Record) {
04213   Record.push_back(Base.isVirtual());
04214   Record.push_back(Base.isBaseOfClass());
04215   Record.push_back(Base.getAccessSpecifierAsWritten());
04216   Record.push_back(Base.getInheritConstructors());
04217   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
04218   AddSourceRange(Base.getSourceRange(), Record);
04219   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 
04220                                           : SourceLocation(),
04221                     Record);
04222 }
04223 
04224 void ASTWriter::FlushCXXBaseSpecifiers() {
04225   RecordData Record;
04226   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
04227     Record.clear();
04228     
04229     // Record the offset of this base-specifier set.
04230     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
04231     if (Index == CXXBaseSpecifiersOffsets.size())
04232       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
04233     else {
04234       if (Index > CXXBaseSpecifiersOffsets.size())
04235         CXXBaseSpecifiersOffsets.resize(Index + 1);
04236       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
04237     }
04238 
04239     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
04240                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
04241     Record.push_back(BEnd - B);
04242     for (; B != BEnd; ++B)
04243       AddCXXBaseSpecifier(*B, Record);
04244     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
04245     
04246     // Flush any expressions that were written as part of the base specifiers.
04247     FlushStmts();
04248   }
04249 
04250   CXXBaseSpecifiersToWrite.clear();
04251 }
04252 
04253 void ASTWriter::AddCXXCtorInitializers(
04254                              const CXXCtorInitializer * const *CtorInitializers,
04255                              unsigned NumCtorInitializers,
04256                              RecordDataImpl &Record) {
04257   Record.push_back(NumCtorInitializers);
04258   for (unsigned i=0; i != NumCtorInitializers; ++i) {
04259     const CXXCtorInitializer *Init = CtorInitializers[i];
04260 
04261     if (Init->isBaseInitializer()) {
04262       Record.push_back(CTOR_INITIALIZER_BASE);
04263       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
04264       Record.push_back(Init->isBaseVirtual());
04265     } else if (Init->isDelegatingInitializer()) {
04266       Record.push_back(CTOR_INITIALIZER_DELEGATING);
04267       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
04268     } else if (Init->isMemberInitializer()){
04269       Record.push_back(CTOR_INITIALIZER_MEMBER);
04270       AddDeclRef(Init->getMember(), Record);
04271     } else {
04272       Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
04273       AddDeclRef(Init->getIndirectMember(), Record);
04274     }
04275 
04276     AddSourceLocation(Init->getMemberLocation(), Record);
04277     AddStmt(Init->getInit());
04278     AddSourceLocation(Init->getLParenLoc(), Record);
04279     AddSourceLocation(Init->getRParenLoc(), Record);
04280     Record.push_back(Init->isWritten());
04281     if (Init->isWritten()) {
04282       Record.push_back(Init->getSourceOrder());
04283     } else {
04284       Record.push_back(Init->getNumArrayIndices());
04285       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
04286         AddDeclRef(Init->getArrayIndex(i), Record);
04287     }
04288   }
04289 }
04290 
04291 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
04292   assert(D->DefinitionData);
04293   struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData;
04294   Record.push_back(Data.IsLambda);
04295   Record.push_back(Data.UserDeclaredConstructor);
04296   Record.push_back(Data.UserDeclaredCopyConstructor);
04297   Record.push_back(Data.UserDeclaredMoveConstructor);
04298   Record.push_back(Data.UserDeclaredCopyAssignment);
04299   Record.push_back(Data.UserDeclaredMoveAssignment);
04300   Record.push_back(Data.UserDeclaredDestructor);
04301   Record.push_back(Data.Aggregate);
04302   Record.push_back(Data.PlainOldData);
04303   Record.push_back(Data.Empty);
04304   Record.push_back(Data.Polymorphic);
04305   Record.push_back(Data.Abstract);
04306   Record.push_back(Data.IsStandardLayout);
04307   Record.push_back(Data.HasNoNonEmptyBases);
04308   Record.push_back(Data.HasPrivateFields);
04309   Record.push_back(Data.HasProtectedFields);
04310   Record.push_back(Data.HasPublicFields);
04311   Record.push_back(Data.HasMutableFields);
04312   Record.push_back(Data.HasOnlyCMembers);
04313   Record.push_back(Data.HasInClassInitializer);
04314   Record.push_back(Data.HasTrivialDefaultConstructor);
04315   Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
04316   Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
04317   Record.push_back(Data.DefaultedCopyConstructorIsConstexpr);
04318   Record.push_back(Data.DefaultedMoveConstructorIsConstexpr);
04319   Record.push_back(Data.HasConstexprDefaultConstructor);
04320   Record.push_back(Data.HasConstexprCopyConstructor);
04321   Record.push_back(Data.HasConstexprMoveConstructor);
04322   Record.push_back(Data.HasTrivialCopyConstructor);
04323   Record.push_back(Data.HasTrivialMoveConstructor);
04324   Record.push_back(Data.HasTrivialCopyAssignment);
04325   Record.push_back(Data.HasTrivialMoveAssignment);
04326   Record.push_back(Data.HasTrivialDestructor);
04327   Record.push_back(Data.HasIrrelevantDestructor);
04328   Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
04329   Record.push_back(Data.ComputedVisibleConversions);
04330   Record.push_back(Data.UserProvidedDefaultConstructor);
04331   Record.push_back(Data.DeclaredDefaultConstructor);
04332   Record.push_back(Data.DeclaredCopyConstructor);
04333   Record.push_back(Data.DeclaredMoveConstructor);
04334   Record.push_back(Data.DeclaredCopyAssignment);
04335   Record.push_back(Data.DeclaredMoveAssignment);
04336   Record.push_back(Data.DeclaredDestructor);
04337   Record.push_back(Data.FailedImplicitMoveConstructor);
04338   Record.push_back(Data.FailedImplicitMoveAssignment);
04339   // IsLambda bit is already saved.
04340 
04341   Record.push_back(Data.NumBases);
04342   if (Data.NumBases > 0)
04343     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 
04344                             Record);
04345   
04346   // FIXME: Make VBases lazily computed when needed to avoid storing them.
04347   Record.push_back(Data.NumVBases);
04348   if (Data.NumVBases > 0)
04349     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 
04350                             Record);
04351 
04352   AddUnresolvedSet(Data.Conversions, Record);
04353   AddUnresolvedSet(Data.VisibleConversions, Record);
04354   // Data.Definition is the owning decl, no need to write it. 
04355   AddDeclRef(Data.FirstFriend, Record);
04356   
04357   // Add lambda-specific data.
04358   if (Data.IsLambda) {
04359     CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData();
04360     Record.push_back(Lambda.Dependent);
04361     Record.push_back(Lambda.NumCaptures);
04362     Record.push_back(Lambda.NumExplicitCaptures);
04363     Record.push_back(Lambda.ManglingNumber);
04364     AddDeclRef(Lambda.ContextDecl, Record);
04365     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
04366       LambdaExpr::Capture &Capture = Lambda.Captures[I];
04367       AddSourceLocation(Capture.getLocation(), Record);
04368       Record.push_back(Capture.isImplicit());
04369       Record.push_back(Capture.getCaptureKind()); // FIXME: stable!
04370       VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0;
04371       AddDeclRef(Var, Record);
04372       AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc()
04373                                                  : SourceLocation(), 
04374                         Record);
04375     }
04376   }
04377 }
04378 
04379 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
04380   assert(Reader && "Cannot remove chain");
04381   assert((!Chain || Chain == Reader) && "Cannot replace chain");
04382   assert(FirstDeclID == NextDeclID &&
04383          FirstTypeID == NextTypeID &&
04384          FirstIdentID == NextIdentID &&
04385          FirstSubmoduleID == NextSubmoduleID &&
04386          FirstSelectorID == NextSelectorID &&
04387          "Setting chain after writing has started.");
04388 
04389   Chain = Reader;
04390 
04391   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
04392   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
04393   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
04394   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
04395   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
04396   NextDeclID = FirstDeclID;
04397   NextTypeID = FirstTypeID;
04398   NextIdentID = FirstIdentID;
04399   NextSelectorID = FirstSelectorID;
04400   NextSubmoduleID = FirstSubmoduleID;
04401 }
04402 
04403 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
04404   IdentifierIDs[II] = ID;
04405   if (II->hasMacroDefinition())
04406     DeserializedMacroNames.push_back(II);
04407 }
04408 
04409 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
04410   // Always take the highest-numbered type index. This copes with an interesting
04411   // case for chained AST writing where we schedule writing the type and then,
04412   // later, deserialize the type from another AST. In this case, we want to
04413   // keep the higher-numbered entry so that we can properly write it out to
04414   // the AST file.
04415   TypeIdx &StoredIdx = TypeIdxs[T];
04416   if (Idx.getIndex() >= StoredIdx.getIndex())
04417     StoredIdx = Idx;
04418 }
04419 
04420 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
04421   SelectorIDs[S] = ID;
04422 }
04423 
04424 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
04425                                     MacroDefinition *MD) {
04426   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
04427   MacroDefinitions[MD] = ID;
04428 }
04429 
04430 void ASTWriter::MacroVisible(IdentifierInfo *II) {
04431   DeserializedMacroNames.push_back(II);
04432 }
04433 
04434 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
04435   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
04436   SubmoduleIDs[Mod] = ID;
04437 }
04438 
04439 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
04440   assert(D->isCompleteDefinition());
04441   assert(!WritingAST && "Already writing the AST!");
04442   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
04443     // We are interested when a PCH decl is modified.
04444     if (RD->isFromASTFile()) {
04445       // A forward reference was mutated into a definition. Rewrite it.
04446       // FIXME: This happens during template instantiation, should we
04447       // have created a new definition decl instead ?
04448       RewriteDecl(RD);
04449     }
04450   }
04451 }
04452 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
04453   assert(!WritingAST && "Already writing the AST!");
04454 
04455   // TU and namespaces are handled elsewhere.
04456   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
04457     return;
04458 
04459   if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
04460     return; // Not a source decl added to a DeclContext from PCH.
04461 
04462   AddUpdatedDeclContext(DC);
04463 }
04464 
04465 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
04466   assert(!WritingAST && "Already writing the AST!");
04467   assert(D->isImplicit());
04468   if (!(!D->isFromASTFile() && RD->isFromASTFile()))
04469     return; // Not a source member added to a class from PCH.
04470   if (!isa<CXXMethodDecl>(D))
04471     return; // We are interested in lazily declared implicit methods.
04472 
04473   // A decl coming from PCH was modified.
04474   assert(RD->isCompleteDefinition());
04475   UpdateRecord &Record = DeclUpdates[RD];
04476   Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER);
04477   Record.push_back(reinterpret_cast<uint64_t>(D));
04478 }
04479 
04480 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
04481                                      const ClassTemplateSpecializationDecl *D) {
04482   // The specializations set is kept in the canonical template.
04483   assert(!WritingAST && "Already writing the AST!");
04484   TD = TD->getCanonicalDecl();
04485   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
04486     return; // Not a source specialization added to a template from PCH.
04487 
04488   UpdateRecord &Record = DeclUpdates[TD];
04489   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
04490   Record.push_back(reinterpret_cast<uint64_t>(D));
04491 }
04492 
04493 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
04494                                                const FunctionDecl *D) {
04495   // The specializations set is kept in the canonical template.
04496   assert(!WritingAST && "Already writing the AST!");
04497   TD = TD->getCanonicalDecl();
04498   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
04499     return; // Not a source specialization added to a template from PCH.
04500 
04501   UpdateRecord &Record = DeclUpdates[TD];
04502   Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION);
04503   Record.push_back(reinterpret_cast<uint64_t>(D));
04504 }
04505 
04506 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
04507   assert(!WritingAST && "Already writing the AST!");
04508   if (!D->isFromASTFile())
04509     return; // Declaration not imported from PCH.
04510 
04511   // Implicit decl from a PCH was defined.
04512   // FIXME: Should implicit definition be a separate FunctionDecl?
04513   RewriteDecl(D);
04514 }
04515 
04516 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
04517   assert(!WritingAST && "Already writing the AST!");
04518   if (!D->isFromASTFile())
04519     return;
04520 
04521   // Since the actual instantiation is delayed, this really means that we need
04522   // to update the instantiation location.
04523   UpdateRecord &Record = DeclUpdates[D];
04524   Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER);
04525   AddSourceLocation(
04526       D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record);
04527 }
04528 
04529 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
04530                                              const ObjCInterfaceDecl *IFD) {
04531   assert(!WritingAST && "Already writing the AST!");
04532   if (!IFD->isFromASTFile())
04533     return; // Declaration not imported from PCH.
04534   
04535   assert(IFD->getDefinition() && "Category on a class without a definition?");
04536   ObjCClassesWithCategories.insert(
04537     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
04538 }
04539 
04540 
04541 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
04542                                           const ObjCPropertyDecl *OrigProp,
04543                                           const ObjCCategoryDecl *ClassExt) {
04544   const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
04545   if (!D)
04546     return;
04547 
04548   assert(!WritingAST && "Already writing the AST!");
04549   if (!D->isFromASTFile())
04550     return; // Declaration not imported from PCH.
04551 
04552   RewriteDecl(D);
04553 }