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