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