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