ASTWriter.cpp revision a1f1fad8b60e1cb9d21a40a37f2e03150bcbeb6f
1//===--- ASTWriter.cpp - AST File Writer ----------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the ASTWriter class, which writes AST files. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Serialization/ASTWriter.h" 15#include "ASTCommon.h" 16#include "clang/Sema/Sema.h" 17#include "clang/Sema/IdentifierResolver.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Decl.h" 20#include "clang/AST/DeclContextInternals.h" 21#include "clang/AST/DeclTemplate.h" 22#include "clang/AST/DeclFriend.h" 23#include "clang/AST/Expr.h" 24#include "clang/AST/ExprCXX.h" 25#include "clang/AST/Type.h" 26#include "clang/AST/TypeLocVisitor.h" 27#include "clang/Serialization/ASTReader.h" 28#include "clang/Lex/MacroInfo.h" 29#include "clang/Lex/PreprocessingRecord.h" 30#include "clang/Lex/Preprocessor.h" 31#include "clang/Lex/HeaderSearch.h" 32#include "clang/Basic/FileManager.h" 33#include "clang/Basic/FileSystemStatCache.h" 34#include "clang/Basic/OnDiskHashTable.h" 35#include "clang/Basic/SourceManager.h" 36#include "clang/Basic/SourceManagerInternals.h" 37#include "clang/Basic/TargetInfo.h" 38#include "clang/Basic/Version.h" 39#include "clang/Basic/VersionTuple.h" 40#include "llvm/ADT/APFloat.h" 41#include "llvm/ADT/APInt.h" 42#include "llvm/ADT/StringExtras.h" 43#include "llvm/Bitcode/BitstreamWriter.h" 44#include "llvm/Support/FileSystem.h" 45#include "llvm/Support/MemoryBuffer.h" 46#include "llvm/Support/Path.h" 47#include <algorithm> 48#include <cstdio> 49#include <string.h> 50#include <utility> 51using namespace clang; 52using namespace clang::serialization; 53 54template <typename T, typename Allocator> 55static StringRef data(const std::vector<T, Allocator> &v) { 56 if (v.empty()) return StringRef(); 57 return StringRef(reinterpret_cast<const char*>(&v[0]), 58 sizeof(T) * v.size()); 59} 60 61template <typename T> 62static StringRef data(const SmallVectorImpl<T> &v) { 63 return StringRef(reinterpret_cast<const char*>(v.data()), 64 sizeof(T) * v.size()); 65} 66 67//===----------------------------------------------------------------------===// 68// Type serialization 69//===----------------------------------------------------------------------===// 70 71namespace { 72 class ASTTypeWriter { 73 ASTWriter &Writer; 74 ASTWriter::RecordDataImpl &Record; 75 76 public: 77 /// \brief Type code that corresponds to the record generated. 78 TypeCode Code; 79 80 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 81 : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { } 82 83 void VisitArrayType(const ArrayType *T); 84 void VisitFunctionType(const FunctionType *T); 85 void VisitTagType(const TagType *T); 86 87#define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); 88#define ABSTRACT_TYPE(Class, Base) 89#include "clang/AST/TypeNodes.def" 90 }; 91} 92 93void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) { 94 llvm_unreachable("Built-in types are never serialized"); 95} 96 97void ASTTypeWriter::VisitComplexType(const ComplexType *T) { 98 Writer.AddTypeRef(T->getElementType(), Record); 99 Code = TYPE_COMPLEX; 100} 101 102void ASTTypeWriter::VisitPointerType(const PointerType *T) { 103 Writer.AddTypeRef(T->getPointeeType(), Record); 104 Code = TYPE_POINTER; 105} 106 107void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { 108 Writer.AddTypeRef(T->getPointeeType(), Record); 109 Code = TYPE_BLOCK_POINTER; 110} 111 112void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { 113 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 114 Record.push_back(T->isSpelledAsLValue()); 115 Code = TYPE_LVALUE_REFERENCE; 116} 117 118void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { 119 Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record); 120 Code = TYPE_RVALUE_REFERENCE; 121} 122 123void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { 124 Writer.AddTypeRef(T->getPointeeType(), Record); 125 Writer.AddTypeRef(QualType(T->getClass(), 0), Record); 126 Code = TYPE_MEMBER_POINTER; 127} 128 129void ASTTypeWriter::VisitArrayType(const ArrayType *T) { 130 Writer.AddTypeRef(T->getElementType(), Record); 131 Record.push_back(T->getSizeModifier()); // FIXME: stable values 132 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values 133} 134 135void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { 136 VisitArrayType(T); 137 Writer.AddAPInt(T->getSize(), Record); 138 Code = TYPE_CONSTANT_ARRAY; 139} 140 141void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 142 VisitArrayType(T); 143 Code = TYPE_INCOMPLETE_ARRAY; 144} 145 146void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { 147 VisitArrayType(T); 148 Writer.AddSourceLocation(T->getLBracketLoc(), Record); 149 Writer.AddSourceLocation(T->getRBracketLoc(), Record); 150 Writer.AddStmt(T->getSizeExpr()); 151 Code = TYPE_VARIABLE_ARRAY; 152} 153 154void ASTTypeWriter::VisitVectorType(const VectorType *T) { 155 Writer.AddTypeRef(T->getElementType(), Record); 156 Record.push_back(T->getNumElements()); 157 Record.push_back(T->getVectorKind()); 158 Code = TYPE_VECTOR; 159} 160 161void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) { 162 VisitVectorType(T); 163 Code = TYPE_EXT_VECTOR; 164} 165 166void ASTTypeWriter::VisitFunctionType(const FunctionType *T) { 167 Writer.AddTypeRef(T->getResultType(), Record); 168 FunctionType::ExtInfo C = T->getExtInfo(); 169 Record.push_back(C.getNoReturn()); 170 Record.push_back(C.getHasRegParm()); 171 Record.push_back(C.getRegParm()); 172 // FIXME: need to stabilize encoding of calling convention... 173 Record.push_back(C.getCC()); 174 Record.push_back(C.getProducesResult()); 175} 176 177void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 178 VisitFunctionType(T); 179 Code = TYPE_FUNCTION_NO_PROTO; 180} 181 182void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { 183 VisitFunctionType(T); 184 Record.push_back(T->getNumArgs()); 185 for (unsigned I = 0, N = T->getNumArgs(); I != N; ++I) 186 Writer.AddTypeRef(T->getArgType(I), Record); 187 Record.push_back(T->isVariadic()); 188 Record.push_back(T->getTypeQuals()); 189 Record.push_back(static_cast<unsigned>(T->getRefQualifier())); 190 Record.push_back(T->getExceptionSpecType()); 191 if (T->getExceptionSpecType() == EST_Dynamic) { 192 Record.push_back(T->getNumExceptions()); 193 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) 194 Writer.AddTypeRef(T->getExceptionType(I), Record); 195 } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) { 196 Writer.AddStmt(T->getNoexceptExpr()); 197 } 198 Code = TYPE_FUNCTION_PROTO; 199} 200 201void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) { 202 Writer.AddDeclRef(T->getDecl(), Record); 203 Code = TYPE_UNRESOLVED_USING; 204} 205 206void ASTTypeWriter::VisitTypedefType(const TypedefType *T) { 207 Writer.AddDeclRef(T->getDecl(), Record); 208 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?"); 209 Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record); 210 Code = TYPE_TYPEDEF; 211} 212 213void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { 214 Writer.AddStmt(T->getUnderlyingExpr()); 215 Code = TYPE_TYPEOF_EXPR; 216} 217 218void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) { 219 Writer.AddTypeRef(T->getUnderlyingType(), Record); 220 Code = TYPE_TYPEOF; 221} 222 223void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) { 224 Writer.AddStmt(T->getUnderlyingExpr()); 225 Code = TYPE_DECLTYPE; 226} 227 228void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) { 229 Writer.AddTypeRef(T->getBaseType(), Record); 230 Writer.AddTypeRef(T->getUnderlyingType(), Record); 231 Record.push_back(T->getUTTKind()); 232 Code = TYPE_UNARY_TRANSFORM; 233} 234 235void ASTTypeWriter::VisitAutoType(const AutoType *T) { 236 Writer.AddTypeRef(T->getDeducedType(), Record); 237 Code = TYPE_AUTO; 238} 239 240void ASTTypeWriter::VisitTagType(const TagType *T) { 241 Record.push_back(T->isDependentType()); 242 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record); 243 assert(!T->isBeingDefined() && 244 "Cannot serialize in the middle of a type definition"); 245} 246 247void ASTTypeWriter::VisitRecordType(const RecordType *T) { 248 VisitTagType(T); 249 Code = TYPE_RECORD; 250} 251 252void ASTTypeWriter::VisitEnumType(const EnumType *T) { 253 VisitTagType(T); 254 Code = TYPE_ENUM; 255} 256 257void ASTTypeWriter::VisitAttributedType(const AttributedType *T) { 258 Writer.AddTypeRef(T->getModifiedType(), Record); 259 Writer.AddTypeRef(T->getEquivalentType(), Record); 260 Record.push_back(T->getAttrKind()); 261 Code = TYPE_ATTRIBUTED; 262} 263 264void 265ASTTypeWriter::VisitSubstTemplateTypeParmType( 266 const SubstTemplateTypeParmType *T) { 267 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 268 Writer.AddTypeRef(T->getReplacementType(), Record); 269 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM; 270} 271 272void 273ASTTypeWriter::VisitSubstTemplateTypeParmPackType( 274 const SubstTemplateTypeParmPackType *T) { 275 Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record); 276 Writer.AddTemplateArgument(T->getArgumentPack(), Record); 277 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK; 278} 279 280void 281ASTTypeWriter::VisitTemplateSpecializationType( 282 const TemplateSpecializationType *T) { 283 Record.push_back(T->isDependentType()); 284 Writer.AddTemplateName(T->getTemplateName(), Record); 285 Record.push_back(T->getNumArgs()); 286 for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end(); 287 ArgI != ArgE; ++ArgI) 288 Writer.AddTemplateArgument(*ArgI, Record); 289 Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() : 290 T->isCanonicalUnqualified() ? QualType() 291 : T->getCanonicalTypeInternal(), 292 Record); 293 Code = TYPE_TEMPLATE_SPECIALIZATION; 294} 295 296void 297ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) { 298 VisitArrayType(T); 299 Writer.AddStmt(T->getSizeExpr()); 300 Writer.AddSourceRange(T->getBracketsRange(), Record); 301 Code = TYPE_DEPENDENT_SIZED_ARRAY; 302} 303 304void 305ASTTypeWriter::VisitDependentSizedExtVectorType( 306 const DependentSizedExtVectorType *T) { 307 // FIXME: Serialize this type (C++ only) 308 llvm_unreachable("Cannot serialize dependent sized extended vector types"); 309} 310 311void 312ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 313 Record.push_back(T->getDepth()); 314 Record.push_back(T->getIndex()); 315 Record.push_back(T->isParameterPack()); 316 Writer.AddDeclRef(T->getDecl(), Record); 317 Code = TYPE_TEMPLATE_TYPE_PARM; 318} 319 320void 321ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) { 322 Record.push_back(T->getKeyword()); 323 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 324 Writer.AddIdentifierRef(T->getIdentifier(), Record); 325 Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType() 326 : T->getCanonicalTypeInternal(), 327 Record); 328 Code = TYPE_DEPENDENT_NAME; 329} 330 331void 332ASTTypeWriter::VisitDependentTemplateSpecializationType( 333 const DependentTemplateSpecializationType *T) { 334 Record.push_back(T->getKeyword()); 335 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 336 Writer.AddIdentifierRef(T->getIdentifier(), Record); 337 Record.push_back(T->getNumArgs()); 338 for (DependentTemplateSpecializationType::iterator 339 I = T->begin(), E = T->end(); I != E; ++I) 340 Writer.AddTemplateArgument(*I, Record); 341 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION; 342} 343 344void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) { 345 Writer.AddTypeRef(T->getPattern(), Record); 346 if (llvm::Optional<unsigned> NumExpansions = T->getNumExpansions()) 347 Record.push_back(*NumExpansions + 1); 348 else 349 Record.push_back(0); 350 Code = TYPE_PACK_EXPANSION; 351} 352 353void ASTTypeWriter::VisitParenType(const ParenType *T) { 354 Writer.AddTypeRef(T->getInnerType(), Record); 355 Code = TYPE_PAREN; 356} 357 358void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) { 359 Record.push_back(T->getKeyword()); 360 Writer.AddNestedNameSpecifier(T->getQualifier(), Record); 361 Writer.AddTypeRef(T->getNamedType(), Record); 362 Code = TYPE_ELABORATED; 363} 364 365void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) { 366 Writer.AddDeclRef(T->getDecl(), Record); 367 Writer.AddTypeRef(T->getInjectedSpecializationType(), Record); 368 Code = TYPE_INJECTED_CLASS_NAME; 369} 370 371void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 372 Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record); 373 Code = TYPE_OBJC_INTERFACE; 374} 375 376void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) { 377 Writer.AddTypeRef(T->getBaseType(), Record); 378 Record.push_back(T->getNumProtocols()); 379 for (ObjCObjectType::qual_iterator I = T->qual_begin(), 380 E = T->qual_end(); I != E; ++I) 381 Writer.AddDeclRef(*I, Record); 382 Code = TYPE_OBJC_OBJECT; 383} 384 385void 386ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 387 Writer.AddTypeRef(T->getPointeeType(), Record); 388 Code = TYPE_OBJC_OBJECT_POINTER; 389} 390 391void 392ASTTypeWriter::VisitAtomicType(const AtomicType *T) { 393 Writer.AddTypeRef(T->getValueType(), Record); 394 Code = TYPE_ATOMIC; 395} 396 397namespace { 398 399class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 400 ASTWriter &Writer; 401 ASTWriter::RecordDataImpl &Record; 402 403public: 404 TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 405 : Writer(Writer), Record(Record) { } 406 407#define ABSTRACT_TYPELOC(CLASS, PARENT) 408#define TYPELOC(CLASS, PARENT) \ 409 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 410#include "clang/AST/TypeLocNodes.def" 411 412 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 413 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 414}; 415 416} 417 418void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 419 // nothing to do 420} 421void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 422 Writer.AddSourceLocation(TL.getBuiltinLoc(), Record); 423 if (TL.needsExtraLocalData()) { 424 Record.push_back(TL.getWrittenTypeSpec()); 425 Record.push_back(TL.getWrittenSignSpec()); 426 Record.push_back(TL.getWrittenWidthSpec()); 427 Record.push_back(TL.hasModeAttr()); 428 } 429} 430void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 431 Writer.AddSourceLocation(TL.getNameLoc(), Record); 432} 433void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 434 Writer.AddSourceLocation(TL.getStarLoc(), Record); 435} 436void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 437 Writer.AddSourceLocation(TL.getCaretLoc(), Record); 438} 439void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 440 Writer.AddSourceLocation(TL.getAmpLoc(), Record); 441} 442void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 443 Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record); 444} 445void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 446 Writer.AddSourceLocation(TL.getStarLoc(), Record); 447 Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record); 448} 449void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 450 Writer.AddSourceLocation(TL.getLBracketLoc(), Record); 451 Writer.AddSourceLocation(TL.getRBracketLoc(), Record); 452 Record.push_back(TL.getSizeExpr() ? 1 : 0); 453 if (TL.getSizeExpr()) 454 Writer.AddStmt(TL.getSizeExpr()); 455} 456void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 457 VisitArrayTypeLoc(TL); 458} 459void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 460 VisitArrayTypeLoc(TL); 461} 462void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 463 VisitArrayTypeLoc(TL); 464} 465void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 466 DependentSizedArrayTypeLoc TL) { 467 VisitArrayTypeLoc(TL); 468} 469void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 470 DependentSizedExtVectorTypeLoc TL) { 471 Writer.AddSourceLocation(TL.getNameLoc(), Record); 472} 473void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 474 Writer.AddSourceLocation(TL.getNameLoc(), Record); 475} 476void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 477 Writer.AddSourceLocation(TL.getNameLoc(), Record); 478} 479void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 480 Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record); 481 Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record); 482 Record.push_back(TL.getTrailingReturn()); 483 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 484 Writer.AddDeclRef(TL.getArg(i), Record); 485} 486void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 487 VisitFunctionTypeLoc(TL); 488} 489void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 490 VisitFunctionTypeLoc(TL); 491} 492void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 493 Writer.AddSourceLocation(TL.getNameLoc(), Record); 494} 495void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 496 Writer.AddSourceLocation(TL.getNameLoc(), Record); 497} 498void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 499 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 500 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 501 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 502} 503void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 504 Writer.AddSourceLocation(TL.getTypeofLoc(), Record); 505 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 506 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 507 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 508} 509void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 510 Writer.AddSourceLocation(TL.getNameLoc(), Record); 511} 512void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 513 Writer.AddSourceLocation(TL.getKWLoc(), Record); 514 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 515 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 516 Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record); 517} 518void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { 519 Writer.AddSourceLocation(TL.getNameLoc(), Record); 520} 521void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 522 Writer.AddSourceLocation(TL.getNameLoc(), Record); 523} 524void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 525 Writer.AddSourceLocation(TL.getNameLoc(), Record); 526} 527void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 528 Writer.AddSourceLocation(TL.getAttrNameLoc(), Record); 529 if (TL.hasAttrOperand()) { 530 SourceRange range = TL.getAttrOperandParensRange(); 531 Writer.AddSourceLocation(range.getBegin(), Record); 532 Writer.AddSourceLocation(range.getEnd(), Record); 533 } 534 if (TL.hasAttrExprOperand()) { 535 Expr *operand = TL.getAttrExprOperand(); 536 Record.push_back(operand ? 1 : 0); 537 if (operand) Writer.AddStmt(operand); 538 } else if (TL.hasAttrEnumOperand()) { 539 Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record); 540 } 541} 542void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 543 Writer.AddSourceLocation(TL.getNameLoc(), Record); 544} 545void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 546 SubstTemplateTypeParmTypeLoc TL) { 547 Writer.AddSourceLocation(TL.getNameLoc(), Record); 548} 549void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 550 SubstTemplateTypeParmPackTypeLoc TL) { 551 Writer.AddSourceLocation(TL.getNameLoc(), Record); 552} 553void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 554 TemplateSpecializationTypeLoc TL) { 555 Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record); 556 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 557 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 558 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 559 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 560 TL.getArgLoc(i).getLocInfo(), Record); 561} 562void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 563 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 564 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 565} 566void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 567 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 568 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 569} 570void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 571 Writer.AddSourceLocation(TL.getNameLoc(), Record); 572} 573void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 574 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 575 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 576 Writer.AddSourceLocation(TL.getNameLoc(), Record); 577} 578void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 579 DependentTemplateSpecializationTypeLoc TL) { 580 Writer.AddSourceLocation(TL.getKeywordLoc(), Record); 581 Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record); 582 Writer.AddSourceLocation(TL.getNameLoc(), Record); 583 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 584 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 585 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 586 Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 587 TL.getArgLoc(I).getLocInfo(), Record); 588} 589void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 590 Writer.AddSourceLocation(TL.getEllipsisLoc(), Record); 591} 592void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 593 Writer.AddSourceLocation(TL.getNameLoc(), Record); 594} 595void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 596 Record.push_back(TL.hasBaseTypeAsWritten()); 597 Writer.AddSourceLocation(TL.getLAngleLoc(), Record); 598 Writer.AddSourceLocation(TL.getRAngleLoc(), Record); 599 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 600 Writer.AddSourceLocation(TL.getProtocolLoc(i), Record); 601} 602void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 603 Writer.AddSourceLocation(TL.getStarLoc(), Record); 604} 605void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 606 Writer.AddSourceLocation(TL.getKWLoc(), Record); 607 Writer.AddSourceLocation(TL.getLParenLoc(), Record); 608 Writer.AddSourceLocation(TL.getRParenLoc(), Record); 609} 610 611//===----------------------------------------------------------------------===// 612// ASTWriter Implementation 613//===----------------------------------------------------------------------===// 614 615static void EmitBlockID(unsigned ID, const char *Name, 616 llvm::BitstreamWriter &Stream, 617 ASTWriter::RecordDataImpl &Record) { 618 Record.clear(); 619 Record.push_back(ID); 620 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 621 622 // Emit the block name if present. 623 if (Name == 0 || Name[0] == 0) return; 624 Record.clear(); 625 while (*Name) 626 Record.push_back(*Name++); 627 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 628} 629 630static void EmitRecordID(unsigned ID, const char *Name, 631 llvm::BitstreamWriter &Stream, 632 ASTWriter::RecordDataImpl &Record) { 633 Record.clear(); 634 Record.push_back(ID); 635 while (*Name) 636 Record.push_back(*Name++); 637 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 638} 639 640static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 641 ASTWriter::RecordDataImpl &Record) { 642#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 643 RECORD(STMT_STOP); 644 RECORD(STMT_NULL_PTR); 645 RECORD(STMT_NULL); 646 RECORD(STMT_COMPOUND); 647 RECORD(STMT_CASE); 648 RECORD(STMT_DEFAULT); 649 RECORD(STMT_LABEL); 650 RECORD(STMT_IF); 651 RECORD(STMT_SWITCH); 652 RECORD(STMT_WHILE); 653 RECORD(STMT_DO); 654 RECORD(STMT_FOR); 655 RECORD(STMT_GOTO); 656 RECORD(STMT_INDIRECT_GOTO); 657 RECORD(STMT_CONTINUE); 658 RECORD(STMT_BREAK); 659 RECORD(STMT_RETURN); 660 RECORD(STMT_DECL); 661 RECORD(STMT_ASM); 662 RECORD(EXPR_PREDEFINED); 663 RECORD(EXPR_DECL_REF); 664 RECORD(EXPR_INTEGER_LITERAL); 665 RECORD(EXPR_FLOATING_LITERAL); 666 RECORD(EXPR_IMAGINARY_LITERAL); 667 RECORD(EXPR_STRING_LITERAL); 668 RECORD(EXPR_CHARACTER_LITERAL); 669 RECORD(EXPR_PAREN); 670 RECORD(EXPR_UNARY_OPERATOR); 671 RECORD(EXPR_SIZEOF_ALIGN_OF); 672 RECORD(EXPR_ARRAY_SUBSCRIPT); 673 RECORD(EXPR_CALL); 674 RECORD(EXPR_MEMBER); 675 RECORD(EXPR_BINARY_OPERATOR); 676 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 677 RECORD(EXPR_CONDITIONAL_OPERATOR); 678 RECORD(EXPR_IMPLICIT_CAST); 679 RECORD(EXPR_CSTYLE_CAST); 680 RECORD(EXPR_COMPOUND_LITERAL); 681 RECORD(EXPR_EXT_VECTOR_ELEMENT); 682 RECORD(EXPR_INIT_LIST); 683 RECORD(EXPR_DESIGNATED_INIT); 684 RECORD(EXPR_IMPLICIT_VALUE_INIT); 685 RECORD(EXPR_VA_ARG); 686 RECORD(EXPR_ADDR_LABEL); 687 RECORD(EXPR_STMT); 688 RECORD(EXPR_CHOOSE); 689 RECORD(EXPR_GNU_NULL); 690 RECORD(EXPR_SHUFFLE_VECTOR); 691 RECORD(EXPR_BLOCK); 692 RECORD(EXPR_BLOCK_DECL_REF); 693 RECORD(EXPR_GENERIC_SELECTION); 694 RECORD(EXPR_OBJC_STRING_LITERAL); 695 RECORD(EXPR_OBJC_ENCODE); 696 RECORD(EXPR_OBJC_SELECTOR_EXPR); 697 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 698 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 699 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 700 RECORD(EXPR_OBJC_KVC_REF_EXPR); 701 RECORD(EXPR_OBJC_MESSAGE_EXPR); 702 RECORD(STMT_OBJC_FOR_COLLECTION); 703 RECORD(STMT_OBJC_CATCH); 704 RECORD(STMT_OBJC_FINALLY); 705 RECORD(STMT_OBJC_AT_TRY); 706 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 707 RECORD(STMT_OBJC_AT_THROW); 708 RECORD(EXPR_CXX_OPERATOR_CALL); 709 RECORD(EXPR_CXX_CONSTRUCT); 710 RECORD(EXPR_CXX_STATIC_CAST); 711 RECORD(EXPR_CXX_DYNAMIC_CAST); 712 RECORD(EXPR_CXX_REINTERPRET_CAST); 713 RECORD(EXPR_CXX_CONST_CAST); 714 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 715 RECORD(EXPR_CXX_BOOL_LITERAL); 716 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 717 RECORD(EXPR_CXX_TYPEID_EXPR); 718 RECORD(EXPR_CXX_TYPEID_TYPE); 719 RECORD(EXPR_CXX_UUIDOF_EXPR); 720 RECORD(EXPR_CXX_UUIDOF_TYPE); 721 RECORD(EXPR_CXX_THIS); 722 RECORD(EXPR_CXX_THROW); 723 RECORD(EXPR_CXX_DEFAULT_ARG); 724 RECORD(EXPR_CXX_BIND_TEMPORARY); 725 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 726 RECORD(EXPR_CXX_NEW); 727 RECORD(EXPR_CXX_DELETE); 728 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 729 RECORD(EXPR_EXPR_WITH_CLEANUPS); 730 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 731 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 732 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 733 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 734 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 735 RECORD(EXPR_CXX_UNARY_TYPE_TRAIT); 736 RECORD(EXPR_CXX_NOEXCEPT); 737 RECORD(EXPR_OPAQUE_VALUE); 738 RECORD(EXPR_BINARY_TYPE_TRAIT); 739 RECORD(EXPR_PACK_EXPANSION); 740 RECORD(EXPR_SIZEOF_PACK); 741 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 742 RECORD(EXPR_CUDA_KERNEL_CALL); 743#undef RECORD 744} 745 746void ASTWriter::WriteBlockInfoBlock() { 747 RecordData Record; 748 Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3); 749 750#define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 751#define RECORD(X) EmitRecordID(X, #X, Stream, Record) 752 753 // AST Top-Level Block. 754 BLOCK(AST_BLOCK); 755 RECORD(ORIGINAL_FILE_NAME); 756 RECORD(ORIGINAL_FILE_ID); 757 RECORD(TYPE_OFFSET); 758 RECORD(DECL_OFFSET); 759 RECORD(LANGUAGE_OPTIONS); 760 RECORD(METADATA); 761 RECORD(IDENTIFIER_OFFSET); 762 RECORD(IDENTIFIER_TABLE); 763 RECORD(EXTERNAL_DEFINITIONS); 764 RECORD(SPECIAL_TYPES); 765 RECORD(STATISTICS); 766 RECORD(TENTATIVE_DEFINITIONS); 767 RECORD(UNUSED_FILESCOPED_DECLS); 768 RECORD(LOCALLY_SCOPED_EXTERNAL_DECLS); 769 RECORD(SELECTOR_OFFSETS); 770 RECORD(METHOD_POOL); 771 RECORD(PP_COUNTER_VALUE); 772 RECORD(SOURCE_LOCATION_OFFSETS); 773 RECORD(SOURCE_LOCATION_PRELOADS); 774 RECORD(STAT_CACHE); 775 RECORD(EXT_VECTOR_DECLS); 776 RECORD(VERSION_CONTROL_BRANCH_REVISION); 777 RECORD(PPD_ENTITIES_OFFSETS); 778 RECORD(IMPORTS); 779 RECORD(REFERENCED_SELECTOR_POOL); 780 RECORD(TU_UPDATE_LEXICAL); 781 RECORD(LOCAL_REDECLARATIONS_MAP); 782 RECORD(SEMA_DECL_REFS); 783 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 784 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 785 RECORD(DECL_REPLACEMENTS); 786 RECORD(UPDATE_VISIBLE); 787 RECORD(DECL_UPDATE_OFFSETS); 788 RECORD(DECL_UPDATES); 789 RECORD(CXX_BASE_SPECIFIER_OFFSETS); 790 RECORD(DIAG_PRAGMA_MAPPINGS); 791 RECORD(CUDA_SPECIAL_DECL_REFS); 792 RECORD(HEADER_SEARCH_TABLE); 793 RECORD(ORIGINAL_PCH_DIR); 794 RECORD(FP_PRAGMA_OPTIONS); 795 RECORD(OPENCL_EXTENSIONS); 796 RECORD(DELEGATING_CTORS); 797 RECORD(FILE_SOURCE_LOCATION_OFFSETS); 798 RECORD(KNOWN_NAMESPACES); 799 RECORD(MODULE_OFFSET_MAP); 800 RECORD(SOURCE_MANAGER_LINE_TABLE); 801 RECORD(OBJC_CATEGORIES_MAP); 802 RECORD(FILE_SORTED_DECLS); 803 RECORD(IMPORTED_MODULES); 804 RECORD(MERGED_DECLARATIONS); 805 RECORD(LOCAL_REDECLARATIONS); 806 RECORD(OBJC_CATEGORIES); 807 808 // SourceManager Block. 809 BLOCK(SOURCE_MANAGER_BLOCK); 810 RECORD(SM_SLOC_FILE_ENTRY); 811 RECORD(SM_SLOC_BUFFER_ENTRY); 812 RECORD(SM_SLOC_BUFFER_BLOB); 813 RECORD(SM_SLOC_EXPANSION_ENTRY); 814 815 // Preprocessor Block. 816 BLOCK(PREPROCESSOR_BLOCK); 817 RECORD(PP_MACRO_OBJECT_LIKE); 818 RECORD(PP_MACRO_FUNCTION_LIKE); 819 RECORD(PP_TOKEN); 820 821 // Decls and Types block. 822 BLOCK(DECLTYPES_BLOCK); 823 RECORD(TYPE_EXT_QUAL); 824 RECORD(TYPE_COMPLEX); 825 RECORD(TYPE_POINTER); 826 RECORD(TYPE_BLOCK_POINTER); 827 RECORD(TYPE_LVALUE_REFERENCE); 828 RECORD(TYPE_RVALUE_REFERENCE); 829 RECORD(TYPE_MEMBER_POINTER); 830 RECORD(TYPE_CONSTANT_ARRAY); 831 RECORD(TYPE_INCOMPLETE_ARRAY); 832 RECORD(TYPE_VARIABLE_ARRAY); 833 RECORD(TYPE_VECTOR); 834 RECORD(TYPE_EXT_VECTOR); 835 RECORD(TYPE_FUNCTION_PROTO); 836 RECORD(TYPE_FUNCTION_NO_PROTO); 837 RECORD(TYPE_TYPEDEF); 838 RECORD(TYPE_TYPEOF_EXPR); 839 RECORD(TYPE_TYPEOF); 840 RECORD(TYPE_RECORD); 841 RECORD(TYPE_ENUM); 842 RECORD(TYPE_OBJC_INTERFACE); 843 RECORD(TYPE_OBJC_OBJECT); 844 RECORD(TYPE_OBJC_OBJECT_POINTER); 845 RECORD(TYPE_DECLTYPE); 846 RECORD(TYPE_ELABORATED); 847 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 848 RECORD(TYPE_UNRESOLVED_USING); 849 RECORD(TYPE_INJECTED_CLASS_NAME); 850 RECORD(TYPE_OBJC_OBJECT); 851 RECORD(TYPE_TEMPLATE_TYPE_PARM); 852 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 853 RECORD(TYPE_DEPENDENT_NAME); 854 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 855 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 856 RECORD(TYPE_PAREN); 857 RECORD(TYPE_PACK_EXPANSION); 858 RECORD(TYPE_ATTRIBUTED); 859 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 860 RECORD(TYPE_ATOMIC); 861 RECORD(DECL_TYPEDEF); 862 RECORD(DECL_ENUM); 863 RECORD(DECL_RECORD); 864 RECORD(DECL_ENUM_CONSTANT); 865 RECORD(DECL_FUNCTION); 866 RECORD(DECL_OBJC_METHOD); 867 RECORD(DECL_OBJC_INTERFACE); 868 RECORD(DECL_OBJC_PROTOCOL); 869 RECORD(DECL_OBJC_IVAR); 870 RECORD(DECL_OBJC_AT_DEFS_FIELD); 871 RECORD(DECL_OBJC_CATEGORY); 872 RECORD(DECL_OBJC_CATEGORY_IMPL); 873 RECORD(DECL_OBJC_IMPLEMENTATION); 874 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 875 RECORD(DECL_OBJC_PROPERTY); 876 RECORD(DECL_OBJC_PROPERTY_IMPL); 877 RECORD(DECL_FIELD); 878 RECORD(DECL_VAR); 879 RECORD(DECL_IMPLICIT_PARAM); 880 RECORD(DECL_PARM_VAR); 881 RECORD(DECL_FILE_SCOPE_ASM); 882 RECORD(DECL_BLOCK); 883 RECORD(DECL_CONTEXT_LEXICAL); 884 RECORD(DECL_CONTEXT_VISIBLE); 885 RECORD(DECL_NAMESPACE); 886 RECORD(DECL_NAMESPACE_ALIAS); 887 RECORD(DECL_USING); 888 RECORD(DECL_USING_SHADOW); 889 RECORD(DECL_USING_DIRECTIVE); 890 RECORD(DECL_UNRESOLVED_USING_VALUE); 891 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 892 RECORD(DECL_LINKAGE_SPEC); 893 RECORD(DECL_CXX_RECORD); 894 RECORD(DECL_CXX_METHOD); 895 RECORD(DECL_CXX_CONSTRUCTOR); 896 RECORD(DECL_CXX_DESTRUCTOR); 897 RECORD(DECL_CXX_CONVERSION); 898 RECORD(DECL_ACCESS_SPEC); 899 RECORD(DECL_FRIEND); 900 RECORD(DECL_FRIEND_TEMPLATE); 901 RECORD(DECL_CLASS_TEMPLATE); 902 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 903 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 904 RECORD(DECL_FUNCTION_TEMPLATE); 905 RECORD(DECL_TEMPLATE_TYPE_PARM); 906 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 907 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 908 RECORD(DECL_STATIC_ASSERT); 909 RECORD(DECL_CXX_BASE_SPECIFIERS); 910 RECORD(DECL_INDIRECTFIELD); 911 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 912 913 // Statements and Exprs can occur in the Decls and Types block. 914 AddStmtsExprs(Stream, Record); 915 916 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 917 RECORD(PPD_MACRO_EXPANSION); 918 RECORD(PPD_MACRO_DEFINITION); 919 RECORD(PPD_INCLUSION_DIRECTIVE); 920 921#undef RECORD 922#undef BLOCK 923 Stream.ExitBlock(); 924} 925 926/// \brief Adjusts the given filename to only write out the portion of the 927/// filename that is not part of the system root directory. 928/// 929/// \param Filename the file name to adjust. 930/// 931/// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and 932/// the returned filename will be adjusted by this system root. 933/// 934/// \returns either the original filename (if it needs no adjustment) or the 935/// adjusted filename (which points into the @p Filename parameter). 936static const char * 937adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) { 938 assert(Filename && "No file name to adjust?"); 939 940 if (isysroot.empty()) 941 return Filename; 942 943 // Verify that the filename and the system root have the same prefix. 944 unsigned Pos = 0; 945 for (; Filename[Pos] && Pos < isysroot.size(); ++Pos) 946 if (Filename[Pos] != isysroot[Pos]) 947 return Filename; // Prefixes don't match. 948 949 // We hit the end of the filename before we hit the end of the system root. 950 if (!Filename[Pos]) 951 return Filename; 952 953 // If the file name has a '/' at the current position, skip over the '/'. 954 // We distinguish sysroot-based includes from absolute includes by the 955 // absence of '/' at the beginning of sysroot-based includes. 956 if (Filename[Pos] == '/') 957 ++Pos; 958 959 return Filename + Pos; 960} 961 962/// \brief Write the AST metadata (e.g., i686-apple-darwin9). 963void ASTWriter::WriteMetadata(ASTContext &Context, StringRef isysroot, 964 const std::string &OutputFile) { 965 using namespace llvm; 966 967 // Metadata 968 const TargetInfo &Target = Context.getTargetInfo(); 969 BitCodeAbbrev *MetaAbbrev = new BitCodeAbbrev(); 970 MetaAbbrev->Add(BitCodeAbbrevOp(METADATA)); 971 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST major 972 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // AST minor 973 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang major 974 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang minor 975 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 976 MetaAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Target triple 977 unsigned MetaAbbrevCode = Stream.EmitAbbrev(MetaAbbrev); 978 979 RecordData Record; 980 Record.push_back(METADATA); 981 Record.push_back(VERSION_MAJOR); 982 Record.push_back(VERSION_MINOR); 983 Record.push_back(CLANG_VERSION_MAJOR); 984 Record.push_back(CLANG_VERSION_MINOR); 985 Record.push_back(!isysroot.empty()); 986 const std::string &Triple = Target.getTriple().getTriple(); 987 Stream.EmitRecordWithBlob(MetaAbbrevCode, Record, Triple); 988 989 if (Chain) { 990 serialization::ModuleManager &Mgr = Chain->getModuleManager(); 991 llvm::SmallVector<char, 128> ModulePaths; 992 Record.clear(); 993 994 for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end(); 995 M != MEnd; ++M) { 996 // Skip modules that weren't directly imported. 997 if (!(*M)->isDirectlyImported()) 998 continue; 999 1000 Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding 1001 // FIXME: Write import location, once it matters. 1002 // FIXME: This writes the absolute path for AST files we depend on. 1003 const std::string &FileName = (*M)->FileName; 1004 Record.push_back(FileName.size()); 1005 Record.append(FileName.begin(), FileName.end()); 1006 } 1007 Stream.EmitRecord(IMPORTS, Record); 1008 } 1009 1010 // Original file name and file ID 1011 SourceManager &SM = Context.getSourceManager(); 1012 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1013 BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev(); 1014 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE_NAME)); 1015 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1016 unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev); 1017 1018 llvm::SmallString<128> MainFilePath(MainFile->getName()); 1019 1020 llvm::sys::fs::make_absolute(MainFilePath); 1021 1022 const char *MainFileNameStr = MainFilePath.c_str(); 1023 MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr, 1024 isysroot); 1025 RecordData Record; 1026 Record.push_back(ORIGINAL_FILE_NAME); 1027 Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr); 1028 1029 Record.clear(); 1030 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1031 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 1032 } 1033 1034 // Original PCH directory 1035 if (!OutputFile.empty() && OutputFile != "-") { 1036 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1037 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 1038 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1039 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 1040 1041 llvm::SmallString<128> OutputPath(OutputFile); 1042 1043 llvm::sys::fs::make_absolute(OutputPath); 1044 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 1045 1046 RecordData Record; 1047 Record.push_back(ORIGINAL_PCH_DIR); 1048 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 1049 } 1050 1051 // Repository branch/version information. 1052 BitCodeAbbrev *RepoAbbrev = new BitCodeAbbrev(); 1053 RepoAbbrev->Add(BitCodeAbbrevOp(VERSION_CONTROL_BRANCH_REVISION)); 1054 RepoAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 1055 unsigned RepoAbbrevCode = Stream.EmitAbbrev(RepoAbbrev); 1056 Record.clear(); 1057 Record.push_back(VERSION_CONTROL_BRANCH_REVISION); 1058 Stream.EmitRecordWithBlob(RepoAbbrevCode, Record, 1059 getClangFullRepositoryVersion()); 1060} 1061 1062/// \brief Write the LangOptions structure. 1063void ASTWriter::WriteLanguageOptions(const LangOptions &LangOpts) { 1064 RecordData Record; 1065#define LANGOPT(Name, Bits, Default, Description) \ 1066 Record.push_back(LangOpts.Name); 1067#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 1068 Record.push_back(static_cast<unsigned>(LangOpts.get##Name())); 1069#include "clang/Basic/LangOptions.def" 1070 1071 Record.push_back(LangOpts.CurrentModule.size()); 1072 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end()); 1073 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1074} 1075 1076//===----------------------------------------------------------------------===// 1077// stat cache Serialization 1078//===----------------------------------------------------------------------===// 1079 1080namespace { 1081// Trait used for the on-disk hash table of stat cache results. 1082class ASTStatCacheTrait { 1083public: 1084 typedef const char * key_type; 1085 typedef key_type key_type_ref; 1086 1087 typedef struct stat data_type; 1088 typedef const data_type &data_type_ref; 1089 1090 static unsigned ComputeHash(const char *path) { 1091 return llvm::HashString(path); 1092 } 1093 1094 std::pair<unsigned,unsigned> 1095 EmitKeyDataLength(raw_ostream& Out, const char *path, 1096 data_type_ref Data) { 1097 unsigned StrLen = strlen(path); 1098 clang::io::Emit16(Out, StrLen); 1099 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1100 clang::io::Emit8(Out, DataLen); 1101 return std::make_pair(StrLen + 1, DataLen); 1102 } 1103 1104 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1105 Out.write(path, KeyLen); 1106 } 1107 1108 void EmitData(raw_ostream &Out, key_type_ref, 1109 data_type_ref Data, unsigned DataLen) { 1110 using namespace clang::io; 1111 uint64_t Start = Out.tell(); (void)Start; 1112 1113 Emit32(Out, (uint32_t) Data.st_ino); 1114 Emit32(Out, (uint32_t) Data.st_dev); 1115 Emit16(Out, (uint16_t) Data.st_mode); 1116 Emit64(Out, (uint64_t) Data.st_mtime); 1117 Emit64(Out, (uint64_t) Data.st_size); 1118 1119 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1120 } 1121}; 1122} // end anonymous namespace 1123 1124/// \brief Write the stat() system call cache to the AST file. 1125void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1126 // Build the on-disk hash table containing information about every 1127 // stat() call. 1128 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1129 unsigned NumStatEntries = 0; 1130 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1131 StatEnd = StatCalls.end(); 1132 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1133 StringRef Filename = Stat->first(); 1134 Generator.insert(Filename.data(), Stat->second); 1135 } 1136 1137 // Create the on-disk hash table in a buffer. 1138 llvm::SmallString<4096> StatCacheData; 1139 uint32_t BucketOffset; 1140 { 1141 llvm::raw_svector_ostream Out(StatCacheData); 1142 // Make sure that no bucket is at offset 0 1143 clang::io::Emit32(Out, 0); 1144 BucketOffset = Generator.Emit(Out); 1145 } 1146 1147 // Create a blob abbreviation 1148 using namespace llvm; 1149 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1150 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1151 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1152 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1153 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1154 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1155 1156 // Write the stat cache 1157 RecordData Record; 1158 Record.push_back(STAT_CACHE); 1159 Record.push_back(BucketOffset); 1160 Record.push_back(NumStatEntries); 1161 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1162} 1163 1164//===----------------------------------------------------------------------===// 1165// Source Manager Serialization 1166//===----------------------------------------------------------------------===// 1167 1168/// \brief Create an abbreviation for the SLocEntry that refers to a 1169/// file. 1170static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1171 using namespace llvm; 1172 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1173 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1174 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1175 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1176 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1177 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1178 // FileEntry fields. 1179 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1180 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden 1182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1183 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1184 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1185 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1186 return Stream.EmitAbbrev(Abbrev); 1187} 1188 1189/// \brief Create an abbreviation for the SLocEntry that refers to a 1190/// buffer. 1191static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1192 using namespace llvm; 1193 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1194 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1198 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1200 return Stream.EmitAbbrev(Abbrev); 1201} 1202 1203/// \brief Create an abbreviation for the SLocEntry that refers to a 1204/// buffer's blob. 1205static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1206 using namespace llvm; 1207 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1208 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1209 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1210 return Stream.EmitAbbrev(Abbrev); 1211} 1212 1213/// \brief Create an abbreviation for the SLocEntry that refers to a macro 1214/// expansion. 1215static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1216 using namespace llvm; 1217 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1218 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1219 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1220 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1222 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1223 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1224 return Stream.EmitAbbrev(Abbrev); 1225} 1226 1227namespace { 1228 // Trait used for the on-disk hash table of header search information. 1229 class HeaderFileInfoTrait { 1230 ASTWriter &Writer; 1231 const HeaderSearch &HS; 1232 1233 // Keep track of the framework names we've used during serialization. 1234 SmallVector<char, 128> FrameworkStringData; 1235 llvm::StringMap<unsigned> FrameworkNameOffset; 1236 1237 public: 1238 HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS) 1239 : Writer(Writer), HS(HS) { } 1240 1241 typedef const char *key_type; 1242 typedef key_type key_type_ref; 1243 1244 typedef HeaderFileInfo data_type; 1245 typedef const data_type &data_type_ref; 1246 1247 static unsigned ComputeHash(const char *path) { 1248 // The hash is based only on the filename portion of the key, so that the 1249 // reader can match based on filenames when symlinking or excess path 1250 // elements ("foo/../", "../") change the form of the name. However, 1251 // complete path is still the key. 1252 return llvm::HashString(llvm::sys::path::filename(path)); 1253 } 1254 1255 std::pair<unsigned,unsigned> 1256 EmitKeyDataLength(raw_ostream& Out, const char *path, 1257 data_type_ref Data) { 1258 unsigned StrLen = strlen(path); 1259 clang::io::Emit16(Out, StrLen); 1260 unsigned DataLen = 1 + 2 + 4 + 4; 1261 clang::io::Emit8(Out, DataLen); 1262 return std::make_pair(StrLen + 1, DataLen); 1263 } 1264 1265 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1266 Out.write(path, KeyLen); 1267 } 1268 1269 void EmitData(raw_ostream &Out, key_type_ref, 1270 data_type_ref Data, unsigned DataLen) { 1271 using namespace clang::io; 1272 uint64_t Start = Out.tell(); (void)Start; 1273 1274 unsigned char Flags = (Data.isImport << 5) 1275 | (Data.isPragmaOnce << 4) 1276 | (Data.DirInfo << 2) 1277 | (Data.Resolved << 1) 1278 | Data.IndexHeaderMapHeader; 1279 Emit8(Out, (uint8_t)Flags); 1280 Emit16(Out, (uint16_t) Data.NumIncludes); 1281 1282 if (!Data.ControllingMacro) 1283 Emit32(Out, (uint32_t)Data.ControllingMacroID); 1284 else 1285 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro)); 1286 1287 unsigned Offset = 0; 1288 if (!Data.Framework.empty()) { 1289 // If this header refers into a framework, save the framework name. 1290 llvm::StringMap<unsigned>::iterator Pos 1291 = FrameworkNameOffset.find(Data.Framework); 1292 if (Pos == FrameworkNameOffset.end()) { 1293 Offset = FrameworkStringData.size() + 1; 1294 FrameworkStringData.append(Data.Framework.begin(), 1295 Data.Framework.end()); 1296 FrameworkStringData.push_back(0); 1297 1298 FrameworkNameOffset[Data.Framework] = Offset; 1299 } else 1300 Offset = Pos->second; 1301 } 1302 Emit32(Out, Offset); 1303 1304 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1305 } 1306 1307 const char *strings_begin() const { return FrameworkStringData.begin(); } 1308 const char *strings_end() const { return FrameworkStringData.end(); } 1309 }; 1310} // end anonymous namespace 1311 1312/// \brief Write the header search block for the list of files that 1313/// 1314/// \param HS The header search structure to save. 1315/// 1316/// \param Chain Whether we're creating a chained AST file. 1317void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) { 1318 SmallVector<const FileEntry *, 16> FilesByUID; 1319 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1320 1321 if (FilesByUID.size() > HS.header_file_size()) 1322 FilesByUID.resize(HS.header_file_size()); 1323 1324 HeaderFileInfoTrait GeneratorTrait(*this, HS); 1325 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1326 SmallVector<const char *, 4> SavedStrings; 1327 unsigned NumHeaderSearchEntries = 0; 1328 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1329 const FileEntry *File = FilesByUID[UID]; 1330 if (!File) 1331 continue; 1332 1333 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo 1334 // from the external source if it was not provided already. 1335 const HeaderFileInfo &HFI = HS.getFileInfo(File); 1336 if (HFI.External && Chain) 1337 continue; 1338 1339 // Turn the file name into an absolute path, if it isn't already. 1340 const char *Filename = File->getName(); 1341 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1342 1343 // If we performed any translation on the file name at all, we need to 1344 // save this string, since the generator will refer to it later. 1345 if (Filename != File->getName()) { 1346 Filename = strdup(Filename); 1347 SavedStrings.push_back(Filename); 1348 } 1349 1350 Generator.insert(Filename, HFI, GeneratorTrait); 1351 ++NumHeaderSearchEntries; 1352 } 1353 1354 // Create the on-disk hash table in a buffer. 1355 llvm::SmallString<4096> TableData; 1356 uint32_t BucketOffset; 1357 { 1358 llvm::raw_svector_ostream Out(TableData); 1359 // Make sure that no bucket is at offset 0 1360 clang::io::Emit32(Out, 0); 1361 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1362 } 1363 1364 // Create a blob abbreviation 1365 using namespace llvm; 1366 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1367 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1368 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1369 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1370 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1371 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1372 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 1373 1374 // Write the header search table 1375 RecordData Record; 1376 Record.push_back(HEADER_SEARCH_TABLE); 1377 Record.push_back(BucketOffset); 1378 Record.push_back(NumHeaderSearchEntries); 1379 Record.push_back(TableData.size()); 1380 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1381 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 1382 1383 // Free all of the strings we had to duplicate. 1384 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1385 free((void*)SavedStrings[I]); 1386} 1387 1388/// \brief Writes the block containing the serialized form of the 1389/// source manager. 1390/// 1391/// TODO: We should probably use an on-disk hash table (stored in a 1392/// blob), indexed based on the file name, so that we only create 1393/// entries for files that we actually need. In the common case (no 1394/// errors), we probably won't have to create file entries for any of 1395/// the files in the AST. 1396void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1397 const Preprocessor &PP, 1398 StringRef isysroot) { 1399 RecordData Record; 1400 1401 // Enter the source manager block. 1402 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1403 1404 // Abbreviations for the various kinds of source-location entries. 1405 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1406 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1407 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1408 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 1409 1410 // Write out the source location entry table. We skip the first 1411 // entry, which is always the same dummy entry. 1412 std::vector<uint32_t> SLocEntryOffsets; 1413 // Write out the offsets of only source location file entries. 1414 // We will go through them in ASTReader::validateFileEntries(). 1415 std::vector<uint32_t> SLocFileEntryOffsets; 1416 RecordData PreloadSLocs; 1417 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 1418 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 1419 I != N; ++I) { 1420 // Get this source location entry. 1421 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1422 1423 // Record the offset of this source-location entry. 1424 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1425 1426 // Figure out which record code to use. 1427 unsigned Code; 1428 if (SLoc->isFile()) { 1429 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 1430 if (Cache->OrigEntry) { 1431 Code = SM_SLOC_FILE_ENTRY; 1432 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1433 } else 1434 Code = SM_SLOC_BUFFER_ENTRY; 1435 } else 1436 Code = SM_SLOC_EXPANSION_ENTRY; 1437 Record.clear(); 1438 Record.push_back(Code); 1439 1440 // Starting offset of this entry within this module, so skip the dummy. 1441 Record.push_back(SLoc->getOffset() - 2); 1442 if (SLoc->isFile()) { 1443 const SrcMgr::FileInfo &File = SLoc->getFile(); 1444 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1445 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1446 Record.push_back(File.hasLineDirectives()); 1447 1448 const SrcMgr::ContentCache *Content = File.getContentCache(); 1449 if (Content->OrigEntry) { 1450 assert(Content->OrigEntry == Content->ContentsEntry && 1451 "Writing to AST an overridden file is not supported"); 1452 1453 // The source location entry is a file. The blob associated 1454 // with this entry is the file name. 1455 1456 // Emit size/modification time for this file. 1457 Record.push_back(Content->OrigEntry->getSize()); 1458 Record.push_back(Content->OrigEntry->getModificationTime()); 1459 Record.push_back(Content->BufferOverridden); 1460 Record.push_back(File.NumCreatedFIDs); 1461 1462 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc); 1463 if (FDI != FileDeclIDs.end()) { 1464 Record.push_back(FDI->second->FirstDeclIndex); 1465 Record.push_back(FDI->second->DeclIDs.size()); 1466 } else { 1467 Record.push_back(0); 1468 Record.push_back(0); 1469 } 1470 1471 // Turn the file name into an absolute path, if it isn't already. 1472 const char *Filename = Content->OrigEntry->getName(); 1473 llvm::SmallString<128> FilePath(Filename); 1474 1475 // Ask the file manager to fixup the relative path for us. This will 1476 // honor the working directory. 1477 SourceMgr.getFileManager().FixupRelativePath(FilePath); 1478 1479 // FIXME: This call to make_absolute shouldn't be necessary, the 1480 // call to FixupRelativePath should always return an absolute path. 1481 llvm::sys::fs::make_absolute(FilePath); 1482 Filename = FilePath.c_str(); 1483 1484 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1485 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1486 1487 if (Content->BufferOverridden) { 1488 Record.clear(); 1489 Record.push_back(SM_SLOC_BUFFER_BLOB); 1490 const llvm::MemoryBuffer *Buffer 1491 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1492 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1493 StringRef(Buffer->getBufferStart(), 1494 Buffer->getBufferSize() + 1)); 1495 } 1496 } else { 1497 // The source location entry is a buffer. The blob associated 1498 // with this entry contains the contents of the buffer. 1499 1500 // We add one to the size so that we capture the trailing NULL 1501 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1502 // the reader side). 1503 const llvm::MemoryBuffer *Buffer 1504 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1505 const char *Name = Buffer->getBufferIdentifier(); 1506 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1507 StringRef(Name, strlen(Name) + 1)); 1508 Record.clear(); 1509 Record.push_back(SM_SLOC_BUFFER_BLOB); 1510 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1511 StringRef(Buffer->getBufferStart(), 1512 Buffer->getBufferSize() + 1)); 1513 1514 if (strcmp(Name, "<built-in>") == 0) { 1515 PreloadSLocs.push_back(SLocEntryOffsets.size()); 1516 } 1517 } 1518 } else { 1519 // The source location entry is a macro expansion. 1520 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 1521 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 1522 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 1523 Record.push_back(Expansion.isMacroArgExpansion() ? 0 1524 : Expansion.getExpansionLocEnd().getRawEncoding()); 1525 1526 // Compute the token length for this macro expansion. 1527 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 1528 if (I + 1 != N) 1529 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 1530 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1531 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 1532 } 1533 } 1534 1535 Stream.ExitBlock(); 1536 1537 if (SLocEntryOffsets.empty()) 1538 return; 1539 1540 // Write the source-location offsets table into the AST block. This 1541 // table is used for lazily loading source-location information. 1542 using namespace llvm; 1543 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1544 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1545 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1546 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 1547 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1548 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1549 1550 Record.clear(); 1551 Record.push_back(SOURCE_LOCATION_OFFSETS); 1552 Record.push_back(SLocEntryOffsets.size()); 1553 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 1554 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 1555 1556 Abbrev = new BitCodeAbbrev(); 1557 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS)); 1558 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1559 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1560 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1561 1562 Record.clear(); 1563 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS); 1564 Record.push_back(SLocFileEntryOffsets.size()); 1565 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record, 1566 data(SLocFileEntryOffsets)); 1567 1568 // Write the source location entry preloads array, telling the AST 1569 // reader which source locations entries it should load eagerly. 1570 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1571 1572 // Write the line table. It depends on remapping working, so it must come 1573 // after the source location offsets. 1574 if (SourceMgr.hasLineTable()) { 1575 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1576 1577 Record.clear(); 1578 // Emit the file names 1579 Record.push_back(LineTable.getNumFilenames()); 1580 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1581 // Emit the file name 1582 const char *Filename = LineTable.getFilename(I); 1583 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1584 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1585 Record.push_back(FilenameLen); 1586 if (FilenameLen) 1587 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1588 } 1589 1590 // Emit the line entries 1591 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1592 L != LEnd; ++L) { 1593 // Only emit entries for local files. 1594 if (L->first < 0) 1595 continue; 1596 1597 // Emit the file ID 1598 Record.push_back(L->first); 1599 1600 // Emit the line entries 1601 Record.push_back(L->second.size()); 1602 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1603 LEEnd = L->second.end(); 1604 LE != LEEnd; ++LE) { 1605 Record.push_back(LE->FileOffset); 1606 Record.push_back(LE->LineNo); 1607 Record.push_back(LE->FilenameID); 1608 Record.push_back((unsigned)LE->FileKind); 1609 Record.push_back(LE->IncludeOffset); 1610 } 1611 } 1612 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 1613 } 1614} 1615 1616//===----------------------------------------------------------------------===// 1617// Preprocessor Serialization 1618//===----------------------------------------------------------------------===// 1619 1620static int compareMacroDefinitions(const void *XPtr, const void *YPtr) { 1621 const std::pair<const IdentifierInfo *, MacroInfo *> &X = 1622 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr; 1623 const std::pair<const IdentifierInfo *, MacroInfo *> &Y = 1624 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr; 1625 return X.first->getName().compare(Y.first->getName()); 1626} 1627 1628/// \brief Writes the block containing the serialized form of the 1629/// preprocessor. 1630/// 1631void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 1632 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1633 if (PPRec) 1634 WritePreprocessorDetail(*PPRec); 1635 1636 RecordData Record; 1637 1638 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1639 if (PP.getCounterValue() != 0) { 1640 Record.push_back(PP.getCounterValue()); 1641 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1642 Record.clear(); 1643 } 1644 1645 // Enter the preprocessor block. 1646 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1647 1648 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1649 // FIXME: use diagnostics subsystem for localization etc. 1650 if (PP.SawDateOrTime()) 1651 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1652 1653 1654 // Loop over all the macro definitions that are live at the end of the file, 1655 // emitting each to the PP section. 1656 1657 // Construct the list of macro definitions that need to be serialized. 1658 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 1659 MacrosToEmit; 1660 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen; 1661 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 1662 E = PP.macro_end(Chain == 0); 1663 I != E; ++I) { 1664 const IdentifierInfo *Name = I->first; 1665 if (!IsModule || I->second->isPublic()) { 1666 MacroDefinitionsSeen.insert(Name); 1667 MacrosToEmit.push_back(std::make_pair(I->first, I->second)); 1668 } 1669 } 1670 1671 // Sort the set of macro definitions that need to be serialized by the 1672 // name of the macro, to provide a stable ordering. 1673 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 1674 &compareMacroDefinitions); 1675 1676 // Resolve any identifiers that defined macros at the time they were 1677 // deserialized, adding them to the list of macros to emit (if appropriate). 1678 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) { 1679 IdentifierInfo *Name 1680 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]); 1681 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name)) 1682 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name))); 1683 } 1684 1685 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) { 1686 const IdentifierInfo *Name = MacrosToEmit[I].first; 1687 MacroInfo *MI = MacrosToEmit[I].second; 1688 if (!MI) 1689 continue; 1690 1691 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1692 // been redefined by the header (in which case they are not isBuiltinMacro). 1693 // Also skip macros from a AST file if we're chaining. 1694 1695 // FIXME: There is a (probably minor) optimization we could do here, if 1696 // the macro comes from the original PCH but the identifier comes from a 1697 // chained PCH, by storing the offset into the original PCH rather than 1698 // writing the macro definition a second time. 1699 if (MI->isBuiltinMacro() || 1700 (Chain && 1701 Name->isFromAST() && !Name->hasChangedSinceDeserialization() && 1702 MI->isFromAST() && !MI->hasChangedAfterLoad())) 1703 continue; 1704 1705 AddIdentifierRef(Name, Record); 1706 MacroOffsets[Name] = Stream.GetCurrentBitNo(); 1707 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1708 Record.push_back(MI->isUsed()); 1709 Record.push_back(MI->isPublic()); 1710 AddSourceLocation(MI->getVisibilityLocation(), Record); 1711 unsigned Code; 1712 if (MI->isObjectLike()) { 1713 Code = PP_MACRO_OBJECT_LIKE; 1714 } else { 1715 Code = PP_MACRO_FUNCTION_LIKE; 1716 1717 Record.push_back(MI->isC99Varargs()); 1718 Record.push_back(MI->isGNUVarargs()); 1719 Record.push_back(MI->getNumArgs()); 1720 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1721 I != E; ++I) 1722 AddIdentifierRef(*I, Record); 1723 } 1724 1725 // If we have a detailed preprocessing record, record the macro definition 1726 // ID that corresponds to this macro. 1727 if (PPRec) 1728 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 1729 1730 Stream.EmitRecord(Code, Record); 1731 Record.clear(); 1732 1733 // Emit the tokens array. 1734 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1735 // Note that we know that the preprocessor does not have any annotation 1736 // tokens in it because they are created by the parser, and thus can't be 1737 // in a macro definition. 1738 const Token &Tok = MI->getReplacementToken(TokNo); 1739 1740 Record.push_back(Tok.getLocation().getRawEncoding()); 1741 Record.push_back(Tok.getLength()); 1742 1743 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1744 // it is needed. 1745 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1746 // FIXME: Should translate token kind to a stable encoding. 1747 Record.push_back(Tok.getKind()); 1748 // FIXME: Should translate token flags to a stable encoding. 1749 Record.push_back(Tok.getFlags()); 1750 1751 Stream.EmitRecord(PP_TOKEN, Record); 1752 Record.clear(); 1753 } 1754 ++NumMacros; 1755 } 1756 Stream.ExitBlock(); 1757} 1758 1759void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1760 if (PPRec.local_begin() == PPRec.local_end()) 1761 return; 1762 1763 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 1764 1765 // Enter the preprocessor block. 1766 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1767 1768 // If the preprocessor has a preprocessing record, emit it. 1769 unsigned NumPreprocessingRecords = 0; 1770 using namespace llvm; 1771 1772 // Set up the abbreviation for 1773 unsigned InclusionAbbrev = 0; 1774 { 1775 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1776 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1777 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1778 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1779 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1780 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1781 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1782 } 1783 1784 unsigned FirstPreprocessorEntityID 1785 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 1786 + NUM_PREDEF_PP_ENTITY_IDS; 1787 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 1788 RecordData Record; 1789 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 1790 EEnd = PPRec.local_end(); 1791 E != EEnd; 1792 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 1793 Record.clear(); 1794 1795 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(), 1796 Stream.GetCurrentBitNo())); 1797 1798 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1799 // Record this macro definition's ID. 1800 MacroDefinitions[MD] = NextPreprocessorEntityID; 1801 1802 AddIdentifierRef(MD->getName(), Record); 1803 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1804 continue; 1805 } 1806 1807 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 1808 Record.push_back(ME->isBuiltinMacro()); 1809 if (ME->isBuiltinMacro()) 1810 AddIdentifierRef(ME->getName(), Record); 1811 else 1812 Record.push_back(MacroDefinitions[ME->getDefinition()]); 1813 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 1814 continue; 1815 } 1816 1817 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1818 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1819 Record.push_back(ID->getFileName().size()); 1820 Record.push_back(ID->wasInQuotes()); 1821 Record.push_back(static_cast<unsigned>(ID->getKind())); 1822 llvm::SmallString<64> Buffer; 1823 Buffer += ID->getFileName(); 1824 Buffer += ID->getFile()->getName(); 1825 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1826 continue; 1827 } 1828 1829 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1830 } 1831 Stream.ExitBlock(); 1832 1833 // Write the offsets table for the preprocessing record. 1834 if (NumPreprocessingRecords > 0) { 1835 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 1836 1837 // Write the offsets table for identifier IDs. 1838 using namespace llvm; 1839 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1840 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 1841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 1842 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1843 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1844 1845 Record.clear(); 1846 Record.push_back(PPD_ENTITIES_OFFSETS); 1847 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 1848 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 1849 data(PreprocessedEntityOffsets)); 1850 } 1851} 1852 1853unsigned ASTWriter::getSubmoduleID(Module *Mod) { 1854 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod); 1855 if (Known != SubmoduleIDs.end()) 1856 return Known->second; 1857 1858 return SubmoduleIDs[Mod] = NextSubmoduleID++; 1859} 1860 1861/// \brief Compute the number of modules within the given tree (including the 1862/// given module). 1863static unsigned getNumberOfModules(Module *Mod) { 1864 unsigned ChildModules = 0; 1865 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 1866 SubEnd = Mod->submodule_end(); 1867 Sub != SubEnd; ++Sub) 1868 ChildModules += getNumberOfModules(*Sub); 1869 1870 return ChildModules + 1; 1871} 1872 1873void ASTWriter::WriteSubmodules(Module *WritingModule) { 1874 // Determine the dependencies of our module and each of it's submodules. 1875 // FIXME: This feels like it belongs somewhere else, but there are no 1876 // other consumers of this information. 1877 SourceManager &SrcMgr = PP->getSourceManager(); 1878 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 1879 for (ASTContext::import_iterator I = Context->local_import_begin(), 1880 IEnd = Context->local_import_end(); 1881 I != IEnd; ++I) { 1882 if (Module *ImportedFrom 1883 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(), 1884 SrcMgr))) { 1885 ImportedFrom->Imports.push_back(I->getImportedModule()); 1886 } 1887 } 1888 1889 // Enter the submodule description block. 1890 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 1891 1892 // Write the abbreviations needed for the submodules block. 1893 using namespace llvm; 1894 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1895 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 1896 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 1897 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 1898 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 1899 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 1900 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem 1901 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules... 1902 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit... 1903 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild... 1904 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1905 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev); 1906 1907 Abbrev = new BitCodeAbbrev(); 1908 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER)); 1909 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1910 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev); 1911 1912 Abbrev = new BitCodeAbbrev(); 1913 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 1914 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1915 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev); 1916 1917 Abbrev = new BitCodeAbbrev(); 1918 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR)); 1919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1920 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev); 1921 1922 Abbrev = new BitCodeAbbrev(); 1923 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES)); 1924 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature 1925 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev); 1926 1927 // Write the submodule metadata block. 1928 RecordData Record; 1929 Record.push_back(getNumberOfModules(WritingModule)); 1930 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS); 1931 Stream.EmitRecord(SUBMODULE_METADATA, Record); 1932 1933 // Write all of the submodules. 1934 std::queue<Module *> Q; 1935 Q.push(WritingModule); 1936 while (!Q.empty()) { 1937 Module *Mod = Q.front(); 1938 Q.pop(); 1939 unsigned ID = getSubmoduleID(Mod); 1940 1941 // Emit the definition of the block. 1942 Record.clear(); 1943 Record.push_back(SUBMODULE_DEFINITION); 1944 Record.push_back(ID); 1945 if (Mod->Parent) { 1946 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 1947 Record.push_back(SubmoduleIDs[Mod->Parent]); 1948 } else { 1949 Record.push_back(0); 1950 } 1951 Record.push_back(Mod->IsFramework); 1952 Record.push_back(Mod->IsExplicit); 1953 Record.push_back(Mod->IsSystem); 1954 Record.push_back(Mod->InferSubmodules); 1955 Record.push_back(Mod->InferExplicitSubmodules); 1956 Record.push_back(Mod->InferExportWildcard); 1957 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 1958 1959 // Emit the requirements. 1960 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) { 1961 Record.clear(); 1962 Record.push_back(SUBMODULE_REQUIRES); 1963 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, 1964 Mod->Requires[I].data(), 1965 Mod->Requires[I].size()); 1966 } 1967 1968 // Emit the umbrella header, if there is one. 1969 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) { 1970 Record.clear(); 1971 Record.push_back(SUBMODULE_UMBRELLA_HEADER); 1972 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 1973 UmbrellaHeader->getName()); 1974 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) { 1975 Record.clear(); 1976 Record.push_back(SUBMODULE_UMBRELLA_DIR); 1977 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 1978 UmbrellaDir->getName()); 1979 } 1980 1981 // Emit the headers. 1982 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) { 1983 Record.clear(); 1984 Record.push_back(SUBMODULE_HEADER); 1985 Stream.EmitRecordWithBlob(HeaderAbbrev, Record, 1986 Mod->Headers[I]->getName()); 1987 } 1988 1989 // Emit the imports. 1990 if (!Mod->Imports.empty()) { 1991 Record.clear(); 1992 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) { 1993 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]); 1994 assert(ImportedID && "Unknown submodule!"); 1995 Record.push_back(ImportedID); 1996 } 1997 Stream.EmitRecord(SUBMODULE_IMPORTS, Record); 1998 } 1999 2000 // Emit the exports. 2001 if (!Mod->Exports.empty()) { 2002 Record.clear(); 2003 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) { 2004 if (Module *Exported = Mod->Exports[I].getPointer()) { 2005 unsigned ExportedID = SubmoduleIDs[Exported]; 2006 assert(ExportedID > 0 && "Unknown submodule ID?"); 2007 Record.push_back(ExportedID); 2008 } else { 2009 Record.push_back(0); 2010 } 2011 2012 Record.push_back(Mod->Exports[I].getInt()); 2013 } 2014 Stream.EmitRecord(SUBMODULE_EXPORTS, Record); 2015 } 2016 2017 // Queue up the submodules of this module. 2018 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 2019 SubEnd = Mod->submodule_end(); 2020 Sub != SubEnd; ++Sub) 2021 Q.push(*Sub); 2022 } 2023 2024 Stream.ExitBlock(); 2025 2026 assert((NextSubmoduleID - FirstSubmoduleID 2027 == getNumberOfModules(WritingModule)) && "Wrong # of submodules"); 2028} 2029 2030serialization::SubmoduleID 2031ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) { 2032 if (Loc.isInvalid() || !WritingModule) 2033 return 0; // No submodule 2034 2035 // Find the module that owns this location. 2036 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 2037 Module *OwningMod 2038 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager())); 2039 if (!OwningMod) 2040 return 0; 2041 2042 // Check whether this submodule is part of our own module. 2043 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule)) 2044 return 0; 2045 2046 return getSubmoduleID(OwningMod); 2047} 2048 2049void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) { 2050 RecordData Record; 2051 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator 2052 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 2053 I != E; ++I) { 2054 const DiagnosticsEngine::DiagStatePoint &point = *I; 2055 if (point.Loc.isInvalid()) 2056 continue; 2057 2058 Record.push_back(point.Loc.getRawEncoding()); 2059 for (DiagnosticsEngine::DiagState::const_iterator 2060 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 2061 if (I->second.isPragma()) { 2062 Record.push_back(I->first); 2063 Record.push_back(I->second.getMapping()); 2064 } 2065 } 2066 Record.push_back(-1); // mark the end of the diag/map pairs for this 2067 // location. 2068 } 2069 2070 if (!Record.empty()) 2071 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 2072} 2073 2074void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 2075 if (CXXBaseSpecifiersOffsets.empty()) 2076 return; 2077 2078 RecordData Record; 2079 2080 // Create a blob abbreviation for the C++ base specifiers offsets. 2081 using namespace llvm; 2082 2083 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2084 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 2085 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2086 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2087 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2088 2089 // Write the base specifier offsets table. 2090 Record.clear(); 2091 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 2092 Record.push_back(CXXBaseSpecifiersOffsets.size()); 2093 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 2094 data(CXXBaseSpecifiersOffsets)); 2095} 2096 2097//===----------------------------------------------------------------------===// 2098// Type Serialization 2099//===----------------------------------------------------------------------===// 2100 2101/// \brief Write the representation of a type to the AST stream. 2102void ASTWriter::WriteType(QualType T) { 2103 TypeIdx &Idx = TypeIdxs[T]; 2104 if (Idx.getIndex() == 0) // we haven't seen this type before. 2105 Idx = TypeIdx(NextTypeID++); 2106 2107 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 2108 2109 // Record the offset for this type. 2110 unsigned Index = Idx.getIndex() - FirstTypeID; 2111 if (TypeOffsets.size() == Index) 2112 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 2113 else if (TypeOffsets.size() < Index) { 2114 TypeOffsets.resize(Index + 1); 2115 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 2116 } 2117 2118 RecordData Record; 2119 2120 // Emit the type's representation. 2121 ASTTypeWriter W(*this, Record); 2122 2123 if (T.hasLocalNonFastQualifiers()) { 2124 Qualifiers Qs = T.getLocalQualifiers(); 2125 AddTypeRef(T.getLocalUnqualifiedType(), Record); 2126 Record.push_back(Qs.getAsOpaqueValue()); 2127 W.Code = TYPE_EXT_QUAL; 2128 } else { 2129 switch (T->getTypeClass()) { 2130 // For all of the concrete, non-dependent types, call the 2131 // appropriate visitor function. 2132#define TYPE(Class, Base) \ 2133 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 2134#define ABSTRACT_TYPE(Class, Base) 2135#include "clang/AST/TypeNodes.def" 2136 } 2137 } 2138 2139 // Emit the serialized record. 2140 Stream.EmitRecord(W.Code, Record); 2141 2142 // Flush any expressions that were written as part of this type. 2143 FlushStmts(); 2144} 2145 2146//===----------------------------------------------------------------------===// 2147// Declaration Serialization 2148//===----------------------------------------------------------------------===// 2149 2150/// \brief Write the block containing all of the declaration IDs 2151/// lexically declared within the given DeclContext. 2152/// 2153/// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 2154/// bistream, or 0 if no block was written. 2155uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 2156 DeclContext *DC) { 2157 if (DC->decls_empty()) 2158 return 0; 2159 2160 uint64_t Offset = Stream.GetCurrentBitNo(); 2161 RecordData Record; 2162 Record.push_back(DECL_CONTEXT_LEXICAL); 2163 SmallVector<KindDeclIDPair, 64> Decls; 2164 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 2165 D != DEnd; ++D) 2166 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 2167 2168 ++NumLexicalDeclContexts; 2169 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 2170 return Offset; 2171} 2172 2173void ASTWriter::WriteTypeDeclOffsets() { 2174 using namespace llvm; 2175 RecordData Record; 2176 2177 // Write the type offsets array 2178 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2179 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 2180 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 2181 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 2182 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 2183 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2184 Record.clear(); 2185 Record.push_back(TYPE_OFFSET); 2186 Record.push_back(TypeOffsets.size()); 2187 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 2188 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 2189 2190 // Write the declaration offsets array 2191 Abbrev = new BitCodeAbbrev(); 2192 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 2193 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 2194 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 2195 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 2196 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2197 Record.clear(); 2198 Record.push_back(DECL_OFFSET); 2199 Record.push_back(DeclOffsets.size()); 2200 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 2201 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 2202} 2203 2204void ASTWriter::WriteFileDeclIDsMap() { 2205 using namespace llvm; 2206 RecordData Record; 2207 2208 // Join the vectors of DeclIDs from all files. 2209 SmallVector<DeclID, 256> FileSortedIDs; 2210 for (FileDeclIDsTy::iterator 2211 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) { 2212 DeclIDInFileInfo &Info = *FI->second; 2213 Info.FirstDeclIndex = FileSortedIDs.size(); 2214 for (LocDeclIDsTy::iterator 2215 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI) 2216 FileSortedIDs.push_back(DI->second); 2217 } 2218 2219 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2220 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 2221 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2222 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 2223 Record.push_back(FILE_SORTED_DECLS); 2224 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); 2225} 2226 2227//===----------------------------------------------------------------------===// 2228// Global Method Pool and Selector Serialization 2229//===----------------------------------------------------------------------===// 2230 2231namespace { 2232// Trait used for the on-disk hash table used in the method pool. 2233class ASTMethodPoolTrait { 2234 ASTWriter &Writer; 2235 2236public: 2237 typedef Selector key_type; 2238 typedef key_type key_type_ref; 2239 2240 struct data_type { 2241 SelectorID ID; 2242 ObjCMethodList Instance, Factory; 2243 }; 2244 typedef const data_type& data_type_ref; 2245 2246 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 2247 2248 static unsigned ComputeHash(Selector Sel) { 2249 return serialization::ComputeHash(Sel); 2250 } 2251 2252 std::pair<unsigned,unsigned> 2253 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 2254 data_type_ref Methods) { 2255 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 2256 clang::io::Emit16(Out, KeyLen); 2257 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 2258 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2259 Method = Method->Next) 2260 if (Method->Method) 2261 DataLen += 4; 2262 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2263 Method = Method->Next) 2264 if (Method->Method) 2265 DataLen += 4; 2266 clang::io::Emit16(Out, DataLen); 2267 return std::make_pair(KeyLen, DataLen); 2268 } 2269 2270 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 2271 uint64_t Start = Out.tell(); 2272 assert((Start >> 32) == 0 && "Selector key offset too large"); 2273 Writer.SetSelectorOffset(Sel, Start); 2274 unsigned N = Sel.getNumArgs(); 2275 clang::io::Emit16(Out, N); 2276 if (N == 0) 2277 N = 1; 2278 for (unsigned I = 0; I != N; ++I) 2279 clang::io::Emit32(Out, 2280 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 2281 } 2282 2283 void EmitData(raw_ostream& Out, key_type_ref, 2284 data_type_ref Methods, unsigned DataLen) { 2285 uint64_t Start = Out.tell(); (void)Start; 2286 clang::io::Emit32(Out, Methods.ID); 2287 unsigned NumInstanceMethods = 0; 2288 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2289 Method = Method->Next) 2290 if (Method->Method) 2291 ++NumInstanceMethods; 2292 2293 unsigned NumFactoryMethods = 0; 2294 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2295 Method = Method->Next) 2296 if (Method->Method) 2297 ++NumFactoryMethods; 2298 2299 clang::io::Emit16(Out, NumInstanceMethods); 2300 clang::io::Emit16(Out, NumFactoryMethods); 2301 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2302 Method = Method->Next) 2303 if (Method->Method) 2304 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2305 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2306 Method = Method->Next) 2307 if (Method->Method) 2308 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2309 2310 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2311 } 2312}; 2313} // end anonymous namespace 2314 2315/// \brief Write ObjC data: selectors and the method pool. 2316/// 2317/// The method pool contains both instance and factory methods, stored 2318/// in an on-disk hash table indexed by the selector. The hash table also 2319/// contains an empty entry for every other selector known to Sema. 2320void ASTWriter::WriteSelectors(Sema &SemaRef) { 2321 using namespace llvm; 2322 2323 // Do we have to do anything at all? 2324 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 2325 return; 2326 unsigned NumTableEntries = 0; 2327 // Create and write out the blob that contains selectors and the method pool. 2328 { 2329 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 2330 ASTMethodPoolTrait Trait(*this); 2331 2332 // Create the on-disk hash table representation. We walk through every 2333 // selector we've seen and look it up in the method pool. 2334 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 2335 for (llvm::DenseMap<Selector, SelectorID>::iterator 2336 I = SelectorIDs.begin(), E = SelectorIDs.end(); 2337 I != E; ++I) { 2338 Selector S = I->first; 2339 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 2340 ASTMethodPoolTrait::data_type Data = { 2341 I->second, 2342 ObjCMethodList(), 2343 ObjCMethodList() 2344 }; 2345 if (F != SemaRef.MethodPool.end()) { 2346 Data.Instance = F->second.first; 2347 Data.Factory = F->second.second; 2348 } 2349 // Only write this selector if it's not in an existing AST or something 2350 // changed. 2351 if (Chain && I->second < FirstSelectorID) { 2352 // Selector already exists. Did it change? 2353 bool changed = false; 2354 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 2355 M = M->Next) { 2356 if (!M->Method->isFromASTFile()) 2357 changed = true; 2358 } 2359 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 2360 M = M->Next) { 2361 if (!M->Method->isFromASTFile()) 2362 changed = true; 2363 } 2364 if (!changed) 2365 continue; 2366 } else if (Data.Instance.Method || Data.Factory.Method) { 2367 // A new method pool entry. 2368 ++NumTableEntries; 2369 } 2370 Generator.insert(S, Data, Trait); 2371 } 2372 2373 // Create the on-disk hash table in a buffer. 2374 llvm::SmallString<4096> MethodPool; 2375 uint32_t BucketOffset; 2376 { 2377 ASTMethodPoolTrait Trait(*this); 2378 llvm::raw_svector_ostream Out(MethodPool); 2379 // Make sure that no bucket is at offset 0 2380 clang::io::Emit32(Out, 0); 2381 BucketOffset = Generator.Emit(Out, Trait); 2382 } 2383 2384 // Create a blob abbreviation 2385 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2386 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 2387 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2388 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2389 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2390 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 2391 2392 // Write the method pool 2393 RecordData Record; 2394 Record.push_back(METHOD_POOL); 2395 Record.push_back(BucketOffset); 2396 Record.push_back(NumTableEntries); 2397 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 2398 2399 // Create a blob abbreviation for the selector table offsets. 2400 Abbrev = new BitCodeAbbrev(); 2401 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 2402 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2403 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2404 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2405 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2406 2407 // Write the selector offsets table. 2408 Record.clear(); 2409 Record.push_back(SELECTOR_OFFSETS); 2410 Record.push_back(SelectorOffsets.size()); 2411 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 2412 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 2413 data(SelectorOffsets)); 2414 } 2415} 2416 2417/// \brief Write the selectors referenced in @selector expression into AST file. 2418void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 2419 using namespace llvm; 2420 if (SemaRef.ReferencedSelectors.empty()) 2421 return; 2422 2423 RecordData Record; 2424 2425 // Note: this writes out all references even for a dependent AST. But it is 2426 // very tricky to fix, and given that @selector shouldn't really appear in 2427 // headers, probably not worth it. It's not a correctness issue. 2428 for (DenseMap<Selector, SourceLocation>::iterator S = 2429 SemaRef.ReferencedSelectors.begin(), 2430 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 2431 Selector Sel = (*S).first; 2432 SourceLocation Loc = (*S).second; 2433 AddSelectorRef(Sel, Record); 2434 AddSourceLocation(Loc, Record); 2435 } 2436 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 2437} 2438 2439//===----------------------------------------------------------------------===// 2440// Identifier Table Serialization 2441//===----------------------------------------------------------------------===// 2442 2443namespace { 2444class ASTIdentifierTableTrait { 2445 ASTWriter &Writer; 2446 Preprocessor &PP; 2447 IdentifierResolver &IdResolver; 2448 bool IsModule; 2449 2450 /// \brief Determines whether this is an "interesting" identifier 2451 /// that needs a full IdentifierInfo structure written into the hash 2452 /// table. 2453 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) { 2454 if (II->isPoisoned() || 2455 II->isExtensionToken() || 2456 II->getObjCOrBuiltinID() || 2457 II->hasRevertedTokenIDToIdentifier() || 2458 II->getFETokenInfo<void>()) 2459 return true; 2460 2461 return hasMacroDefinition(II, Macro); 2462 } 2463 2464 bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) { 2465 if (!II->hasMacroDefinition()) 2466 return false; 2467 2468 if (Macro || (Macro = PP.getMacroInfo(II))) 2469 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic()); 2470 2471 return false; 2472 } 2473 2474public: 2475 typedef IdentifierInfo* key_type; 2476 typedef key_type key_type_ref; 2477 2478 typedef IdentID data_type; 2479 typedef data_type data_type_ref; 2480 2481 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 2482 IdentifierResolver &IdResolver, bool IsModule) 2483 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { } 2484 2485 static unsigned ComputeHash(const IdentifierInfo* II) { 2486 return llvm::HashString(II->getName()); 2487 } 2488 2489 std::pair<unsigned,unsigned> 2490 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 2491 unsigned KeyLen = II->getLength() + 1; 2492 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 2493 MacroInfo *Macro = 0; 2494 if (isInterestingIdentifier(II, Macro)) { 2495 DataLen += 2; // 2 bytes for builtin ID, flags 2496 if (hasMacroDefinition(II, Macro)) 2497 DataLen += 8; 2498 2499 for (IdentifierResolver::iterator D = IdResolver.begin(II), 2500 DEnd = IdResolver.end(); 2501 D != DEnd; ++D) 2502 DataLen += sizeof(DeclID); 2503 } 2504 clang::io::Emit16(Out, DataLen); 2505 // We emit the key length after the data length so that every 2506 // string is preceded by a 16-bit length. This matches the PTH 2507 // format for storing identifiers. 2508 clang::io::Emit16(Out, KeyLen); 2509 return std::make_pair(KeyLen, DataLen); 2510 } 2511 2512 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 2513 unsigned KeyLen) { 2514 // Record the location of the key data. This is used when generating 2515 // the mapping from persistent IDs to strings. 2516 Writer.SetIdentifierOffset(II, Out.tell()); 2517 Out.write(II->getNameStart(), KeyLen); 2518 } 2519 2520 void EmitData(raw_ostream& Out, IdentifierInfo* II, 2521 IdentID ID, unsigned) { 2522 MacroInfo *Macro = 0; 2523 if (!isInterestingIdentifier(II, Macro)) { 2524 clang::io::Emit32(Out, ID << 1); 2525 return; 2526 } 2527 2528 clang::io::Emit32(Out, (ID << 1) | 0x01); 2529 uint32_t Bits = 0; 2530 bool HasMacroDefinition = hasMacroDefinition(II, Macro); 2531 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2532 assert((Bits & 0x7ff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 2533 Bits = (Bits << 1) | unsigned(HasMacroDefinition); 2534 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2535 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2536 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2537 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2538 clang::io::Emit16(Out, Bits); 2539 2540 if (HasMacroDefinition) { 2541 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2542 clang::io::Emit32(Out, 2543 Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc())); 2544 } 2545 2546 // Emit the declaration IDs in reverse order, because the 2547 // IdentifierResolver provides the declarations as they would be 2548 // visible (e.g., the function "stat" would come before the struct 2549 // "stat"), but the ASTReader adds declarations to the end of the list 2550 // (so we need to see the struct "status" before the function "status"). 2551 // Only emit declarations that aren't from a chained PCH, though. 2552 SmallVector<Decl *, 16> Decls(IdResolver.begin(II), 2553 IdResolver.end()); 2554 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2555 DEnd = Decls.rend(); 2556 D != DEnd; ++D) 2557 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2558 } 2559}; 2560} // end anonymous namespace 2561 2562/// \brief Write the identifier table into the AST file. 2563/// 2564/// The identifier table consists of a blob containing string data 2565/// (the actual identifiers themselves) and a separate "offsets" index 2566/// that maps identifier IDs to locations within the blob. 2567void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 2568 IdentifierResolver &IdResolver, 2569 bool IsModule) { 2570 using namespace llvm; 2571 2572 // Create and write out the blob that contains the identifier 2573 // strings. 2574 { 2575 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2576 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2577 2578 // Look for any identifiers that were named while processing the 2579 // headers, but are otherwise not needed. We add these to the hash 2580 // table to enable checking of the predefines buffer in the case 2581 // where the user adds new macro definitions when building the AST 2582 // file. 2583 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2584 IDEnd = PP.getIdentifierTable().end(); 2585 ID != IDEnd; ++ID) 2586 getIdentifierRef(ID->second); 2587 2588 // Create the on-disk hash table representation. We only store offsets 2589 // for identifiers that appear here for the first time. 2590 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2591 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2592 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2593 ID != IDEnd; ++ID) { 2594 assert(ID->first && "NULL identifier in identifier table"); 2595 if (!Chain || !ID->first->isFromAST() || 2596 ID->first->hasChangedSinceDeserialization()) 2597 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 2598 Trait); 2599 } 2600 2601 // Create the on-disk hash table in a buffer. 2602 llvm::SmallString<4096> IdentifierTable; 2603 uint32_t BucketOffset; 2604 { 2605 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2606 llvm::raw_svector_ostream Out(IdentifierTable); 2607 // Make sure that no bucket is at offset 0 2608 clang::io::Emit32(Out, 0); 2609 BucketOffset = Generator.Emit(Out, Trait); 2610 } 2611 2612 // Create a blob abbreviation 2613 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2614 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2615 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2616 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2617 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2618 2619 // Write the identifier table 2620 RecordData Record; 2621 Record.push_back(IDENTIFIER_TABLE); 2622 Record.push_back(BucketOffset); 2623 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2624 } 2625 2626 // Write the offsets table for identifier IDs. 2627 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2628 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2629 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2630 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2631 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2632 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2633 2634 RecordData Record; 2635 Record.push_back(IDENTIFIER_OFFSET); 2636 Record.push_back(IdentifierOffsets.size()); 2637 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 2638 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2639 data(IdentifierOffsets)); 2640} 2641 2642//===----------------------------------------------------------------------===// 2643// DeclContext's Name Lookup Table Serialization 2644//===----------------------------------------------------------------------===// 2645 2646namespace { 2647// Trait used for the on-disk hash table used in the method pool. 2648class ASTDeclContextNameLookupTrait { 2649 ASTWriter &Writer; 2650 2651public: 2652 typedef DeclarationName key_type; 2653 typedef key_type key_type_ref; 2654 2655 typedef DeclContext::lookup_result data_type; 2656 typedef const data_type& data_type_ref; 2657 2658 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2659 2660 unsigned ComputeHash(DeclarationName Name) { 2661 llvm::FoldingSetNodeID ID; 2662 ID.AddInteger(Name.getNameKind()); 2663 2664 switch (Name.getNameKind()) { 2665 case DeclarationName::Identifier: 2666 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2667 break; 2668 case DeclarationName::ObjCZeroArgSelector: 2669 case DeclarationName::ObjCOneArgSelector: 2670 case DeclarationName::ObjCMultiArgSelector: 2671 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2672 break; 2673 case DeclarationName::CXXConstructorName: 2674 case DeclarationName::CXXDestructorName: 2675 case DeclarationName::CXXConversionFunctionName: 2676 break; 2677 case DeclarationName::CXXOperatorName: 2678 ID.AddInteger(Name.getCXXOverloadedOperator()); 2679 break; 2680 case DeclarationName::CXXLiteralOperatorName: 2681 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2682 case DeclarationName::CXXUsingDirective: 2683 break; 2684 } 2685 2686 return ID.ComputeHash(); 2687 } 2688 2689 std::pair<unsigned,unsigned> 2690 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 2691 data_type_ref Lookup) { 2692 unsigned KeyLen = 1; 2693 switch (Name.getNameKind()) { 2694 case DeclarationName::Identifier: 2695 case DeclarationName::ObjCZeroArgSelector: 2696 case DeclarationName::ObjCOneArgSelector: 2697 case DeclarationName::ObjCMultiArgSelector: 2698 case DeclarationName::CXXLiteralOperatorName: 2699 KeyLen += 4; 2700 break; 2701 case DeclarationName::CXXOperatorName: 2702 KeyLen += 1; 2703 break; 2704 case DeclarationName::CXXConstructorName: 2705 case DeclarationName::CXXDestructorName: 2706 case DeclarationName::CXXConversionFunctionName: 2707 case DeclarationName::CXXUsingDirective: 2708 break; 2709 } 2710 clang::io::Emit16(Out, KeyLen); 2711 2712 // 2 bytes for num of decls and 4 for each DeclID. 2713 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2714 clang::io::Emit16(Out, DataLen); 2715 2716 return std::make_pair(KeyLen, DataLen); 2717 } 2718 2719 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 2720 using namespace clang::io; 2721 2722 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2723 Emit8(Out, Name.getNameKind()); 2724 switch (Name.getNameKind()) { 2725 case DeclarationName::Identifier: 2726 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2727 break; 2728 case DeclarationName::ObjCZeroArgSelector: 2729 case DeclarationName::ObjCOneArgSelector: 2730 case DeclarationName::ObjCMultiArgSelector: 2731 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2732 break; 2733 case DeclarationName::CXXOperatorName: 2734 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2735 Emit8(Out, Name.getCXXOverloadedOperator()); 2736 break; 2737 case DeclarationName::CXXLiteralOperatorName: 2738 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2739 break; 2740 case DeclarationName::CXXConstructorName: 2741 case DeclarationName::CXXDestructorName: 2742 case DeclarationName::CXXConversionFunctionName: 2743 case DeclarationName::CXXUsingDirective: 2744 break; 2745 } 2746 } 2747 2748 void EmitData(raw_ostream& Out, key_type_ref, 2749 data_type Lookup, unsigned DataLen) { 2750 uint64_t Start = Out.tell(); (void)Start; 2751 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2752 for (; Lookup.first != Lookup.second; ++Lookup.first) 2753 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2754 2755 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2756 } 2757}; 2758} // end anonymous namespace 2759 2760/// \brief Write the block containing all of the declaration IDs 2761/// visible from the given DeclContext. 2762/// 2763/// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2764/// bitstream, or 0 if no block was written. 2765uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2766 DeclContext *DC) { 2767 if (DC->getPrimaryContext() != DC) 2768 return 0; 2769 2770 // Since there is no name lookup into functions or methods, don't bother to 2771 // build a visible-declarations table for these entities. 2772 if (DC->isFunctionOrMethod()) 2773 return 0; 2774 2775 // If not in C++, we perform name lookup for the translation unit via the 2776 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2777 // FIXME: In C++ we need the visible declarations in order to "see" the 2778 // friend declarations, is there a way to do this without writing the table ? 2779 if (DC->isTranslationUnit() && !Context.getLangOptions().CPlusPlus) 2780 return 0; 2781 2782 // Force the DeclContext to build a its name-lookup table. 2783 if (!DC->hasExternalVisibleStorage()) 2784 DC->lookup(DeclarationName()); 2785 2786 // Serialize the contents of the mapping used for lookup. Note that, 2787 // although we have two very different code paths, the serialized 2788 // representation is the same for both cases: a declaration name, 2789 // followed by a size, followed by references to the visible 2790 // declarations that have that name. 2791 uint64_t Offset = Stream.GetCurrentBitNo(); 2792 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2793 if (!Map || Map->empty()) 2794 return 0; 2795 2796 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2797 ASTDeclContextNameLookupTrait Trait(*this); 2798 2799 // Create the on-disk hash table representation. 2800 DeclarationName ConversionName; 2801 llvm::SmallVector<NamedDecl *, 4> ConversionDecls; 2802 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2803 D != DEnd; ++D) { 2804 DeclarationName Name = D->first; 2805 DeclContext::lookup_result Result = D->second.getLookupResult(); 2806 if (Result.first != Result.second) { 2807 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2808 // Hash all conversion function names to the same name. The actual 2809 // type information in conversion function name is not used in the 2810 // key (since such type information is not stable across different 2811 // modules), so the intended effect is to coalesce all of the conversion 2812 // functions under a single key. 2813 if (!ConversionName) 2814 ConversionName = Name; 2815 ConversionDecls.append(Result.first, Result.second); 2816 continue; 2817 } 2818 2819 Generator.insert(Name, Result, Trait); 2820 } 2821 } 2822 2823 // Add the conversion functions 2824 if (!ConversionDecls.empty()) { 2825 Generator.insert(ConversionName, 2826 DeclContext::lookup_result(ConversionDecls.begin(), 2827 ConversionDecls.end()), 2828 Trait); 2829 } 2830 2831 // Create the on-disk hash table in a buffer. 2832 llvm::SmallString<4096> LookupTable; 2833 uint32_t BucketOffset; 2834 { 2835 llvm::raw_svector_ostream Out(LookupTable); 2836 // Make sure that no bucket is at offset 0 2837 clang::io::Emit32(Out, 0); 2838 BucketOffset = Generator.Emit(Out, Trait); 2839 } 2840 2841 // Write the lookup table 2842 RecordData Record; 2843 Record.push_back(DECL_CONTEXT_VISIBLE); 2844 Record.push_back(BucketOffset); 2845 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2846 LookupTable.str()); 2847 2848 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2849 ++NumVisibleDeclContexts; 2850 return Offset; 2851} 2852 2853/// \brief Write an UPDATE_VISIBLE block for the given context. 2854/// 2855/// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2856/// DeclContext in a dependent AST file. As such, they only exist for the TU 2857/// (in C++) and for namespaces. 2858void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2859 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2860 if (!Map || Map->empty()) 2861 return; 2862 2863 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2864 ASTDeclContextNameLookupTrait Trait(*this); 2865 2866 // Create the hash table. 2867 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2868 D != DEnd; ++D) { 2869 DeclarationName Name = D->first; 2870 DeclContext::lookup_result Result = D->second.getLookupResult(); 2871 // For any name that appears in this table, the results are complete, i.e. 2872 // they overwrite results from previous PCHs. Merging is always a mess. 2873 if (Result.first != Result.second) 2874 Generator.insert(Name, Result, Trait); 2875 } 2876 2877 // Create the on-disk hash table in a buffer. 2878 llvm::SmallString<4096> LookupTable; 2879 uint32_t BucketOffset; 2880 { 2881 llvm::raw_svector_ostream Out(LookupTable); 2882 // Make sure that no bucket is at offset 0 2883 clang::io::Emit32(Out, 0); 2884 BucketOffset = Generator.Emit(Out, Trait); 2885 } 2886 2887 // Write the lookup table 2888 RecordData Record; 2889 Record.push_back(UPDATE_VISIBLE); 2890 Record.push_back(getDeclID(cast<Decl>(DC))); 2891 Record.push_back(BucketOffset); 2892 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2893} 2894 2895/// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 2896void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 2897 RecordData Record; 2898 Record.push_back(Opts.fp_contract); 2899 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 2900} 2901 2902/// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 2903void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 2904 if (!SemaRef.Context.getLangOptions().OpenCL) 2905 return; 2906 2907 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 2908 RecordData Record; 2909#define OPENCLEXT(nm) Record.push_back(Opts.nm); 2910#include "clang/Basic/OpenCLExtensions.def" 2911 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 2912} 2913 2914void ASTWriter::WriteRedeclarations() { 2915 RecordData LocalRedeclChains; 2916 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap; 2917 2918 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) { 2919 Decl *First = Redeclarations[I]; 2920 assert(First->getPreviousDecl() == 0 && "Not the first declaration?"); 2921 2922 Decl *MostRecent = First->getMostRecentDecl(); 2923 2924 // If we only have a single declaration, there is no point in storing 2925 // a redeclaration chain. 2926 if (First == MostRecent) 2927 continue; 2928 2929 unsigned Offset = LocalRedeclChains.size(); 2930 unsigned Size = 0; 2931 LocalRedeclChains.push_back(0); // Placeholder for the size. 2932 2933 // Collect the set of local redeclarations of this declaration. 2934 for (Decl *Prev = MostRecent; Prev != First; 2935 Prev = Prev->getPreviousDecl()) { 2936 if (!Prev->isFromASTFile()) { 2937 AddDeclRef(Prev, LocalRedeclChains); 2938 ++Size; 2939 } 2940 } 2941 LocalRedeclChains[Offset] = Size; 2942 2943 // Reverse the set of local redeclarations, so that we store them in 2944 // order (since we found them in reverse order). 2945 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end()); 2946 2947 // Add the mapping from the first ID to the set of local declarations. 2948 LocalRedeclarationsInfo Info = { getDeclID(First), Offset }; 2949 LocalRedeclsMap.push_back(Info); 2950 2951 assert(N == Redeclarations.size() && 2952 "Deserialized a declaration we shouldn't have"); 2953 } 2954 2955 if (LocalRedeclChains.empty()) 2956 return; 2957 2958 // Sort the local redeclarations map by the first declaration ID, 2959 // since the reader will be performing binary searches on this information. 2960 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end()); 2961 2962 // Emit the local redeclarations map. 2963 using namespace llvm; 2964 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2965 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP)); 2966 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 2967 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2968 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 2969 2970 RecordData Record; 2971 Record.push_back(LOCAL_REDECLARATIONS_MAP); 2972 Record.push_back(LocalRedeclsMap.size()); 2973 Stream.EmitRecordWithBlob(AbbrevID, Record, 2974 reinterpret_cast<char*>(LocalRedeclsMap.data()), 2975 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo)); 2976 2977 // Emit the redeclaration chains. 2978 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains); 2979} 2980 2981void ASTWriter::WriteObjCCategories() { 2982 llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 2983 RecordData Categories; 2984 2985 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 2986 unsigned Size = 0; 2987 unsigned StartIndex = Categories.size(); 2988 2989 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 2990 2991 // Allocate space for the size. 2992 Categories.push_back(0); 2993 2994 // Add the categories. 2995 for (ObjCCategoryDecl *Cat = Class->getCategoryList(); 2996 Cat; Cat = Cat->getNextClassCategory(), ++Size) { 2997 assert(getDeclID(Cat) != 0 && "Bogus category"); 2998 AddDeclRef(Cat, Categories); 2999 } 3000 3001 // Update the size. 3002 Categories[StartIndex] = Size; 3003 3004 // Record this interface -> category map. 3005 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 3006 CategoriesMap.push_back(CatInfo); 3007 } 3008 3009 // Sort the categories map by the definition ID, since the reader will be 3010 // performing binary searches on this information. 3011 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 3012 3013 // Emit the categories map. 3014 using namespace llvm; 3015 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3016 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 3017 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 3018 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3019 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 3020 3021 RecordData Record; 3022 Record.push_back(OBJC_CATEGORIES_MAP); 3023 Record.push_back(CategoriesMap.size()); 3024 Stream.EmitRecordWithBlob(AbbrevID, Record, 3025 reinterpret_cast<char*>(CategoriesMap.data()), 3026 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 3027 3028 // Emit the category lists. 3029 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 3030} 3031 3032void ASTWriter::WriteMergedDecls() { 3033 if (!Chain || Chain->MergedDecls.empty()) 3034 return; 3035 3036 RecordData Record; 3037 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(), 3038 IEnd = Chain->MergedDecls.end(); 3039 I != IEnd; ++I) { 3040 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID() 3041 : getDeclID(I->first); 3042 assert(CanonID && "Merged declaration not known?"); 3043 3044 Record.push_back(CanonID); 3045 Record.push_back(I->second.size()); 3046 Record.append(I->second.begin(), I->second.end()); 3047 } 3048 Stream.EmitRecord(MERGED_DECLARATIONS, Record); 3049} 3050 3051//===----------------------------------------------------------------------===// 3052// General Serialization Routines 3053//===----------------------------------------------------------------------===// 3054 3055/// \brief Write a record containing the given attributes. 3056void ASTWriter::WriteAttributes(const AttrVec &Attrs, RecordDataImpl &Record) { 3057 Record.push_back(Attrs.size()); 3058 for (AttrVec::const_iterator i = Attrs.begin(), e = Attrs.end(); i != e; ++i){ 3059 const Attr * A = *i; 3060 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 3061 AddSourceRange(A->getRange(), Record); 3062 3063#include "clang/Serialization/AttrPCHWrite.inc" 3064 3065 } 3066} 3067 3068void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 3069 Record.push_back(Str.size()); 3070 Record.insert(Record.end(), Str.begin(), Str.end()); 3071} 3072 3073void ASTWriter::AddVersionTuple(const VersionTuple &Version, 3074 RecordDataImpl &Record) { 3075 Record.push_back(Version.getMajor()); 3076 if (llvm::Optional<unsigned> Minor = Version.getMinor()) 3077 Record.push_back(*Minor + 1); 3078 else 3079 Record.push_back(0); 3080 if (llvm::Optional<unsigned> Subminor = Version.getSubminor()) 3081 Record.push_back(*Subminor + 1); 3082 else 3083 Record.push_back(0); 3084} 3085 3086/// \brief Note that the identifier II occurs at the given offset 3087/// within the identifier table. 3088void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 3089 IdentID ID = IdentifierIDs[II]; 3090 // Only store offsets new to this AST file. Other identifier names are looked 3091 // up earlier in the chain and thus don't need an offset. 3092 if (ID >= FirstIdentID) 3093 IdentifierOffsets[ID - FirstIdentID] = Offset; 3094} 3095 3096/// \brief Note that the selector Sel occurs at the given offset 3097/// within the method pool/selector table. 3098void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 3099 unsigned ID = SelectorIDs[Sel]; 3100 assert(ID && "Unknown selector"); 3101 // Don't record offsets for selectors that are also available in a different 3102 // file. 3103 if (ID < FirstSelectorID) 3104 return; 3105 SelectorOffsets[ID - FirstSelectorID] = Offset; 3106} 3107 3108ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 3109 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0), 3110 WritingAST(false), 3111 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 3112 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 3113 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 3114 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS), 3115 NextSubmoduleID(FirstSubmoduleID), 3116 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 3117 CollectedStmts(&StmtsToEmit), 3118 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 3119 NumVisibleDeclContexts(0), 3120 NextCXXBaseSpecifiersID(1), 3121 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0), 3122 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0), 3123 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0), 3124 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0), 3125 DeclTypedefAbbrev(0), 3126 DeclVarAbbrev(0), DeclFieldAbbrev(0), 3127 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0) 3128{ 3129} 3130 3131ASTWriter::~ASTWriter() { 3132 for (FileDeclIDsTy::iterator 3133 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I) 3134 delete I->second; 3135} 3136 3137void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 3138 const std::string &OutputFile, 3139 Module *WritingModule, StringRef isysroot) { 3140 WritingAST = true; 3141 3142 // Emit the file header. 3143 Stream.Emit((unsigned)'C', 8); 3144 Stream.Emit((unsigned)'P', 8); 3145 Stream.Emit((unsigned)'C', 8); 3146 Stream.Emit((unsigned)'H', 8); 3147 3148 WriteBlockInfoBlock(); 3149 3150 Context = &SemaRef.Context; 3151 PP = &SemaRef.PP; 3152 this->WritingModule = WritingModule; 3153 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule); 3154 Context = 0; 3155 PP = 0; 3156 this->WritingModule = 0; 3157 3158 WritingAST = false; 3159} 3160 3161template<typename Vector> 3162static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 3163 ASTWriter::RecordData &Record) { 3164 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end(); 3165 I != E; ++I) { 3166 Writer.AddDeclRef(*I, Record); 3167 } 3168} 3169 3170void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 3171 StringRef isysroot, 3172 const std::string &OutputFile, 3173 Module *WritingModule) { 3174 using namespace llvm; 3175 3176 // Make sure that the AST reader knows to finalize itself. 3177 if (Chain) 3178 Chain->finalizeForWriting(); 3179 3180 ASTContext &Context = SemaRef.Context; 3181 Preprocessor &PP = SemaRef.PP; 3182 3183 // Set up predefined declaration IDs. 3184 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 3185 if (Context.ObjCIdDecl) 3186 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 3187 if (Context.ObjCSelDecl) 3188 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID; 3189 if (Context.ObjCClassDecl) 3190 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID; 3191 if (Context.ObjCProtocolClassDecl) 3192 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID; 3193 if (Context.Int128Decl) 3194 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID; 3195 if (Context.UInt128Decl) 3196 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID; 3197 if (Context.ObjCInstanceTypeDecl) 3198 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID; 3199 3200 if (!Chain) { 3201 // Make sure that we emit IdentifierInfos (and any attached 3202 // declarations) for builtins. We don't need to do this when we're 3203 // emitting chained PCH files, because all of the builtins will be 3204 // in the original PCH file. 3205 // FIXME: Modules won't like this at all. 3206 IdentifierTable &Table = PP.getIdentifierTable(); 3207 SmallVector<const char *, 32> BuiltinNames; 3208 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 3209 Context.getLangOptions().NoBuiltin); 3210 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 3211 getIdentifierRef(&Table.get(BuiltinNames[I])); 3212 } 3213 3214 // If there are any out-of-date identifiers, bring them up to date. 3215 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) { 3216 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 3217 IDEnd = PP.getIdentifierTable().end(); 3218 ID != IDEnd; ++ID) 3219 if (ID->second->isOutOfDate()) 3220 ExtSource->updateOutOfDateIdentifier(*ID->second); 3221 } 3222 3223 // Build a record containing all of the tentative definitions in this file, in 3224 // TentativeDefinitions order. Generally, this record will be empty for 3225 // headers. 3226 RecordData TentativeDefinitions; 3227 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 3228 3229 // Build a record containing all of the file scoped decls in this file. 3230 RecordData UnusedFileScopedDecls; 3231 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 3232 UnusedFileScopedDecls); 3233 3234 // Build a record containing all of the delegating constructors we still need 3235 // to resolve. 3236 RecordData DelegatingCtorDecls; 3237 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 3238 3239 // Write the set of weak, undeclared identifiers. We always write the 3240 // entire table, since later PCH files in a PCH chain are only interested in 3241 // the results at the end of the chain. 3242 RecordData WeakUndeclaredIdentifiers; 3243 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 3244 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 3245 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 3246 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 3247 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 3248 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 3249 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 3250 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 3251 } 3252 } 3253 3254 // Build a record containing all of the locally-scoped external 3255 // declarations in this header file. Generally, this record will be 3256 // empty. 3257 RecordData LocallyScopedExternalDecls; 3258 // FIXME: This is filling in the AST file in densemap order which is 3259 // nondeterminstic! 3260 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3261 TD = SemaRef.LocallyScopedExternalDecls.begin(), 3262 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 3263 TD != TDEnd; ++TD) { 3264 if (!TD->second->isFromASTFile()) 3265 AddDeclRef(TD->second, LocallyScopedExternalDecls); 3266 } 3267 3268 // Build a record containing all of the ext_vector declarations. 3269 RecordData ExtVectorDecls; 3270 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 3271 3272 // Build a record containing all of the VTable uses information. 3273 RecordData VTableUses; 3274 if (!SemaRef.VTableUses.empty()) { 3275 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 3276 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 3277 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 3278 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 3279 } 3280 } 3281 3282 // Build a record containing all of dynamic classes declarations. 3283 RecordData DynamicClasses; 3284 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 3285 3286 // Build a record containing all of pending implicit instantiations. 3287 RecordData PendingInstantiations; 3288 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 3289 I = SemaRef.PendingInstantiations.begin(), 3290 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 3291 AddDeclRef(I->first, PendingInstantiations); 3292 AddSourceLocation(I->second, PendingInstantiations); 3293 } 3294 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 3295 "There are local ones at end of translation unit!"); 3296 3297 // Build a record containing some declaration references. 3298 RecordData SemaDeclRefs; 3299 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 3300 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 3301 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 3302 } 3303 3304 RecordData CUDASpecialDeclRefs; 3305 if (Context.getcudaConfigureCallDecl()) { 3306 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 3307 } 3308 3309 // Build a record containing all of the known namespaces. 3310 RecordData KnownNamespaces; 3311 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 3312 I = SemaRef.KnownNamespaces.begin(), 3313 IEnd = SemaRef.KnownNamespaces.end(); 3314 I != IEnd; ++I) { 3315 if (!I->second) 3316 AddDeclRef(I->first, KnownNamespaces); 3317 } 3318 3319 // Write the remaining AST contents. 3320 RecordData Record; 3321 Stream.EnterSubblock(AST_BLOCK_ID, 5); 3322 WriteMetadata(Context, isysroot, OutputFile); 3323 WriteLanguageOptions(Context.getLangOptions()); 3324 if (StatCalls && isysroot.empty()) 3325 WriteStatCache(*StatCalls); 3326 3327 // Create a lexical update block containing all of the declarations in the 3328 // translation unit that do not come from other AST files. 3329 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 3330 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 3331 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 3332 E = TU->noload_decls_end(); 3333 I != E; ++I) { 3334 if (!(*I)->isFromASTFile()) 3335 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 3336 } 3337 3338 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 3339 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 3340 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3341 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 3342 Record.clear(); 3343 Record.push_back(TU_UPDATE_LEXICAL); 3344 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 3345 data(NewGlobalDecls)); 3346 3347 // And a visible updates block for the translation unit. 3348 Abv = new llvm::BitCodeAbbrev(); 3349 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 3350 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 3351 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 3352 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3353 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 3354 WriteDeclContextVisibleUpdate(TU); 3355 3356 // If the translation unit has an anonymous namespace, and we don't already 3357 // have an update block for it, write it as an update block. 3358 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 3359 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 3360 if (Record.empty()) { 3361 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE); 3362 Record.push_back(reinterpret_cast<uint64_t>(NS)); 3363 } 3364 } 3365 3366 // Resolve any declaration pointers within the declaration updates block. 3367 ResolveDeclUpdatesBlocks(); 3368 3369 // Form the record of special types. 3370 RecordData SpecialTypes; 3371 AddTypeRef(Context.getBuiltinVaListType(), SpecialTypes); 3372 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 3373 AddTypeRef(Context.getFILEType(), SpecialTypes); 3374 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 3375 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 3376 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 3377 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 3378 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 3379 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 3380 3381 // Keep writing types and declarations until all types and 3382 // declarations have been written. 3383 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3384 WriteDeclsBlockAbbrevs(); 3385 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 3386 E = DeclsToRewrite.end(); 3387 I != E; ++I) 3388 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 3389 while (!DeclTypesToEmit.empty()) { 3390 DeclOrType DOT = DeclTypesToEmit.front(); 3391 DeclTypesToEmit.pop(); 3392 if (DOT.isType()) 3393 WriteType(DOT.getType()); 3394 else 3395 WriteDecl(Context, DOT.getDecl()); 3396 } 3397 Stream.ExitBlock(); 3398 3399 WriteFileDeclIDsMap(); 3400 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 3401 3402 if (Chain) { 3403 // Write the mapping information describing our module dependencies and how 3404 // each of those modules were mapped into our own offset/ID space, so that 3405 // the reader can build the appropriate mapping to its own offset/ID space. 3406 // The map consists solely of a blob with the following format: 3407 // *(module-name-len:i16 module-name:len*i8 3408 // source-location-offset:i32 3409 // identifier-id:i32 3410 // preprocessed-entity-id:i32 3411 // macro-definition-id:i32 3412 // submodule-id:i32 3413 // selector-id:i32 3414 // declaration-id:i32 3415 // c++-base-specifiers-id:i32 3416 // type-id:i32) 3417 // 3418 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3419 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 3420 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3421 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 3422 llvm::SmallString<2048> Buffer; 3423 { 3424 llvm::raw_svector_ostream Out(Buffer); 3425 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(), 3426 MEnd = Chain->ModuleMgr.end(); 3427 M != MEnd; ++M) { 3428 StringRef FileName = (*M)->FileName; 3429 io::Emit16(Out, FileName.size()); 3430 Out.write(FileName.data(), FileName.size()); 3431 io::Emit32(Out, (*M)->SLocEntryBaseOffset); 3432 io::Emit32(Out, (*M)->BaseIdentifierID); 3433 io::Emit32(Out, (*M)->BasePreprocessedEntityID); 3434 io::Emit32(Out, (*M)->BaseSubmoduleID); 3435 io::Emit32(Out, (*M)->BaseSelectorID); 3436 io::Emit32(Out, (*M)->BaseDeclID); 3437 io::Emit32(Out, (*M)->BaseTypeIndex); 3438 } 3439 } 3440 Record.clear(); 3441 Record.push_back(MODULE_OFFSET_MAP); 3442 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 3443 Buffer.data(), Buffer.size()); 3444 } 3445 WritePreprocessor(PP, WritingModule != 0); 3446 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 3447 WriteSelectors(SemaRef); 3448 WriteReferencedSelectorsPool(SemaRef); 3449 WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0); 3450 WriteFPPragmaOptions(SemaRef.getFPOptions()); 3451 WriteOpenCLExtensions(SemaRef); 3452 3453 WriteTypeDeclOffsets(); 3454 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 3455 3456 WriteCXXBaseSpecifiersOffsets(); 3457 3458 // If we're emitting a module, write out the submodule information. 3459 if (WritingModule) 3460 WriteSubmodules(WritingModule); 3461 3462 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 3463 3464 // Write the record containing external, unnamed definitions. 3465 if (!ExternalDefinitions.empty()) 3466 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 3467 3468 // Write the record containing tentative definitions. 3469 if (!TentativeDefinitions.empty()) 3470 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 3471 3472 // Write the record containing unused file scoped decls. 3473 if (!UnusedFileScopedDecls.empty()) 3474 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 3475 3476 // Write the record containing weak undeclared identifiers. 3477 if (!WeakUndeclaredIdentifiers.empty()) 3478 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 3479 WeakUndeclaredIdentifiers); 3480 3481 // Write the record containing locally-scoped external definitions. 3482 if (!LocallyScopedExternalDecls.empty()) 3483 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 3484 LocallyScopedExternalDecls); 3485 3486 // Write the record containing ext_vector type names. 3487 if (!ExtVectorDecls.empty()) 3488 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 3489 3490 // Write the record containing VTable uses information. 3491 if (!VTableUses.empty()) 3492 Stream.EmitRecord(VTABLE_USES, VTableUses); 3493 3494 // Write the record containing dynamic classes declarations. 3495 if (!DynamicClasses.empty()) 3496 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 3497 3498 // Write the record containing pending implicit instantiations. 3499 if (!PendingInstantiations.empty()) 3500 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 3501 3502 // Write the record containing declaration references of Sema. 3503 if (!SemaDeclRefs.empty()) 3504 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 3505 3506 // Write the record containing CUDA-specific declaration references. 3507 if (!CUDASpecialDeclRefs.empty()) 3508 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 3509 3510 // Write the delegating constructors. 3511 if (!DelegatingCtorDecls.empty()) 3512 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 3513 3514 // Write the known namespaces. 3515 if (!KnownNamespaces.empty()) 3516 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 3517 3518 // Write the visible updates to DeclContexts. 3519 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 3520 I = UpdatedDeclContexts.begin(), 3521 E = UpdatedDeclContexts.end(); 3522 I != E; ++I) 3523 WriteDeclContextVisibleUpdate(*I); 3524 3525 if (!WritingModule) { 3526 // Write the submodules that were imported, if any. 3527 RecordData ImportedModules; 3528 for (ASTContext::import_iterator I = Context.local_import_begin(), 3529 IEnd = Context.local_import_end(); 3530 I != IEnd; ++I) { 3531 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 3532 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]); 3533 } 3534 if (!ImportedModules.empty()) { 3535 // Sort module IDs. 3536 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end()); 3537 3538 // Unique module IDs. 3539 ImportedModules.erase(std::unique(ImportedModules.begin(), 3540 ImportedModules.end()), 3541 ImportedModules.end()); 3542 3543 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 3544 } 3545 } 3546 3547 WriteDeclUpdatesBlocks(); 3548 WriteDeclReplacementsBlock(); 3549 WriteMergedDecls(); 3550 WriteRedeclarations(); 3551 WriteObjCCategories(); 3552 3553 // Some simple statistics 3554 Record.clear(); 3555 Record.push_back(NumStatements); 3556 Record.push_back(NumMacros); 3557 Record.push_back(NumLexicalDeclContexts); 3558 Record.push_back(NumVisibleDeclContexts); 3559 Stream.EmitRecord(STATISTICS, Record); 3560 Stream.ExitBlock(); 3561} 3562 3563/// \brief Go through the declaration update blocks and resolve declaration 3564/// pointers into declaration IDs. 3565void ASTWriter::ResolveDeclUpdatesBlocks() { 3566 for (DeclUpdateMap::iterator 3567 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3568 const Decl *D = I->first; 3569 UpdateRecord &URec = I->second; 3570 3571 if (isRewritten(D)) 3572 continue; // The decl will be written completely 3573 3574 unsigned Idx = 0, N = URec.size(); 3575 while (Idx < N) { 3576 switch ((DeclUpdateKind)URec[Idx++]) { 3577 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 3578 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3579 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 3580 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx])); 3581 ++Idx; 3582 break; 3583 3584 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3585 ++Idx; 3586 break; 3587 } 3588 } 3589 } 3590} 3591 3592void ASTWriter::WriteDeclUpdatesBlocks() { 3593 if (DeclUpdates.empty()) 3594 return; 3595 3596 RecordData OffsetsRecord; 3597 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3598 for (DeclUpdateMap::iterator 3599 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3600 const Decl *D = I->first; 3601 UpdateRecord &URec = I->second; 3602 3603 if (isRewritten(D)) 3604 continue; // The decl will be written completely,no need to store updates. 3605 3606 uint64_t Offset = Stream.GetCurrentBitNo(); 3607 Stream.EmitRecord(DECL_UPDATES, URec); 3608 3609 OffsetsRecord.push_back(GetDeclRef(D)); 3610 OffsetsRecord.push_back(Offset); 3611 } 3612 Stream.ExitBlock(); 3613 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 3614} 3615 3616void ASTWriter::WriteDeclReplacementsBlock() { 3617 if (ReplacedDecls.empty()) 3618 return; 3619 3620 RecordData Record; 3621 for (SmallVector<ReplacedDeclInfo, 16>::iterator 3622 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 3623 Record.push_back(I->ID); 3624 Record.push_back(I->Offset); 3625 Record.push_back(I->Loc); 3626 } 3627 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 3628} 3629 3630void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 3631 Record.push_back(Loc.getRawEncoding()); 3632} 3633 3634void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 3635 AddSourceLocation(Range.getBegin(), Record); 3636 AddSourceLocation(Range.getEnd(), Record); 3637} 3638 3639void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 3640 Record.push_back(Value.getBitWidth()); 3641 const uint64_t *Words = Value.getRawData(); 3642 Record.append(Words, Words + Value.getNumWords()); 3643} 3644 3645void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 3646 Record.push_back(Value.isUnsigned()); 3647 AddAPInt(Value, Record); 3648} 3649 3650void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 3651 AddAPInt(Value.bitcastToAPInt(), Record); 3652} 3653 3654void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 3655 Record.push_back(getIdentifierRef(II)); 3656} 3657 3658IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 3659 if (II == 0) 3660 return 0; 3661 3662 IdentID &ID = IdentifierIDs[II]; 3663 if (ID == 0) 3664 ID = NextIdentID++; 3665 return ID; 3666} 3667 3668void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3669 Record.push_back(getSelectorRef(SelRef)); 3670} 3671 3672SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3673 if (Sel.getAsOpaquePtr() == 0) { 3674 return 0; 3675 } 3676 3677 SelectorID &SID = SelectorIDs[Sel]; 3678 if (SID == 0 && Chain) { 3679 // This might trigger a ReadSelector callback, which will set the ID for 3680 // this selector. 3681 Chain->LoadSelector(Sel); 3682 } 3683 if (SID == 0) { 3684 SID = NextSelectorID++; 3685 } 3686 return SID; 3687} 3688 3689void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3690 AddDeclRef(Temp->getDestructor(), Record); 3691} 3692 3693void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3694 CXXBaseSpecifier const *BasesEnd, 3695 RecordDataImpl &Record) { 3696 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3697 CXXBaseSpecifiersToWrite.push_back( 3698 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3699 Bases, BasesEnd)); 3700 Record.push_back(NextCXXBaseSpecifiersID++); 3701} 3702 3703void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3704 const TemplateArgumentLocInfo &Arg, 3705 RecordDataImpl &Record) { 3706 switch (Kind) { 3707 case TemplateArgument::Expression: 3708 AddStmt(Arg.getAsExpr()); 3709 break; 3710 case TemplateArgument::Type: 3711 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3712 break; 3713 case TemplateArgument::Template: 3714 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3715 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3716 break; 3717 case TemplateArgument::TemplateExpansion: 3718 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3719 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3720 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3721 break; 3722 case TemplateArgument::Null: 3723 case TemplateArgument::Integral: 3724 case TemplateArgument::Declaration: 3725 case TemplateArgument::Pack: 3726 break; 3727 } 3728} 3729 3730void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3731 RecordDataImpl &Record) { 3732 AddTemplateArgument(Arg.getArgument(), Record); 3733 3734 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3735 bool InfoHasSameExpr 3736 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3737 Record.push_back(InfoHasSameExpr); 3738 if (InfoHasSameExpr) 3739 return; // Avoid storing the same expr twice. 3740 } 3741 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3742 Record); 3743} 3744 3745void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 3746 RecordDataImpl &Record) { 3747 if (TInfo == 0) { 3748 AddTypeRef(QualType(), Record); 3749 return; 3750 } 3751 3752 AddTypeLoc(TInfo->getTypeLoc(), Record); 3753} 3754 3755void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 3756 AddTypeRef(TL.getType(), Record); 3757 3758 TypeLocWriter TLW(*this, Record); 3759 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 3760 TLW.Visit(TL); 3761} 3762 3763void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3764 Record.push_back(GetOrCreateTypeID(T)); 3765} 3766 3767TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 3768 return MakeTypeID(*Context, T, 3769 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3770} 3771 3772TypeID ASTWriter::getTypeID(QualType T) const { 3773 return MakeTypeID(*Context, T, 3774 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3775} 3776 3777TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3778 if (T.isNull()) 3779 return TypeIdx(); 3780 assert(!T.getLocalFastQualifiers()); 3781 3782 TypeIdx &Idx = TypeIdxs[T]; 3783 if (Idx.getIndex() == 0) { 3784 // We haven't seen this type before. Assign it a new ID and put it 3785 // into the queue of types to emit. 3786 Idx = TypeIdx(NextTypeID++); 3787 DeclTypesToEmit.push(T); 3788 } 3789 return Idx; 3790} 3791 3792TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3793 if (T.isNull()) 3794 return TypeIdx(); 3795 assert(!T.getLocalFastQualifiers()); 3796 3797 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3798 assert(I != TypeIdxs.end() && "Type not emitted!"); 3799 return I->second; 3800} 3801 3802void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3803 Record.push_back(GetDeclRef(D)); 3804} 3805 3806DeclID ASTWriter::GetDeclRef(const Decl *D) { 3807 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 3808 3809 if (D == 0) { 3810 return 0; 3811 } 3812 3813 // If D comes from an AST file, its declaration ID is already known and 3814 // fixed. 3815 if (D->isFromASTFile()) 3816 return D->getGlobalID(); 3817 3818 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3819 DeclID &ID = DeclIDs[D]; 3820 if (ID == 0) { 3821 // We haven't seen this declaration before. Give it a new ID and 3822 // enqueue it in the list of declarations to emit. 3823 ID = NextDeclID++; 3824 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3825 } 3826 3827 return ID; 3828} 3829 3830DeclID ASTWriter::getDeclID(const Decl *D) { 3831 if (D == 0) 3832 return 0; 3833 3834 // If D comes from an AST file, its declaration ID is already known and 3835 // fixed. 3836 if (D->isFromASTFile()) 3837 return D->getGlobalID(); 3838 3839 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3840 return DeclIDs[D]; 3841} 3842 3843static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L, 3844 std::pair<unsigned, serialization::DeclID> R) { 3845 return L.first < R.first; 3846} 3847 3848void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 3849 assert(ID); 3850 assert(D); 3851 3852 SourceLocation Loc = D->getLocation(); 3853 if (Loc.isInvalid()) 3854 return; 3855 3856 // We only keep track of the file-level declarations of each file. 3857 if (!D->getLexicalDeclContext()->isFileContext()) 3858 return; 3859 3860 SourceManager &SM = Context->getSourceManager(); 3861 SourceLocation FileLoc = SM.getFileLoc(Loc); 3862 assert(SM.isLocalSourceLocation(FileLoc)); 3863 FileID FID; 3864 unsigned Offset; 3865 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 3866 if (FID.isInvalid()) 3867 return; 3868 const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID); 3869 assert(Entry->isFile()); 3870 3871 DeclIDInFileInfo *&Info = FileDeclIDs[Entry]; 3872 if (!Info) 3873 Info = new DeclIDInFileInfo(); 3874 3875 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 3876 LocDeclIDsTy &Decls = Info->DeclIDs; 3877 3878 if (Decls.empty() || Decls.back().first <= Offset) { 3879 Decls.push_back(LocDecl); 3880 return; 3881 } 3882 3883 LocDeclIDsTy::iterator 3884 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl); 3885 3886 Decls.insert(I, LocDecl); 3887} 3888 3889void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3890 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3891 Record.push_back(Name.getNameKind()); 3892 switch (Name.getNameKind()) { 3893 case DeclarationName::Identifier: 3894 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3895 break; 3896 3897 case DeclarationName::ObjCZeroArgSelector: 3898 case DeclarationName::ObjCOneArgSelector: 3899 case DeclarationName::ObjCMultiArgSelector: 3900 AddSelectorRef(Name.getObjCSelector(), Record); 3901 break; 3902 3903 case DeclarationName::CXXConstructorName: 3904 case DeclarationName::CXXDestructorName: 3905 case DeclarationName::CXXConversionFunctionName: 3906 AddTypeRef(Name.getCXXNameType(), Record); 3907 break; 3908 3909 case DeclarationName::CXXOperatorName: 3910 Record.push_back(Name.getCXXOverloadedOperator()); 3911 break; 3912 3913 case DeclarationName::CXXLiteralOperatorName: 3914 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3915 break; 3916 3917 case DeclarationName::CXXUsingDirective: 3918 // No extra data to emit 3919 break; 3920 } 3921} 3922 3923void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3924 DeclarationName Name, RecordDataImpl &Record) { 3925 switch (Name.getNameKind()) { 3926 case DeclarationName::CXXConstructorName: 3927 case DeclarationName::CXXDestructorName: 3928 case DeclarationName::CXXConversionFunctionName: 3929 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3930 break; 3931 3932 case DeclarationName::CXXOperatorName: 3933 AddSourceLocation( 3934 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 3935 Record); 3936 AddSourceLocation( 3937 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 3938 Record); 3939 break; 3940 3941 case DeclarationName::CXXLiteralOperatorName: 3942 AddSourceLocation( 3943 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 3944 Record); 3945 break; 3946 3947 case DeclarationName::Identifier: 3948 case DeclarationName::ObjCZeroArgSelector: 3949 case DeclarationName::ObjCOneArgSelector: 3950 case DeclarationName::ObjCMultiArgSelector: 3951 case DeclarationName::CXXUsingDirective: 3952 break; 3953 } 3954} 3955 3956void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 3957 RecordDataImpl &Record) { 3958 AddDeclarationName(NameInfo.getName(), Record); 3959 AddSourceLocation(NameInfo.getLoc(), Record); 3960 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 3961} 3962 3963void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 3964 RecordDataImpl &Record) { 3965 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 3966 Record.push_back(Info.NumTemplParamLists); 3967 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 3968 AddTemplateParameterList(Info.TemplParamLists[i], Record); 3969} 3970 3971void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 3972 RecordDataImpl &Record) { 3973 // Nested name specifiers usually aren't too long. I think that 8 would 3974 // typically accommodate the vast majority. 3975 SmallVector<NestedNameSpecifier *, 8> NestedNames; 3976 3977 // Push each of the NNS's onto a stack for serialization in reverse order. 3978 while (NNS) { 3979 NestedNames.push_back(NNS); 3980 NNS = NNS->getPrefix(); 3981 } 3982 3983 Record.push_back(NestedNames.size()); 3984 while(!NestedNames.empty()) { 3985 NNS = NestedNames.pop_back_val(); 3986 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 3987 Record.push_back(Kind); 3988 switch (Kind) { 3989 case NestedNameSpecifier::Identifier: 3990 AddIdentifierRef(NNS->getAsIdentifier(), Record); 3991 break; 3992 3993 case NestedNameSpecifier::Namespace: 3994 AddDeclRef(NNS->getAsNamespace(), Record); 3995 break; 3996 3997 case NestedNameSpecifier::NamespaceAlias: 3998 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 3999 break; 4000 4001 case NestedNameSpecifier::TypeSpec: 4002 case NestedNameSpecifier::TypeSpecWithTemplate: 4003 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 4004 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 4005 break; 4006 4007 case NestedNameSpecifier::Global: 4008 // Don't need to write an associated value. 4009 break; 4010 } 4011 } 4012} 4013 4014void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 4015 RecordDataImpl &Record) { 4016 // Nested name specifiers usually aren't too long. I think that 8 would 4017 // typically accommodate the vast majority. 4018 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 4019 4020 // Push each of the nested-name-specifiers's onto a stack for 4021 // serialization in reverse order. 4022 while (NNS) { 4023 NestedNames.push_back(NNS); 4024 NNS = NNS.getPrefix(); 4025 } 4026 4027 Record.push_back(NestedNames.size()); 4028 while(!NestedNames.empty()) { 4029 NNS = NestedNames.pop_back_val(); 4030 NestedNameSpecifier::SpecifierKind Kind 4031 = NNS.getNestedNameSpecifier()->getKind(); 4032 Record.push_back(Kind); 4033 switch (Kind) { 4034 case NestedNameSpecifier::Identifier: 4035 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 4036 AddSourceRange(NNS.getLocalSourceRange(), Record); 4037 break; 4038 4039 case NestedNameSpecifier::Namespace: 4040 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 4041 AddSourceRange(NNS.getLocalSourceRange(), Record); 4042 break; 4043 4044 case NestedNameSpecifier::NamespaceAlias: 4045 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 4046 AddSourceRange(NNS.getLocalSourceRange(), Record); 4047 break; 4048 4049 case NestedNameSpecifier::TypeSpec: 4050 case NestedNameSpecifier::TypeSpecWithTemplate: 4051 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 4052 AddTypeLoc(NNS.getTypeLoc(), Record); 4053 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 4054 break; 4055 4056 case NestedNameSpecifier::Global: 4057 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 4058 break; 4059 } 4060 } 4061} 4062 4063void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 4064 TemplateName::NameKind Kind = Name.getKind(); 4065 Record.push_back(Kind); 4066 switch (Kind) { 4067 case TemplateName::Template: 4068 AddDeclRef(Name.getAsTemplateDecl(), Record); 4069 break; 4070 4071 case TemplateName::OverloadedTemplate: { 4072 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 4073 Record.push_back(OvT->size()); 4074 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 4075 I != E; ++I) 4076 AddDeclRef(*I, Record); 4077 break; 4078 } 4079 4080 case TemplateName::QualifiedTemplate: { 4081 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 4082 AddNestedNameSpecifier(QualT->getQualifier(), Record); 4083 Record.push_back(QualT->hasTemplateKeyword()); 4084 AddDeclRef(QualT->getTemplateDecl(), Record); 4085 break; 4086 } 4087 4088 case TemplateName::DependentTemplate: { 4089 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 4090 AddNestedNameSpecifier(DepT->getQualifier(), Record); 4091 Record.push_back(DepT->isIdentifier()); 4092 if (DepT->isIdentifier()) 4093 AddIdentifierRef(DepT->getIdentifier(), Record); 4094 else 4095 Record.push_back(DepT->getOperator()); 4096 break; 4097 } 4098 4099 case TemplateName::SubstTemplateTemplateParm: { 4100 SubstTemplateTemplateParmStorage *subst 4101 = Name.getAsSubstTemplateTemplateParm(); 4102 AddDeclRef(subst->getParameter(), Record); 4103 AddTemplateName(subst->getReplacement(), Record); 4104 break; 4105 } 4106 4107 case TemplateName::SubstTemplateTemplateParmPack: { 4108 SubstTemplateTemplateParmPackStorage *SubstPack 4109 = Name.getAsSubstTemplateTemplateParmPack(); 4110 AddDeclRef(SubstPack->getParameterPack(), Record); 4111 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 4112 break; 4113 } 4114 } 4115} 4116 4117void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 4118 RecordDataImpl &Record) { 4119 Record.push_back(Arg.getKind()); 4120 switch (Arg.getKind()) { 4121 case TemplateArgument::Null: 4122 break; 4123 case TemplateArgument::Type: 4124 AddTypeRef(Arg.getAsType(), Record); 4125 break; 4126 case TemplateArgument::Declaration: 4127 AddDeclRef(Arg.getAsDecl(), Record); 4128 break; 4129 case TemplateArgument::Integral: 4130 AddAPSInt(*Arg.getAsIntegral(), Record); 4131 AddTypeRef(Arg.getIntegralType(), Record); 4132 break; 4133 case TemplateArgument::Template: 4134 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 4135 break; 4136 case TemplateArgument::TemplateExpansion: 4137 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 4138 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 4139 Record.push_back(*NumExpansions + 1); 4140 else 4141 Record.push_back(0); 4142 break; 4143 case TemplateArgument::Expression: 4144 AddStmt(Arg.getAsExpr()); 4145 break; 4146 case TemplateArgument::Pack: 4147 Record.push_back(Arg.pack_size()); 4148 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 4149 I != E; ++I) 4150 AddTemplateArgument(*I, Record); 4151 break; 4152 } 4153} 4154 4155void 4156ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 4157 RecordDataImpl &Record) { 4158 assert(TemplateParams && "No TemplateParams!"); 4159 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 4160 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 4161 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 4162 Record.push_back(TemplateParams->size()); 4163 for (TemplateParameterList::const_iterator 4164 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 4165 P != PEnd; ++P) 4166 AddDeclRef(*P, Record); 4167} 4168 4169/// \brief Emit a template argument list. 4170void 4171ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 4172 RecordDataImpl &Record) { 4173 assert(TemplateArgs && "No TemplateArgs!"); 4174 Record.push_back(TemplateArgs->size()); 4175 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 4176 AddTemplateArgument(TemplateArgs->get(i), Record); 4177} 4178 4179 4180void 4181ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 4182 Record.push_back(Set.size()); 4183 for (UnresolvedSetImpl::const_iterator 4184 I = Set.begin(), E = Set.end(); I != E; ++I) { 4185 AddDeclRef(I.getDecl(), Record); 4186 Record.push_back(I.getAccess()); 4187 } 4188} 4189 4190void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 4191 RecordDataImpl &Record) { 4192 Record.push_back(Base.isVirtual()); 4193 Record.push_back(Base.isBaseOfClass()); 4194 Record.push_back(Base.getAccessSpecifierAsWritten()); 4195 Record.push_back(Base.getInheritConstructors()); 4196 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 4197 AddSourceRange(Base.getSourceRange(), Record); 4198 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 4199 : SourceLocation(), 4200 Record); 4201} 4202 4203void ASTWriter::FlushCXXBaseSpecifiers() { 4204 RecordData Record; 4205 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 4206 Record.clear(); 4207 4208 // Record the offset of this base-specifier set. 4209 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 4210 if (Index == CXXBaseSpecifiersOffsets.size()) 4211 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 4212 else { 4213 if (Index > CXXBaseSpecifiersOffsets.size()) 4214 CXXBaseSpecifiersOffsets.resize(Index + 1); 4215 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 4216 } 4217 4218 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 4219 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 4220 Record.push_back(BEnd - B); 4221 for (; B != BEnd; ++B) 4222 AddCXXBaseSpecifier(*B, Record); 4223 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 4224 4225 // Flush any expressions that were written as part of the base specifiers. 4226 FlushStmts(); 4227 } 4228 4229 CXXBaseSpecifiersToWrite.clear(); 4230} 4231 4232void ASTWriter::AddCXXCtorInitializers( 4233 const CXXCtorInitializer * const *CtorInitializers, 4234 unsigned NumCtorInitializers, 4235 RecordDataImpl &Record) { 4236 Record.push_back(NumCtorInitializers); 4237 for (unsigned i=0; i != NumCtorInitializers; ++i) { 4238 const CXXCtorInitializer *Init = CtorInitializers[i]; 4239 4240 if (Init->isBaseInitializer()) { 4241 Record.push_back(CTOR_INITIALIZER_BASE); 4242 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4243 Record.push_back(Init->isBaseVirtual()); 4244 } else if (Init->isDelegatingInitializer()) { 4245 Record.push_back(CTOR_INITIALIZER_DELEGATING); 4246 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4247 } else if (Init->isMemberInitializer()){ 4248 Record.push_back(CTOR_INITIALIZER_MEMBER); 4249 AddDeclRef(Init->getMember(), Record); 4250 } else { 4251 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 4252 AddDeclRef(Init->getIndirectMember(), Record); 4253 } 4254 4255 AddSourceLocation(Init->getMemberLocation(), Record); 4256 AddStmt(Init->getInit()); 4257 AddSourceLocation(Init->getLParenLoc(), Record); 4258 AddSourceLocation(Init->getRParenLoc(), Record); 4259 Record.push_back(Init->isWritten()); 4260 if (Init->isWritten()) { 4261 Record.push_back(Init->getSourceOrder()); 4262 } else { 4263 Record.push_back(Init->getNumArrayIndices()); 4264 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 4265 AddDeclRef(Init->getArrayIndex(i), Record); 4266 } 4267 } 4268} 4269 4270void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 4271 assert(D->DefinitionData); 4272 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 4273 Record.push_back(Data.UserDeclaredConstructor); 4274 Record.push_back(Data.UserDeclaredCopyConstructor); 4275 Record.push_back(Data.UserDeclaredMoveConstructor); 4276 Record.push_back(Data.UserDeclaredCopyAssignment); 4277 Record.push_back(Data.UserDeclaredMoveAssignment); 4278 Record.push_back(Data.UserDeclaredDestructor); 4279 Record.push_back(Data.Aggregate); 4280 Record.push_back(Data.PlainOldData); 4281 Record.push_back(Data.Empty); 4282 Record.push_back(Data.Polymorphic); 4283 Record.push_back(Data.Abstract); 4284 Record.push_back(Data.IsStandardLayout); 4285 Record.push_back(Data.HasNoNonEmptyBases); 4286 Record.push_back(Data.HasPrivateFields); 4287 Record.push_back(Data.HasProtectedFields); 4288 Record.push_back(Data.HasPublicFields); 4289 Record.push_back(Data.HasMutableFields); 4290 Record.push_back(Data.HasTrivialDefaultConstructor); 4291 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 4292 Record.push_back(Data.HasTrivialCopyConstructor); 4293 Record.push_back(Data.HasTrivialMoveConstructor); 4294 Record.push_back(Data.HasTrivialCopyAssignment); 4295 Record.push_back(Data.HasTrivialMoveAssignment); 4296 Record.push_back(Data.HasTrivialDestructor); 4297 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 4298 Record.push_back(Data.ComputedVisibleConversions); 4299 Record.push_back(Data.UserProvidedDefaultConstructor); 4300 Record.push_back(Data.DeclaredDefaultConstructor); 4301 Record.push_back(Data.DeclaredCopyConstructor); 4302 Record.push_back(Data.DeclaredMoveConstructor); 4303 Record.push_back(Data.DeclaredCopyAssignment); 4304 Record.push_back(Data.DeclaredMoveAssignment); 4305 Record.push_back(Data.DeclaredDestructor); 4306 Record.push_back(Data.FailedImplicitMoveConstructor); 4307 Record.push_back(Data.FailedImplicitMoveAssignment); 4308 4309 Record.push_back(Data.NumBases); 4310 if (Data.NumBases > 0) 4311 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 4312 Record); 4313 4314 // FIXME: Make VBases lazily computed when needed to avoid storing them. 4315 Record.push_back(Data.NumVBases); 4316 if (Data.NumVBases > 0) 4317 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 4318 Record); 4319 4320 AddUnresolvedSet(Data.Conversions, Record); 4321 AddUnresolvedSet(Data.VisibleConversions, Record); 4322 // Data.Definition is the owning decl, no need to write it. 4323 AddDeclRef(Data.FirstFriend, Record); 4324} 4325 4326void ASTWriter::ReaderInitialized(ASTReader *Reader) { 4327 assert(Reader && "Cannot remove chain"); 4328 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 4329 assert(FirstDeclID == NextDeclID && 4330 FirstTypeID == NextTypeID && 4331 FirstIdentID == NextIdentID && 4332 FirstSubmoduleID == NextSubmoduleID && 4333 FirstSelectorID == NextSelectorID && 4334 "Setting chain after writing has started."); 4335 4336 Chain = Reader; 4337 4338 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 4339 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 4340 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 4341 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 4342 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 4343 NextDeclID = FirstDeclID; 4344 NextTypeID = FirstTypeID; 4345 NextIdentID = FirstIdentID; 4346 NextSelectorID = FirstSelectorID; 4347 NextSubmoduleID = FirstSubmoduleID; 4348} 4349 4350void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 4351 IdentifierIDs[II] = ID; 4352 if (II->hasMacroDefinition()) 4353 DeserializedMacroNames.push_back(II); 4354} 4355 4356void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 4357 // Always take the highest-numbered type index. This copes with an interesting 4358 // case for chained AST writing where we schedule writing the type and then, 4359 // later, deserialize the type from another AST. In this case, we want to 4360 // keep the higher-numbered entry so that we can properly write it out to 4361 // the AST file. 4362 TypeIdx &StoredIdx = TypeIdxs[T]; 4363 if (Idx.getIndex() >= StoredIdx.getIndex()) 4364 StoredIdx = Idx; 4365} 4366 4367void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 4368 SelectorIDs[S] = ID; 4369} 4370 4371void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 4372 MacroDefinition *MD) { 4373 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 4374 MacroDefinitions[MD] = ID; 4375} 4376 4377void ASTWriter::MacroVisible(IdentifierInfo *II) { 4378 DeserializedMacroNames.push_back(II); 4379} 4380 4381void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 4382 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 4383 SubmoduleIDs[Mod] = ID; 4384} 4385 4386void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 4387 assert(D->isCompleteDefinition()); 4388 assert(!WritingAST && "Already writing the AST!"); 4389 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 4390 // We are interested when a PCH decl is modified. 4391 if (RD->isFromASTFile()) { 4392 // A forward reference was mutated into a definition. Rewrite it. 4393 // FIXME: This happens during template instantiation, should we 4394 // have created a new definition decl instead ? 4395 RewriteDecl(RD); 4396 } 4397 } 4398} 4399void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 4400 assert(!WritingAST && "Already writing the AST!"); 4401 4402 // TU and namespaces are handled elsewhere. 4403 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 4404 return; 4405 4406 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile())) 4407 return; // Not a source decl added to a DeclContext from PCH. 4408 4409 AddUpdatedDeclContext(DC); 4410} 4411 4412void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 4413 assert(!WritingAST && "Already writing the AST!"); 4414 assert(D->isImplicit()); 4415 if (!(!D->isFromASTFile() && RD->isFromASTFile())) 4416 return; // Not a source member added to a class from PCH. 4417 if (!isa<CXXMethodDecl>(D)) 4418 return; // We are interested in lazily declared implicit methods. 4419 4420 // A decl coming from PCH was modified. 4421 assert(RD->isCompleteDefinition()); 4422 UpdateRecord &Record = DeclUpdates[RD]; 4423 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 4424 Record.push_back(reinterpret_cast<uint64_t>(D)); 4425} 4426 4427void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 4428 const ClassTemplateSpecializationDecl *D) { 4429 // The specializations set is kept in the canonical template. 4430 assert(!WritingAST && "Already writing the AST!"); 4431 TD = TD->getCanonicalDecl(); 4432 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4433 return; // Not a source specialization added to a template from PCH. 4434 4435 UpdateRecord &Record = DeclUpdates[TD]; 4436 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4437 Record.push_back(reinterpret_cast<uint64_t>(D)); 4438} 4439 4440void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 4441 const FunctionDecl *D) { 4442 // The specializations set is kept in the canonical template. 4443 assert(!WritingAST && "Already writing the AST!"); 4444 TD = TD->getCanonicalDecl(); 4445 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4446 return; // Not a source specialization added to a template from PCH. 4447 4448 UpdateRecord &Record = DeclUpdates[TD]; 4449 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4450 Record.push_back(reinterpret_cast<uint64_t>(D)); 4451} 4452 4453void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 4454 assert(!WritingAST && "Already writing the AST!"); 4455 if (!D->isFromASTFile()) 4456 return; // Declaration not imported from PCH. 4457 4458 // Implicit decl from a PCH was defined. 4459 // FIXME: Should implicit definition be a separate FunctionDecl? 4460 RewriteDecl(D); 4461} 4462 4463void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 4464 assert(!WritingAST && "Already writing the AST!"); 4465 if (!D->isFromASTFile()) 4466 return; 4467 4468 // Since the actual instantiation is delayed, this really means that we need 4469 // to update the instantiation location. 4470 UpdateRecord &Record = DeclUpdates[D]; 4471 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER); 4472 AddSourceLocation( 4473 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record); 4474} 4475 4476void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 4477 const ObjCInterfaceDecl *IFD) { 4478 assert(!WritingAST && "Already writing the AST!"); 4479 if (!IFD->isFromASTFile()) 4480 return; // Declaration not imported from PCH. 4481 4482 assert(IFD->getDefinition() && "Category on a class without a definition?"); 4483 ObjCClassesWithCategories.insert( 4484 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 4485} 4486 4487 4488void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, 4489 const ObjCPropertyDecl *OrigProp, 4490 const ObjCCategoryDecl *ClassExt) { 4491 const ObjCInterfaceDecl *D = ClassExt->getClassInterface(); 4492 if (!D) 4493 return; 4494 4495 assert(!WritingAST && "Already writing the AST!"); 4496 if (!D->isFromASTFile()) 4497 return; // Declaration not imported from PCH. 4498 4499 RewriteDecl(D); 4500} 4501 4502