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