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((unsigned) LangOpts.ObjCRuntime.getKind()); 1086 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record); 1087 1088 Record.push_back(LangOpts.CurrentModule.size()); 1089 Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end()); 1090 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1091 } 1092 1093 //===----------------------------------------------------------------------===// 1094 // stat cache Serialization 1095 //===----------------------------------------------------------------------===// 1096 1097 namespace { 1098 // Trait used for the on-disk hash table of stat cache results. 1099 class ASTStatCacheTrait { 1100 public: 1101 typedef const char * key_type; 1102 typedef key_type key_type_ref; 1103 1104 typedef struct stat data_type; 1105 typedef const data_type &data_type_ref; 1106 1107 static unsigned ComputeHash(const char *path) { 1108 return llvm::HashString(path); 1109 } 1110 1111 std::pair<unsigned,unsigned> 1112 EmitKeyDataLength(raw_ostream& Out, const char *path, 1113 data_type_ref Data) { 1114 unsigned StrLen = strlen(path); 1115 clang::io::Emit16(Out, StrLen); 1116 unsigned DataLen = 4 + 4 + 2 + 8 + 8; 1117 clang::io::Emit8(Out, DataLen); 1118 return std::make_pair(StrLen + 1, DataLen); 1119 } 1120 1121 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1122 Out.write(path, KeyLen); 1123 } 1124 1125 void EmitData(raw_ostream &Out, key_type_ref, 1126 data_type_ref Data, unsigned DataLen) { 1127 using namespace clang::io; 1128 uint64_t Start = Out.tell(); (void)Start; 1129 1130 Emit32(Out, (uint32_t) Data.st_ino); 1131 Emit32(Out, (uint32_t) Data.st_dev); 1132 Emit16(Out, (uint16_t) Data.st_mode); 1133 Emit64(Out, (uint64_t) Data.st_mtime); 1134 Emit64(Out, (uint64_t) Data.st_size); 1135 1136 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1137 } 1138 }; 1139 } // end anonymous namespace 1140 1141 /// \brief Write the stat() system call cache to the AST file. 1142 void ASTWriter::WriteStatCache(MemorizeStatCalls &StatCalls) { 1143 // Build the on-disk hash table containing information about every 1144 // stat() call. 1145 OnDiskChainedHashTableGenerator<ASTStatCacheTrait> Generator; 1146 unsigned NumStatEntries = 0; 1147 for (MemorizeStatCalls::iterator Stat = StatCalls.begin(), 1148 StatEnd = StatCalls.end(); 1149 Stat != StatEnd; ++Stat, ++NumStatEntries) { 1150 StringRef Filename = Stat->first(); 1151 Generator.insert(Filename.data(), Stat->second); 1152 } 1153 1154 // Create the on-disk hash table in a buffer. 1155 SmallString<4096> StatCacheData; 1156 uint32_t BucketOffset; 1157 { 1158 llvm::raw_svector_ostream Out(StatCacheData); 1159 // Make sure that no bucket is at offset 0 1160 clang::io::Emit32(Out, 0); 1161 BucketOffset = Generator.Emit(Out); 1162 } 1163 1164 // Create a blob abbreviation 1165 using namespace llvm; 1166 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1167 Abbrev->Add(BitCodeAbbrevOp(STAT_CACHE)); 1168 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1169 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1170 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1171 unsigned StatCacheAbbrev = Stream.EmitAbbrev(Abbrev); 1172 1173 // Write the stat cache 1174 RecordData Record; 1175 Record.push_back(STAT_CACHE); 1176 Record.push_back(BucketOffset); 1177 Record.push_back(NumStatEntries); 1178 Stream.EmitRecordWithBlob(StatCacheAbbrev, Record, StatCacheData.str()); 1179 } 1180 1181 //===----------------------------------------------------------------------===// 1182 // Source Manager Serialization 1183 //===----------------------------------------------------------------------===// 1184 1185 /// \brief Create an abbreviation for the SLocEntry that refers to a 1186 /// file. 1187 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1188 using namespace llvm; 1189 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1190 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1191 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1192 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1193 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1194 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1195 // FileEntry fields. 1196 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1197 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1198 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // BufferOverridden 1199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1200 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1202 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1203 return Stream.EmitAbbrev(Abbrev); 1204 } 1205 1206 /// \brief Create an abbreviation for the SLocEntry that refers to a 1207 /// buffer. 1208 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1209 using namespace llvm; 1210 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1211 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic 1215 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1216 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1217 return Stream.EmitAbbrev(Abbrev); 1218 } 1219 1220 /// \brief Create an abbreviation for the SLocEntry that refers to a 1221 /// buffer's blob. 1222 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) { 1223 using namespace llvm; 1224 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1225 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB)); 1226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1227 return Stream.EmitAbbrev(Abbrev); 1228 } 1229 1230 /// \brief Create an abbreviation for the SLocEntry that refers to a macro 1231 /// expansion. 1232 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1233 using namespace llvm; 1234 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1235 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1236 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1237 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1238 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1239 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1240 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1241 return Stream.EmitAbbrev(Abbrev); 1242 } 1243 1244 namespace { 1245 // Trait used for the on-disk hash table of header search information. 1246 class HeaderFileInfoTrait { 1247 ASTWriter &Writer; 1248 1249 // Keep track of the framework names we've used during serialization. 1250 SmallVector<char, 128> FrameworkStringData; 1251 llvm::StringMap<unsigned> FrameworkNameOffset; 1252 1253 public: 1254 HeaderFileInfoTrait(ASTWriter &Writer) 1255 : Writer(Writer) { } 1256 1257 typedef const char *key_type; 1258 typedef key_type key_type_ref; 1259 1260 typedef HeaderFileInfo data_type; 1261 typedef const data_type &data_type_ref; 1262 1263 static unsigned ComputeHash(const char *path) { 1264 // The hash is based only on the filename portion of the key, so that the 1265 // reader can match based on filenames when symlinking or excess path 1266 // elements ("foo/../", "../") change the form of the name. However, 1267 // complete path is still the key. 1268 return llvm::HashString(llvm::sys::path::filename(path)); 1269 } 1270 1271 std::pair<unsigned,unsigned> 1272 EmitKeyDataLength(raw_ostream& Out, const char *path, 1273 data_type_ref Data) { 1274 unsigned StrLen = strlen(path); 1275 clang::io::Emit16(Out, StrLen); 1276 unsigned DataLen = 1 + 2 + 4 + 4; 1277 clang::io::Emit8(Out, DataLen); 1278 return std::make_pair(StrLen + 1, DataLen); 1279 } 1280 1281 void EmitKey(raw_ostream& Out, const char *path, unsigned KeyLen) { 1282 Out.write(path, KeyLen); 1283 } 1284 1285 void EmitData(raw_ostream &Out, key_type_ref, 1286 data_type_ref Data, unsigned DataLen) { 1287 using namespace clang::io; 1288 uint64_t Start = Out.tell(); (void)Start; 1289 1290 unsigned char Flags = (Data.isImport << 5) 1291 | (Data.isPragmaOnce << 4) 1292 | (Data.DirInfo << 2) 1293 | (Data.Resolved << 1) 1294 | Data.IndexHeaderMapHeader; 1295 Emit8(Out, (uint8_t)Flags); 1296 Emit16(Out, (uint16_t) Data.NumIncludes); 1297 1298 if (!Data.ControllingMacro) 1299 Emit32(Out, (uint32_t)Data.ControllingMacroID); 1300 else 1301 Emit32(Out, (uint32_t)Writer.getIdentifierRef(Data.ControllingMacro)); 1302 1303 unsigned Offset = 0; 1304 if (!Data.Framework.empty()) { 1305 // If this header refers into a framework, save the framework name. 1306 llvm::StringMap<unsigned>::iterator Pos 1307 = FrameworkNameOffset.find(Data.Framework); 1308 if (Pos == FrameworkNameOffset.end()) { 1309 Offset = FrameworkStringData.size() + 1; 1310 FrameworkStringData.append(Data.Framework.begin(), 1311 Data.Framework.end()); 1312 FrameworkStringData.push_back(0); 1313 1314 FrameworkNameOffset[Data.Framework] = Offset; 1315 } else 1316 Offset = Pos->second; 1317 } 1318 Emit32(Out, Offset); 1319 1320 assert(Out.tell() - Start == DataLen && "Wrong data length"); 1321 } 1322 1323 const char *strings_begin() const { return FrameworkStringData.begin(); } 1324 const char *strings_end() const { return FrameworkStringData.end(); } 1325 }; 1326 } // end anonymous namespace 1327 1328 /// \brief Write the header search block for the list of files that 1329 /// 1330 /// \param HS The header search structure to save. 1331 /// 1332 /// \param Chain Whether we're creating a chained AST file. 1333 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) { 1334 SmallVector<const FileEntry *, 16> FilesByUID; 1335 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 1336 1337 if (FilesByUID.size() > HS.header_file_size()) 1338 FilesByUID.resize(HS.header_file_size()); 1339 1340 HeaderFileInfoTrait GeneratorTrait(*this); 1341 OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 1342 SmallVector<const char *, 4> SavedStrings; 1343 unsigned NumHeaderSearchEntries = 0; 1344 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 1345 const FileEntry *File = FilesByUID[UID]; 1346 if (!File) 1347 continue; 1348 1349 // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo 1350 // from the external source if it was not provided already. 1351 const HeaderFileInfo &HFI = HS.getFileInfo(File); 1352 if (HFI.External && Chain) 1353 continue; 1354 1355 // Turn the file name into an absolute path, if it isn't already. 1356 const char *Filename = File->getName(); 1357 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1358 1359 // If we performed any translation on the file name at all, we need to 1360 // save this string, since the generator will refer to it later. 1361 if (Filename != File->getName()) { 1362 Filename = strdup(Filename); 1363 SavedStrings.push_back(Filename); 1364 } 1365 1366 Generator.insert(Filename, HFI, GeneratorTrait); 1367 ++NumHeaderSearchEntries; 1368 } 1369 1370 // Create the on-disk hash table in a buffer. 1371 SmallString<4096> TableData; 1372 uint32_t BucketOffset; 1373 { 1374 llvm::raw_svector_ostream Out(TableData); 1375 // Make sure that no bucket is at offset 0 1376 clang::io::Emit32(Out, 0); 1377 BucketOffset = Generator.Emit(Out, GeneratorTrait); 1378 } 1379 1380 // Create a blob abbreviation 1381 using namespace llvm; 1382 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1383 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 1384 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1385 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1386 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1387 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1388 unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev); 1389 1390 // Write the header search table 1391 RecordData Record; 1392 Record.push_back(HEADER_SEARCH_TABLE); 1393 Record.push_back(BucketOffset); 1394 Record.push_back(NumHeaderSearchEntries); 1395 Record.push_back(TableData.size()); 1396 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 1397 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str()); 1398 1399 // Free all of the strings we had to duplicate. 1400 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 1401 free((void*)SavedStrings[I]); 1402 } 1403 1404 /// \brief Writes the block containing the serialized form of the 1405 /// source manager. 1406 /// 1407 /// TODO: We should probably use an on-disk hash table (stored in a 1408 /// blob), indexed based on the file name, so that we only create 1409 /// entries for files that we actually need. In the common case (no 1410 /// errors), we probably won't have to create file entries for any of 1411 /// the files in the AST. 1412 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 1413 const Preprocessor &PP, 1414 StringRef isysroot) { 1415 RecordData Record; 1416 1417 // Enter the source manager block. 1418 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3); 1419 1420 // Abbreviations for the various kinds of source-location entries. 1421 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 1422 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 1423 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream); 1424 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 1425 1426 // Write out the source location entry table. We skip the first 1427 // entry, which is always the same dummy entry. 1428 std::vector<uint32_t> SLocEntryOffsets; 1429 // Write out the offsets of only source location file entries. 1430 // We will go through them in ASTReader::validateFileEntries(). 1431 std::vector<uint32_t> SLocFileEntryOffsets; 1432 RecordData PreloadSLocs; 1433 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 1434 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 1435 I != N; ++I) { 1436 // Get this source location entry. 1437 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1438 1439 // Record the offset of this source-location entry. 1440 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1441 1442 // Figure out which record code to use. 1443 unsigned Code; 1444 if (SLoc->isFile()) { 1445 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 1446 if (Cache->OrigEntry) { 1447 Code = SM_SLOC_FILE_ENTRY; 1448 SLocFileEntryOffsets.push_back(Stream.GetCurrentBitNo()); 1449 } else 1450 Code = SM_SLOC_BUFFER_ENTRY; 1451 } else 1452 Code = SM_SLOC_EXPANSION_ENTRY; 1453 Record.clear(); 1454 Record.push_back(Code); 1455 1456 // Starting offset of this entry within this module, so skip the dummy. 1457 Record.push_back(SLoc->getOffset() - 2); 1458 if (SLoc->isFile()) { 1459 const SrcMgr::FileInfo &File = SLoc->getFile(); 1460 Record.push_back(File.getIncludeLoc().getRawEncoding()); 1461 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 1462 Record.push_back(File.hasLineDirectives()); 1463 1464 const SrcMgr::ContentCache *Content = File.getContentCache(); 1465 if (Content->OrigEntry) { 1466 assert(Content->OrigEntry == Content->ContentsEntry && 1467 "Writing to AST an overridden file is not supported"); 1468 1469 // The source location entry is a file. The blob associated 1470 // with this entry is the file name. 1471 1472 // Emit size/modification time for this file. 1473 Record.push_back(Content->OrigEntry->getSize()); 1474 Record.push_back(Content->OrigEntry->getModificationTime()); 1475 Record.push_back(Content->BufferOverridden); 1476 Record.push_back(File.NumCreatedFIDs); 1477 1478 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(SLoc); 1479 if (FDI != FileDeclIDs.end()) { 1480 Record.push_back(FDI->second->FirstDeclIndex); 1481 Record.push_back(FDI->second->DeclIDs.size()); 1482 } else { 1483 Record.push_back(0); 1484 Record.push_back(0); 1485 } 1486 1487 // Turn the file name into an absolute path, if it isn't already. 1488 const char *Filename = Content->OrigEntry->getName(); 1489 SmallString<128> FilePath(Filename); 1490 1491 // Ask the file manager to fixup the relative path for us. This will 1492 // honor the working directory. 1493 SourceMgr.getFileManager().FixupRelativePath(FilePath); 1494 1495 // FIXME: This call to make_absolute shouldn't be necessary, the 1496 // call to FixupRelativePath should always return an absolute path. 1497 llvm::sys::fs::make_absolute(FilePath); 1498 Filename = FilePath.c_str(); 1499 1500 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1501 Stream.EmitRecordWithBlob(SLocFileAbbrv, Record, Filename); 1502 1503 if (Content->BufferOverridden) { 1504 Record.clear(); 1505 Record.push_back(SM_SLOC_BUFFER_BLOB); 1506 const llvm::MemoryBuffer *Buffer 1507 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1508 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1509 StringRef(Buffer->getBufferStart(), 1510 Buffer->getBufferSize() + 1)); 1511 } 1512 } else { 1513 // The source location entry is a buffer. The blob associated 1514 // with this entry contains the contents of the buffer. 1515 1516 // We add one to the size so that we capture the trailing NULL 1517 // that is required by llvm::MemoryBuffer::getMemBuffer (on 1518 // the reader side). 1519 const llvm::MemoryBuffer *Buffer 1520 = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager()); 1521 const char *Name = Buffer->getBufferIdentifier(); 1522 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 1523 StringRef(Name, strlen(Name) + 1)); 1524 Record.clear(); 1525 Record.push_back(SM_SLOC_BUFFER_BLOB); 1526 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, 1527 StringRef(Buffer->getBufferStart(), 1528 Buffer->getBufferSize() + 1)); 1529 1530 if (strcmp(Name, "<built-in>") == 0) { 1531 PreloadSLocs.push_back(SLocEntryOffsets.size()); 1532 } 1533 } 1534 } else { 1535 // The source location entry is a macro expansion. 1536 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 1537 Record.push_back(Expansion.getSpellingLoc().getRawEncoding()); 1538 Record.push_back(Expansion.getExpansionLocStart().getRawEncoding()); 1539 Record.push_back(Expansion.isMacroArgExpansion() ? 0 1540 : Expansion.getExpansionLocEnd().getRawEncoding()); 1541 1542 // Compute the token length for this macro expansion. 1543 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 1544 if (I + 1 != N) 1545 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 1546 Record.push_back(NextOffset - SLoc->getOffset() - 1); 1547 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 1548 } 1549 } 1550 1551 Stream.ExitBlock(); 1552 1553 if (SLocEntryOffsets.empty()) 1554 return; 1555 1556 // Write the source-location offsets table into the AST block. This 1557 // table is used for lazily loading source-location information. 1558 using namespace llvm; 1559 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1560 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 1561 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1562 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 1563 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1564 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1565 1566 Record.clear(); 1567 Record.push_back(SOURCE_LOCATION_OFFSETS); 1568 Record.push_back(SLocEntryOffsets.size()); 1569 Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy 1570 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets)); 1571 1572 Abbrev = new BitCodeAbbrev(); 1573 Abbrev->Add(BitCodeAbbrevOp(FILE_SOURCE_LOCATION_OFFSETS)); 1574 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 1575 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 1576 unsigned SLocFileOffsetsAbbrev = Stream.EmitAbbrev(Abbrev); 1577 1578 Record.clear(); 1579 Record.push_back(FILE_SOURCE_LOCATION_OFFSETS); 1580 Record.push_back(SLocFileEntryOffsets.size()); 1581 Stream.EmitRecordWithBlob(SLocFileOffsetsAbbrev, Record, 1582 data(SLocFileEntryOffsets)); 1583 1584 // Write the source location entry preloads array, telling the AST 1585 // reader which source locations entries it should load eagerly. 1586 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 1587 1588 // Write the line table. It depends on remapping working, so it must come 1589 // after the source location offsets. 1590 if (SourceMgr.hasLineTable()) { 1591 LineTableInfo &LineTable = SourceMgr.getLineTable(); 1592 1593 Record.clear(); 1594 // Emit the file names 1595 Record.push_back(LineTable.getNumFilenames()); 1596 for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) { 1597 // Emit the file name 1598 const char *Filename = LineTable.getFilename(I); 1599 Filename = adjustFilenameForRelocatablePCH(Filename, isysroot); 1600 unsigned FilenameLen = Filename? strlen(Filename) : 0; 1601 Record.push_back(FilenameLen); 1602 if (FilenameLen) 1603 Record.insert(Record.end(), Filename, Filename + FilenameLen); 1604 } 1605 1606 // Emit the line entries 1607 for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end(); 1608 L != LEnd; ++L) { 1609 // Only emit entries for local files. 1610 if (L->first.ID < 0) 1611 continue; 1612 1613 // Emit the file ID 1614 Record.push_back(L->first.ID); 1615 1616 // Emit the line entries 1617 Record.push_back(L->second.size()); 1618 for (std::vector<LineEntry>::iterator LE = L->second.begin(), 1619 LEEnd = L->second.end(); 1620 LE != LEEnd; ++LE) { 1621 Record.push_back(LE->FileOffset); 1622 Record.push_back(LE->LineNo); 1623 Record.push_back(LE->FilenameID); 1624 Record.push_back((unsigned)LE->FileKind); 1625 Record.push_back(LE->IncludeOffset); 1626 } 1627 } 1628 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 1629 } 1630 } 1631 1632 //===----------------------------------------------------------------------===// 1633 // Preprocessor Serialization 1634 //===----------------------------------------------------------------------===// 1635 1636 static int compareMacroDefinitions(const void *XPtr, const void *YPtr) { 1637 const std::pair<const IdentifierInfo *, MacroInfo *> &X = 1638 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)XPtr; 1639 const std::pair<const IdentifierInfo *, MacroInfo *> &Y = 1640 *(const std::pair<const IdentifierInfo *, MacroInfo *>*)YPtr; 1641 return X.first->getName().compare(Y.first->getName()); 1642 } 1643 1644 /// \brief Writes the block containing the serialized form of the 1645 /// preprocessor. 1646 /// 1647 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 1648 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 1649 if (PPRec) 1650 WritePreprocessorDetail(*PPRec); 1651 1652 RecordData Record; 1653 1654 // If the preprocessor __COUNTER__ value has been bumped, remember it. 1655 if (PP.getCounterValue() != 0) { 1656 Record.push_back(PP.getCounterValue()); 1657 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 1658 Record.clear(); 1659 } 1660 1661 // Enter the preprocessor block. 1662 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 1663 1664 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 1665 // FIXME: use diagnostics subsystem for localization etc. 1666 if (PP.SawDateOrTime()) 1667 fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n"); 1668 1669 1670 // Loop over all the macro definitions that are live at the end of the file, 1671 // emitting each to the PP section. 1672 1673 // Construct the list of macro definitions that need to be serialized. 1674 SmallVector<std::pair<const IdentifierInfo *, MacroInfo *>, 2> 1675 MacrosToEmit; 1676 llvm::SmallPtrSet<const IdentifierInfo*, 4> MacroDefinitionsSeen; 1677 for (Preprocessor::macro_iterator I = PP.macro_begin(Chain == 0), 1678 E = PP.macro_end(Chain == 0); 1679 I != E; ++I) { 1680 const IdentifierInfo *Name = I->first; 1681 if (!IsModule || I->second->isPublic()) { 1682 MacroDefinitionsSeen.insert(Name); 1683 MacrosToEmit.push_back(std::make_pair(I->first, I->second)); 1684 } 1685 } 1686 1687 // Sort the set of macro definitions that need to be serialized by the 1688 // name of the macro, to provide a stable ordering. 1689 llvm::array_pod_sort(MacrosToEmit.begin(), MacrosToEmit.end(), 1690 &compareMacroDefinitions); 1691 1692 // Resolve any identifiers that defined macros at the time they were 1693 // deserialized, adding them to the list of macros to emit (if appropriate). 1694 for (unsigned I = 0, N = DeserializedMacroNames.size(); I != N; ++I) { 1695 IdentifierInfo *Name 1696 = const_cast<IdentifierInfo *>(DeserializedMacroNames[I]); 1697 if (Name->hasMacroDefinition() && MacroDefinitionsSeen.insert(Name)) 1698 MacrosToEmit.push_back(std::make_pair(Name, PP.getMacroInfo(Name))); 1699 } 1700 1701 for (unsigned I = 0, N = MacrosToEmit.size(); I != N; ++I) { 1702 const IdentifierInfo *Name = MacrosToEmit[I].first; 1703 MacroInfo *MI = MacrosToEmit[I].second; 1704 if (!MI) 1705 continue; 1706 1707 // Don't emit builtin macros like __LINE__ to the AST file unless they have 1708 // been redefined by the header (in which case they are not isBuiltinMacro). 1709 // Also skip macros from a AST file if we're chaining. 1710 1711 // FIXME: There is a (probably minor) optimization we could do here, if 1712 // the macro comes from the original PCH but the identifier comes from a 1713 // chained PCH, by storing the offset into the original PCH rather than 1714 // writing the macro definition a second time. 1715 if (MI->isBuiltinMacro() || 1716 (Chain && 1717 Name->isFromAST() && !Name->hasChangedSinceDeserialization() && 1718 MI->isFromAST() && !MI->hasChangedAfterLoad())) 1719 continue; 1720 1721 AddIdentifierRef(Name, Record); 1722 MacroOffsets[Name] = Stream.GetCurrentBitNo(); 1723 Record.push_back(MI->getDefinitionLoc().getRawEncoding()); 1724 Record.push_back(MI->isUsed()); 1725 Record.push_back(MI->isPublic()); 1726 AddSourceLocation(MI->getVisibilityLocation(), Record); 1727 unsigned Code; 1728 if (MI->isObjectLike()) { 1729 Code = PP_MACRO_OBJECT_LIKE; 1730 } else { 1731 Code = PP_MACRO_FUNCTION_LIKE; 1732 1733 Record.push_back(MI->isC99Varargs()); 1734 Record.push_back(MI->isGNUVarargs()); 1735 Record.push_back(MI->getNumArgs()); 1736 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 1737 I != E; ++I) 1738 AddIdentifierRef(*I, Record); 1739 } 1740 1741 // If we have a detailed preprocessing record, record the macro definition 1742 // ID that corresponds to this macro. 1743 if (PPRec) 1744 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 1745 1746 Stream.EmitRecord(Code, Record); 1747 Record.clear(); 1748 1749 // Emit the tokens array. 1750 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 1751 // Note that we know that the preprocessor does not have any annotation 1752 // tokens in it because they are created by the parser, and thus can't be 1753 // in a macro definition. 1754 const Token &Tok = MI->getReplacementToken(TokNo); 1755 1756 Record.push_back(Tok.getLocation().getRawEncoding()); 1757 Record.push_back(Tok.getLength()); 1758 1759 // FIXME: When reading literal tokens, reconstruct the literal pointer if 1760 // it is needed. 1761 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 1762 // FIXME: Should translate token kind to a stable encoding. 1763 Record.push_back(Tok.getKind()); 1764 // FIXME: Should translate token flags to a stable encoding. 1765 Record.push_back(Tok.getFlags()); 1766 1767 Stream.EmitRecord(PP_TOKEN, Record); 1768 Record.clear(); 1769 } 1770 ++NumMacros; 1771 } 1772 Stream.ExitBlock(); 1773 } 1774 1775 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 1776 if (PPRec.local_begin() == PPRec.local_end()) 1777 return; 1778 1779 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 1780 1781 // Enter the preprocessor block. 1782 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 1783 1784 // If the preprocessor has a preprocessing record, emit it. 1785 unsigned NumPreprocessingRecords = 0; 1786 using namespace llvm; 1787 1788 // Set up the abbreviation for 1789 unsigned InclusionAbbrev = 0; 1790 { 1791 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1792 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 1793 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 1794 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 1795 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 1796 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1797 InclusionAbbrev = Stream.EmitAbbrev(Abbrev); 1798 } 1799 1800 unsigned FirstPreprocessorEntityID 1801 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 1802 + NUM_PREDEF_PP_ENTITY_IDS; 1803 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 1804 RecordData Record; 1805 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 1806 EEnd = PPRec.local_end(); 1807 E != EEnd; 1808 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 1809 Record.clear(); 1810 1811 PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(), 1812 Stream.GetCurrentBitNo())); 1813 1814 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) { 1815 // Record this macro definition's ID. 1816 MacroDefinitions[MD] = NextPreprocessorEntityID; 1817 1818 AddIdentifierRef(MD->getName(), Record); 1819 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 1820 continue; 1821 } 1822 1823 if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) { 1824 Record.push_back(ME->isBuiltinMacro()); 1825 if (ME->isBuiltinMacro()) 1826 AddIdentifierRef(ME->getName(), Record); 1827 else 1828 Record.push_back(MacroDefinitions[ME->getDefinition()]); 1829 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 1830 continue; 1831 } 1832 1833 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) { 1834 Record.push_back(PPD_INCLUSION_DIRECTIVE); 1835 Record.push_back(ID->getFileName().size()); 1836 Record.push_back(ID->wasInQuotes()); 1837 Record.push_back(static_cast<unsigned>(ID->getKind())); 1838 SmallString<64> Buffer; 1839 Buffer += ID->getFileName(); 1840 // Check that the FileEntry is not null because it was not resolved and 1841 // we create a PCH even with compiler errors. 1842 if (ID->getFile()) 1843 Buffer += ID->getFile()->getName(); 1844 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 1845 continue; 1846 } 1847 1848 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 1849 } 1850 Stream.ExitBlock(); 1851 1852 // Write the offsets table for the preprocessing record. 1853 if (NumPreprocessingRecords > 0) { 1854 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 1855 1856 // Write the offsets table for identifier IDs. 1857 using namespace llvm; 1858 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1859 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 1860 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 1861 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 1862 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 1863 1864 Record.clear(); 1865 Record.push_back(PPD_ENTITIES_OFFSETS); 1866 Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS); 1867 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 1868 data(PreprocessedEntityOffsets)); 1869 } 1870 } 1871 1872 unsigned ASTWriter::getSubmoduleID(Module *Mod) { 1873 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod); 1874 if (Known != SubmoduleIDs.end()) 1875 return Known->second; 1876 1877 return SubmoduleIDs[Mod] = NextSubmoduleID++; 1878 } 1879 1880 /// \brief Compute the number of modules within the given tree (including the 1881 /// given module). 1882 static unsigned getNumberOfModules(Module *Mod) { 1883 unsigned ChildModules = 0; 1884 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 1885 SubEnd = Mod->submodule_end(); 1886 Sub != SubEnd; ++Sub) 1887 ChildModules += getNumberOfModules(*Sub); 1888 1889 return ChildModules + 1; 1890 } 1891 1892 void ASTWriter::WriteSubmodules(Module *WritingModule) { 1893 // Determine the dependencies of our module and each of it's submodules. 1894 // FIXME: This feels like it belongs somewhere else, but there are no 1895 // other consumers of this information. 1896 SourceManager &SrcMgr = PP->getSourceManager(); 1897 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 1898 for (ASTContext::import_iterator I = Context->local_import_begin(), 1899 IEnd = Context->local_import_end(); 1900 I != IEnd; ++I) { 1901 if (Module *ImportedFrom 1902 = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(), 1903 SrcMgr))) { 1904 ImportedFrom->Imports.push_back(I->getImportedModule()); 1905 } 1906 } 1907 1908 // Enter the submodule description block. 1909 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 1910 1911 // Write the abbreviations needed for the submodules block. 1912 using namespace llvm; 1913 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 1914 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 1915 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 1916 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 1917 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 1918 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 1919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem 1920 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules... 1921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit... 1922 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild... 1923 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1924 unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev); 1925 1926 Abbrev = new BitCodeAbbrev(); 1927 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER)); 1928 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1929 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev); 1930 1931 Abbrev = new BitCodeAbbrev(); 1932 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 1933 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1934 unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev); 1935 1936 Abbrev = new BitCodeAbbrev(); 1937 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR)); 1938 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1939 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev); 1940 1941 Abbrev = new BitCodeAbbrev(); 1942 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES)); 1943 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature 1944 unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev); 1945 1946 // Write the submodule metadata block. 1947 RecordData Record; 1948 Record.push_back(getNumberOfModules(WritingModule)); 1949 Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS); 1950 Stream.EmitRecord(SUBMODULE_METADATA, Record); 1951 1952 // Write all of the submodules. 1953 std::queue<Module *> Q; 1954 Q.push(WritingModule); 1955 while (!Q.empty()) { 1956 Module *Mod = Q.front(); 1957 Q.pop(); 1958 unsigned ID = getSubmoduleID(Mod); 1959 1960 // Emit the definition of the block. 1961 Record.clear(); 1962 Record.push_back(SUBMODULE_DEFINITION); 1963 Record.push_back(ID); 1964 if (Mod->Parent) { 1965 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 1966 Record.push_back(SubmoduleIDs[Mod->Parent]); 1967 } else { 1968 Record.push_back(0); 1969 } 1970 Record.push_back(Mod->IsFramework); 1971 Record.push_back(Mod->IsExplicit); 1972 Record.push_back(Mod->IsSystem); 1973 Record.push_back(Mod->InferSubmodules); 1974 Record.push_back(Mod->InferExplicitSubmodules); 1975 Record.push_back(Mod->InferExportWildcard); 1976 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 1977 1978 // Emit the requirements. 1979 for (unsigned I = 0, N = Mod->Requires.size(); I != N; ++I) { 1980 Record.clear(); 1981 Record.push_back(SUBMODULE_REQUIRES); 1982 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, 1983 Mod->Requires[I].data(), 1984 Mod->Requires[I].size()); 1985 } 1986 1987 // Emit the umbrella header, if there is one. 1988 if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) { 1989 Record.clear(); 1990 Record.push_back(SUBMODULE_UMBRELLA_HEADER); 1991 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 1992 UmbrellaHeader->getName()); 1993 } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) { 1994 Record.clear(); 1995 Record.push_back(SUBMODULE_UMBRELLA_DIR); 1996 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 1997 UmbrellaDir->getName()); 1998 } 1999 2000 // Emit the headers. 2001 for (unsigned I = 0, N = Mod->Headers.size(); I != N; ++I) { 2002 Record.clear(); 2003 Record.push_back(SUBMODULE_HEADER); 2004 Stream.EmitRecordWithBlob(HeaderAbbrev, Record, 2005 Mod->Headers[I]->getName()); 2006 } 2007 2008 // Emit the imports. 2009 if (!Mod->Imports.empty()) { 2010 Record.clear(); 2011 for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) { 2012 unsigned ImportedID = getSubmoduleID(Mod->Imports[I]); 2013 assert(ImportedID && "Unknown submodule!"); 2014 Record.push_back(ImportedID); 2015 } 2016 Stream.EmitRecord(SUBMODULE_IMPORTS, Record); 2017 } 2018 2019 // Emit the exports. 2020 if (!Mod->Exports.empty()) { 2021 Record.clear(); 2022 for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) { 2023 if (Module *Exported = Mod->Exports[I].getPointer()) { 2024 unsigned ExportedID = SubmoduleIDs[Exported]; 2025 assert(ExportedID > 0 && "Unknown submodule ID?"); 2026 Record.push_back(ExportedID); 2027 } else { 2028 Record.push_back(0); 2029 } 2030 2031 Record.push_back(Mod->Exports[I].getInt()); 2032 } 2033 Stream.EmitRecord(SUBMODULE_EXPORTS, Record); 2034 } 2035 2036 // Queue up the submodules of this module. 2037 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 2038 SubEnd = Mod->submodule_end(); 2039 Sub != SubEnd; ++Sub) 2040 Q.push(*Sub); 2041 } 2042 2043 Stream.ExitBlock(); 2044 2045 assert((NextSubmoduleID - FirstSubmoduleID 2046 == getNumberOfModules(WritingModule)) && "Wrong # of submodules"); 2047 } 2048 2049 serialization::SubmoduleID 2050 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) { 2051 if (Loc.isInvalid() || !WritingModule) 2052 return 0; // No submodule 2053 2054 // Find the module that owns this location. 2055 ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap(); 2056 Module *OwningMod 2057 = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager())); 2058 if (!OwningMod) 2059 return 0; 2060 2061 // Check whether this submodule is part of our own module. 2062 if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule)) 2063 return 0; 2064 2065 return getSubmoduleID(OwningMod); 2066 } 2067 2068 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag) { 2069 RecordData Record; 2070 for (DiagnosticsEngine::DiagStatePointsTy::const_iterator 2071 I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end(); 2072 I != E; ++I) { 2073 const DiagnosticsEngine::DiagStatePoint &point = *I; 2074 if (point.Loc.isInvalid()) 2075 continue; 2076 2077 Record.push_back(point.Loc.getRawEncoding()); 2078 for (DiagnosticsEngine::DiagState::const_iterator 2079 I = point.State->begin(), E = point.State->end(); I != E; ++I) { 2080 if (I->second.isPragma()) { 2081 Record.push_back(I->first); 2082 Record.push_back(I->second.getMapping()); 2083 } 2084 } 2085 Record.push_back(-1); // mark the end of the diag/map pairs for this 2086 // location. 2087 } 2088 2089 if (!Record.empty()) 2090 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 2091 } 2092 2093 void ASTWriter::WriteCXXBaseSpecifiersOffsets() { 2094 if (CXXBaseSpecifiersOffsets.empty()) 2095 return; 2096 2097 RecordData Record; 2098 2099 // Create a blob abbreviation for the C++ base specifiers offsets. 2100 using namespace llvm; 2101 2102 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2103 Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS)); 2104 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2105 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2106 unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2107 2108 // Write the base specifier offsets table. 2109 Record.clear(); 2110 Record.push_back(CXX_BASE_SPECIFIER_OFFSETS); 2111 Record.push_back(CXXBaseSpecifiersOffsets.size()); 2112 Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record, 2113 data(CXXBaseSpecifiersOffsets)); 2114 } 2115 2116 //===----------------------------------------------------------------------===// 2117 // Type Serialization 2118 //===----------------------------------------------------------------------===// 2119 2120 /// \brief Write the representation of a type to the AST stream. 2121 void ASTWriter::WriteType(QualType T) { 2122 TypeIdx &Idx = TypeIdxs[T]; 2123 if (Idx.getIndex() == 0) // we haven't seen this type before. 2124 Idx = TypeIdx(NextTypeID++); 2125 2126 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 2127 2128 // Record the offset for this type. 2129 unsigned Index = Idx.getIndex() - FirstTypeID; 2130 if (TypeOffsets.size() == Index) 2131 TypeOffsets.push_back(Stream.GetCurrentBitNo()); 2132 else if (TypeOffsets.size() < Index) { 2133 TypeOffsets.resize(Index + 1); 2134 TypeOffsets[Index] = Stream.GetCurrentBitNo(); 2135 } 2136 2137 RecordData Record; 2138 2139 // Emit the type's representation. 2140 ASTTypeWriter W(*this, Record); 2141 2142 if (T.hasLocalNonFastQualifiers()) { 2143 Qualifiers Qs = T.getLocalQualifiers(); 2144 AddTypeRef(T.getLocalUnqualifiedType(), Record); 2145 Record.push_back(Qs.getAsOpaqueValue()); 2146 W.Code = TYPE_EXT_QUAL; 2147 } else { 2148 switch (T->getTypeClass()) { 2149 // For all of the concrete, non-dependent types, call the 2150 // appropriate visitor function. 2151 #define TYPE(Class, Base) \ 2152 case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break; 2153 #define ABSTRACT_TYPE(Class, Base) 2154 #include "clang/AST/TypeNodes.def" 2155 } 2156 } 2157 2158 // Emit the serialized record. 2159 Stream.EmitRecord(W.Code, Record); 2160 2161 // Flush any expressions that were written as part of this type. 2162 FlushStmts(); 2163 } 2164 2165 //===----------------------------------------------------------------------===// 2166 // Declaration Serialization 2167 //===----------------------------------------------------------------------===// 2168 2169 /// \brief Write the block containing all of the declaration IDs 2170 /// lexically declared within the given DeclContext. 2171 /// 2172 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 2173 /// bistream, or 0 if no block was written. 2174 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 2175 DeclContext *DC) { 2176 if (DC->decls_empty()) 2177 return 0; 2178 2179 uint64_t Offset = Stream.GetCurrentBitNo(); 2180 RecordData Record; 2181 Record.push_back(DECL_CONTEXT_LEXICAL); 2182 SmallVector<KindDeclIDPair, 64> Decls; 2183 for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end(); 2184 D != DEnd; ++D) 2185 Decls.push_back(std::make_pair((*D)->getKind(), GetDeclRef(*D))); 2186 2187 ++NumLexicalDeclContexts; 2188 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls)); 2189 return Offset; 2190 } 2191 2192 void ASTWriter::WriteTypeDeclOffsets() { 2193 using namespace llvm; 2194 RecordData Record; 2195 2196 // Write the type offsets array 2197 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2198 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 2199 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 2200 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 2201 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 2202 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2203 Record.clear(); 2204 Record.push_back(TYPE_OFFSET); 2205 Record.push_back(TypeOffsets.size()); 2206 Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS); 2207 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets)); 2208 2209 // Write the declaration offsets array 2210 Abbrev = new BitCodeAbbrev(); 2211 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 2212 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 2213 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 2214 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 2215 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2216 Record.clear(); 2217 Record.push_back(DECL_OFFSET); 2218 Record.push_back(DeclOffsets.size()); 2219 Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS); 2220 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets)); 2221 } 2222 2223 void ASTWriter::WriteFileDeclIDsMap() { 2224 using namespace llvm; 2225 RecordData Record; 2226 2227 // Join the vectors of DeclIDs from all files. 2228 SmallVector<DeclID, 256> FileSortedIDs; 2229 for (FileDeclIDsTy::iterator 2230 FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) { 2231 DeclIDInFileInfo &Info = *FI->second; 2232 Info.FirstDeclIndex = FileSortedIDs.size(); 2233 for (LocDeclIDsTy::iterator 2234 DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI) 2235 FileSortedIDs.push_back(DI->second); 2236 } 2237 2238 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2239 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 2240 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2241 unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev); 2242 Record.push_back(FILE_SORTED_DECLS); 2243 Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs)); 2244 } 2245 2246 void ASTWriter::WriteComments() { 2247 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 2248 ArrayRef<RawComment *> RawComments = Context->Comments.getComments(); 2249 RecordData Record; 2250 for (ArrayRef<RawComment *>::iterator I = RawComments.begin(), 2251 E = RawComments.end(); 2252 I != E; ++I) { 2253 Record.clear(); 2254 AddSourceRange((*I)->getSourceRange(), Record); 2255 Record.push_back((*I)->getKind()); 2256 Record.push_back((*I)->isTrailingComment()); 2257 Record.push_back((*I)->isAlmostTrailingComment()); 2258 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 2259 } 2260 Stream.ExitBlock(); 2261 } 2262 2263 //===----------------------------------------------------------------------===// 2264 // Global Method Pool and Selector Serialization 2265 //===----------------------------------------------------------------------===// 2266 2267 namespace { 2268 // Trait used for the on-disk hash table used in the method pool. 2269 class ASTMethodPoolTrait { 2270 ASTWriter &Writer; 2271 2272 public: 2273 typedef Selector key_type; 2274 typedef key_type key_type_ref; 2275 2276 struct data_type { 2277 SelectorID ID; 2278 ObjCMethodList Instance, Factory; 2279 }; 2280 typedef const data_type& data_type_ref; 2281 2282 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 2283 2284 static unsigned ComputeHash(Selector Sel) { 2285 return serialization::ComputeHash(Sel); 2286 } 2287 2288 std::pair<unsigned,unsigned> 2289 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 2290 data_type_ref Methods) { 2291 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 2292 clang::io::Emit16(Out, KeyLen); 2293 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 2294 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2295 Method = Method->Next) 2296 if (Method->Method) 2297 DataLen += 4; 2298 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2299 Method = Method->Next) 2300 if (Method->Method) 2301 DataLen += 4; 2302 clang::io::Emit16(Out, DataLen); 2303 return std::make_pair(KeyLen, DataLen); 2304 } 2305 2306 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 2307 uint64_t Start = Out.tell(); 2308 assert((Start >> 32) == 0 && "Selector key offset too large"); 2309 Writer.SetSelectorOffset(Sel, Start); 2310 unsigned N = Sel.getNumArgs(); 2311 clang::io::Emit16(Out, N); 2312 if (N == 0) 2313 N = 1; 2314 for (unsigned I = 0; I != N; ++I) 2315 clang::io::Emit32(Out, 2316 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 2317 } 2318 2319 void EmitData(raw_ostream& Out, key_type_ref, 2320 data_type_ref Methods, unsigned DataLen) { 2321 uint64_t Start = Out.tell(); (void)Start; 2322 clang::io::Emit32(Out, Methods.ID); 2323 unsigned NumInstanceMethods = 0; 2324 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2325 Method = Method->Next) 2326 if (Method->Method) 2327 ++NumInstanceMethods; 2328 2329 unsigned NumFactoryMethods = 0; 2330 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2331 Method = Method->Next) 2332 if (Method->Method) 2333 ++NumFactoryMethods; 2334 2335 clang::io::Emit16(Out, NumInstanceMethods); 2336 clang::io::Emit16(Out, NumFactoryMethods); 2337 for (const ObjCMethodList *Method = &Methods.Instance; Method; 2338 Method = Method->Next) 2339 if (Method->Method) 2340 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2341 for (const ObjCMethodList *Method = &Methods.Factory; Method; 2342 Method = Method->Next) 2343 if (Method->Method) 2344 clang::io::Emit32(Out, Writer.getDeclID(Method->Method)); 2345 2346 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2347 } 2348 }; 2349 } // end anonymous namespace 2350 2351 /// \brief Write ObjC data: selectors and the method pool. 2352 /// 2353 /// The method pool contains both instance and factory methods, stored 2354 /// in an on-disk hash table indexed by the selector. The hash table also 2355 /// contains an empty entry for every other selector known to Sema. 2356 void ASTWriter::WriteSelectors(Sema &SemaRef) { 2357 using namespace llvm; 2358 2359 // Do we have to do anything at all? 2360 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 2361 return; 2362 unsigned NumTableEntries = 0; 2363 // Create and write out the blob that contains selectors and the method pool. 2364 { 2365 OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 2366 ASTMethodPoolTrait Trait(*this); 2367 2368 // Create the on-disk hash table representation. We walk through every 2369 // selector we've seen and look it up in the method pool. 2370 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 2371 for (llvm::DenseMap<Selector, SelectorID>::iterator 2372 I = SelectorIDs.begin(), E = SelectorIDs.end(); 2373 I != E; ++I) { 2374 Selector S = I->first; 2375 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 2376 ASTMethodPoolTrait::data_type Data = { 2377 I->second, 2378 ObjCMethodList(), 2379 ObjCMethodList() 2380 }; 2381 if (F != SemaRef.MethodPool.end()) { 2382 Data.Instance = F->second.first; 2383 Data.Factory = F->second.second; 2384 } 2385 // Only write this selector if it's not in an existing AST or something 2386 // changed. 2387 if (Chain && I->second < FirstSelectorID) { 2388 // Selector already exists. Did it change? 2389 bool changed = false; 2390 for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method; 2391 M = M->Next) { 2392 if (!M->Method->isFromASTFile()) 2393 changed = true; 2394 } 2395 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method; 2396 M = M->Next) { 2397 if (!M->Method->isFromASTFile()) 2398 changed = true; 2399 } 2400 if (!changed) 2401 continue; 2402 } else if (Data.Instance.Method || Data.Factory.Method) { 2403 // A new method pool entry. 2404 ++NumTableEntries; 2405 } 2406 Generator.insert(S, Data, Trait); 2407 } 2408 2409 // Create the on-disk hash table in a buffer. 2410 SmallString<4096> MethodPool; 2411 uint32_t BucketOffset; 2412 { 2413 ASTMethodPoolTrait Trait(*this); 2414 llvm::raw_svector_ostream Out(MethodPool); 2415 // Make sure that no bucket is at offset 0 2416 clang::io::Emit32(Out, 0); 2417 BucketOffset = Generator.Emit(Out, Trait); 2418 } 2419 2420 // Create a blob abbreviation 2421 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2422 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 2423 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2424 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2425 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2426 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev); 2427 2428 // Write the method pool 2429 RecordData Record; 2430 Record.push_back(METHOD_POOL); 2431 Record.push_back(BucketOffset); 2432 Record.push_back(NumTableEntries); 2433 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str()); 2434 2435 // Create a blob abbreviation for the selector table offsets. 2436 Abbrev = new BitCodeAbbrev(); 2437 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 2438 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 2439 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2440 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2441 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2442 2443 // Write the selector offsets table. 2444 Record.clear(); 2445 Record.push_back(SELECTOR_OFFSETS); 2446 Record.push_back(SelectorOffsets.size()); 2447 Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS); 2448 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 2449 data(SelectorOffsets)); 2450 } 2451 } 2452 2453 /// \brief Write the selectors referenced in @selector expression into AST file. 2454 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 2455 using namespace llvm; 2456 if (SemaRef.ReferencedSelectors.empty()) 2457 return; 2458 2459 RecordData Record; 2460 2461 // Note: this writes out all references even for a dependent AST. But it is 2462 // very tricky to fix, and given that @selector shouldn't really appear in 2463 // headers, probably not worth it. It's not a correctness issue. 2464 for (DenseMap<Selector, SourceLocation>::iterator S = 2465 SemaRef.ReferencedSelectors.begin(), 2466 E = SemaRef.ReferencedSelectors.end(); S != E; ++S) { 2467 Selector Sel = (*S).first; 2468 SourceLocation Loc = (*S).second; 2469 AddSelectorRef(Sel, Record); 2470 AddSourceLocation(Loc, Record); 2471 } 2472 Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record); 2473 } 2474 2475 //===----------------------------------------------------------------------===// 2476 // Identifier Table Serialization 2477 //===----------------------------------------------------------------------===// 2478 2479 namespace { 2480 class ASTIdentifierTableTrait { 2481 ASTWriter &Writer; 2482 Preprocessor &PP; 2483 IdentifierResolver &IdResolver; 2484 bool IsModule; 2485 2486 /// \brief Determines whether this is an "interesting" identifier 2487 /// that needs a full IdentifierInfo structure written into the hash 2488 /// table. 2489 bool isInterestingIdentifier(IdentifierInfo *II, MacroInfo *&Macro) { 2490 if (II->isPoisoned() || 2491 II->isExtensionToken() || 2492 II->getObjCOrBuiltinID() || 2493 II->hasRevertedTokenIDToIdentifier() || 2494 II->getFETokenInfo<void>()) 2495 return true; 2496 2497 return hasMacroDefinition(II, Macro); 2498 } 2499 2500 bool hasMacroDefinition(IdentifierInfo *II, MacroInfo *&Macro) { 2501 if (!II->hasMacroDefinition()) 2502 return false; 2503 2504 if (Macro || (Macro = PP.getMacroInfo(II))) 2505 return !Macro->isBuiltinMacro() && (!IsModule || Macro->isPublic()); 2506 2507 return false; 2508 } 2509 2510 public: 2511 typedef IdentifierInfo* key_type; 2512 typedef key_type key_type_ref; 2513 2514 typedef IdentID data_type; 2515 typedef data_type data_type_ref; 2516 2517 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 2518 IdentifierResolver &IdResolver, bool IsModule) 2519 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { } 2520 2521 static unsigned ComputeHash(const IdentifierInfo* II) { 2522 return llvm::HashString(II->getName()); 2523 } 2524 2525 std::pair<unsigned,unsigned> 2526 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 2527 unsigned KeyLen = II->getLength() + 1; 2528 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 2529 MacroInfo *Macro = 0; 2530 if (isInterestingIdentifier(II, Macro)) { 2531 DataLen += 2; // 2 bytes for builtin ID, flags 2532 if (hasMacroDefinition(II, Macro)) 2533 DataLen += 8; 2534 2535 for (IdentifierResolver::iterator D = IdResolver.begin(II), 2536 DEnd = IdResolver.end(); 2537 D != DEnd; ++D) 2538 DataLen += sizeof(DeclID); 2539 } 2540 clang::io::Emit16(Out, DataLen); 2541 // We emit the key length after the data length so that every 2542 // string is preceded by a 16-bit length. This matches the PTH 2543 // format for storing identifiers. 2544 clang::io::Emit16(Out, KeyLen); 2545 return std::make_pair(KeyLen, DataLen); 2546 } 2547 2548 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 2549 unsigned KeyLen) { 2550 // Record the location of the key data. This is used when generating 2551 // the mapping from persistent IDs to strings. 2552 Writer.SetIdentifierOffset(II, Out.tell()); 2553 Out.write(II->getNameStart(), KeyLen); 2554 } 2555 2556 void EmitData(raw_ostream& Out, IdentifierInfo* II, 2557 IdentID ID, unsigned) { 2558 MacroInfo *Macro = 0; 2559 if (!isInterestingIdentifier(II, Macro)) { 2560 clang::io::Emit32(Out, ID << 1); 2561 return; 2562 } 2563 2564 clang::io::Emit32(Out, (ID << 1) | 0x01); 2565 uint32_t Bits = 0; 2566 bool HasMacroDefinition = hasMacroDefinition(II, Macro); 2567 Bits = (uint32_t)II->getObjCOrBuiltinID(); 2568 assert((Bits & 0x7ff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 2569 Bits = (Bits << 1) | unsigned(HasMacroDefinition); 2570 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 2571 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 2572 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 2573 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 2574 clang::io::Emit16(Out, Bits); 2575 2576 if (HasMacroDefinition) { 2577 clang::io::Emit32(Out, Writer.getMacroOffset(II)); 2578 clang::io::Emit32(Out, 2579 Writer.inferSubmoduleIDFromLocation(Macro->getDefinitionLoc())); 2580 } 2581 2582 // Emit the declaration IDs in reverse order, because the 2583 // IdentifierResolver provides the declarations as they would be 2584 // visible (e.g., the function "stat" would come before the struct 2585 // "stat"), but the ASTReader adds declarations to the end of the list 2586 // (so we need to see the struct "status" before the function "status"). 2587 // Only emit declarations that aren't from a chained PCH, though. 2588 SmallVector<Decl *, 16> Decls(IdResolver.begin(II), 2589 IdResolver.end()); 2590 for (SmallVector<Decl *, 16>::reverse_iterator D = Decls.rbegin(), 2591 DEnd = Decls.rend(); 2592 D != DEnd; ++D) 2593 clang::io::Emit32(Out, Writer.getDeclID(*D)); 2594 } 2595 }; 2596 } // end anonymous namespace 2597 2598 /// \brief Write the identifier table into the AST file. 2599 /// 2600 /// The identifier table consists of a blob containing string data 2601 /// (the actual identifiers themselves) and a separate "offsets" index 2602 /// that maps identifier IDs to locations within the blob. 2603 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 2604 IdentifierResolver &IdResolver, 2605 bool IsModule) { 2606 using namespace llvm; 2607 2608 // Create and write out the blob that contains the identifier 2609 // strings. 2610 { 2611 OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 2612 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2613 2614 // Look for any identifiers that were named while processing the 2615 // headers, but are otherwise not needed. We add these to the hash 2616 // table to enable checking of the predefines buffer in the case 2617 // where the user adds new macro definitions when building the AST 2618 // file. 2619 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 2620 IDEnd = PP.getIdentifierTable().end(); 2621 ID != IDEnd; ++ID) 2622 getIdentifierRef(ID->second); 2623 2624 // Create the on-disk hash table representation. We only store offsets 2625 // for identifiers that appear here for the first time. 2626 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 2627 for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator 2628 ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end(); 2629 ID != IDEnd; ++ID) { 2630 assert(ID->first && "NULL identifier in identifier table"); 2631 if (!Chain || !ID->first->isFromAST() || 2632 ID->first->hasChangedSinceDeserialization()) 2633 Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second, 2634 Trait); 2635 } 2636 2637 // Create the on-disk hash table in a buffer. 2638 SmallString<4096> IdentifierTable; 2639 uint32_t BucketOffset; 2640 { 2641 ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule); 2642 llvm::raw_svector_ostream Out(IdentifierTable); 2643 // Make sure that no bucket is at offset 0 2644 clang::io::Emit32(Out, 0); 2645 BucketOffset = Generator.Emit(Out, Trait); 2646 } 2647 2648 // Create a blob abbreviation 2649 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2650 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 2651 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2652 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2653 unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev); 2654 2655 // Write the identifier table 2656 RecordData Record; 2657 Record.push_back(IDENTIFIER_TABLE); 2658 Record.push_back(BucketOffset); 2659 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str()); 2660 } 2661 2662 // Write the offsets table for identifier IDs. 2663 BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2664 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 2665 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 2666 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2667 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2668 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev); 2669 2670 RecordData Record; 2671 Record.push_back(IDENTIFIER_OFFSET); 2672 Record.push_back(IdentifierOffsets.size()); 2673 Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS); 2674 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 2675 data(IdentifierOffsets)); 2676 } 2677 2678 //===----------------------------------------------------------------------===// 2679 // DeclContext's Name Lookup Table Serialization 2680 //===----------------------------------------------------------------------===// 2681 2682 namespace { 2683 // Trait used for the on-disk hash table used in the method pool. 2684 class ASTDeclContextNameLookupTrait { 2685 ASTWriter &Writer; 2686 2687 public: 2688 typedef DeclarationName key_type; 2689 typedef key_type key_type_ref; 2690 2691 typedef DeclContext::lookup_result data_type; 2692 typedef const data_type& data_type_ref; 2693 2694 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 2695 2696 unsigned ComputeHash(DeclarationName Name) { 2697 llvm::FoldingSetNodeID ID; 2698 ID.AddInteger(Name.getNameKind()); 2699 2700 switch (Name.getNameKind()) { 2701 case DeclarationName::Identifier: 2702 ID.AddString(Name.getAsIdentifierInfo()->getName()); 2703 break; 2704 case DeclarationName::ObjCZeroArgSelector: 2705 case DeclarationName::ObjCOneArgSelector: 2706 case DeclarationName::ObjCMultiArgSelector: 2707 ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector())); 2708 break; 2709 case DeclarationName::CXXConstructorName: 2710 case DeclarationName::CXXDestructorName: 2711 case DeclarationName::CXXConversionFunctionName: 2712 break; 2713 case DeclarationName::CXXOperatorName: 2714 ID.AddInteger(Name.getCXXOverloadedOperator()); 2715 break; 2716 case DeclarationName::CXXLiteralOperatorName: 2717 ID.AddString(Name.getCXXLiteralIdentifier()->getName()); 2718 case DeclarationName::CXXUsingDirective: 2719 break; 2720 } 2721 2722 return ID.ComputeHash(); 2723 } 2724 2725 std::pair<unsigned,unsigned> 2726 EmitKeyDataLength(raw_ostream& Out, DeclarationName Name, 2727 data_type_ref Lookup) { 2728 unsigned KeyLen = 1; 2729 switch (Name.getNameKind()) { 2730 case DeclarationName::Identifier: 2731 case DeclarationName::ObjCZeroArgSelector: 2732 case DeclarationName::ObjCOneArgSelector: 2733 case DeclarationName::ObjCMultiArgSelector: 2734 case DeclarationName::CXXLiteralOperatorName: 2735 KeyLen += 4; 2736 break; 2737 case DeclarationName::CXXOperatorName: 2738 KeyLen += 1; 2739 break; 2740 case DeclarationName::CXXConstructorName: 2741 case DeclarationName::CXXDestructorName: 2742 case DeclarationName::CXXConversionFunctionName: 2743 case DeclarationName::CXXUsingDirective: 2744 break; 2745 } 2746 clang::io::Emit16(Out, KeyLen); 2747 2748 // 2 bytes for num of decls and 4 for each DeclID. 2749 unsigned DataLen = 2 + 4 * (Lookup.second - Lookup.first); 2750 clang::io::Emit16(Out, DataLen); 2751 2752 return std::make_pair(KeyLen, DataLen); 2753 } 2754 2755 void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) { 2756 using namespace clang::io; 2757 2758 assert(Name.getNameKind() < 0x100 && "Invalid name kind ?"); 2759 Emit8(Out, Name.getNameKind()); 2760 switch (Name.getNameKind()) { 2761 case DeclarationName::Identifier: 2762 Emit32(Out, Writer.getIdentifierRef(Name.getAsIdentifierInfo())); 2763 break; 2764 case DeclarationName::ObjCZeroArgSelector: 2765 case DeclarationName::ObjCOneArgSelector: 2766 case DeclarationName::ObjCMultiArgSelector: 2767 Emit32(Out, Writer.getSelectorRef(Name.getObjCSelector())); 2768 break; 2769 case DeclarationName::CXXOperatorName: 2770 assert(Name.getCXXOverloadedOperator() < 0x100 && "Invalid operator ?"); 2771 Emit8(Out, Name.getCXXOverloadedOperator()); 2772 break; 2773 case DeclarationName::CXXLiteralOperatorName: 2774 Emit32(Out, Writer.getIdentifierRef(Name.getCXXLiteralIdentifier())); 2775 break; 2776 case DeclarationName::CXXConstructorName: 2777 case DeclarationName::CXXDestructorName: 2778 case DeclarationName::CXXConversionFunctionName: 2779 case DeclarationName::CXXUsingDirective: 2780 break; 2781 } 2782 } 2783 2784 void EmitData(raw_ostream& Out, key_type_ref, 2785 data_type Lookup, unsigned DataLen) { 2786 uint64_t Start = Out.tell(); (void)Start; 2787 clang::io::Emit16(Out, Lookup.second - Lookup.first); 2788 for (; Lookup.first != Lookup.second; ++Lookup.first) 2789 clang::io::Emit32(Out, Writer.GetDeclRef(*Lookup.first)); 2790 2791 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 2792 } 2793 }; 2794 } // end anonymous namespace 2795 2796 /// \brief Write the block containing all of the declaration IDs 2797 /// visible from the given DeclContext. 2798 /// 2799 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 2800 /// bitstream, or 0 if no block was written. 2801 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 2802 DeclContext *DC) { 2803 if (DC->getPrimaryContext() != DC) 2804 return 0; 2805 2806 // Since there is no name lookup into functions or methods, don't bother to 2807 // build a visible-declarations table for these entities. 2808 if (DC->isFunctionOrMethod()) 2809 return 0; 2810 2811 // If not in C++, we perform name lookup for the translation unit via the 2812 // IdentifierInfo chains, don't bother to build a visible-declarations table. 2813 // FIXME: In C++ we need the visible declarations in order to "see" the 2814 // friend declarations, is there a way to do this without writing the table ? 2815 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 2816 return 0; 2817 2818 // Serialize the contents of the mapping used for lookup. Note that, 2819 // although we have two very different code paths, the serialized 2820 // representation is the same for both cases: a declaration name, 2821 // followed by a size, followed by references to the visible 2822 // declarations that have that name. 2823 uint64_t Offset = Stream.GetCurrentBitNo(); 2824 StoredDeclsMap *Map = DC->buildLookup(); 2825 if (!Map || Map->empty()) 2826 return 0; 2827 2828 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2829 ASTDeclContextNameLookupTrait Trait(*this); 2830 2831 // Create the on-disk hash table representation. 2832 DeclarationName ConversionName; 2833 llvm::SmallVector<NamedDecl *, 4> ConversionDecls; 2834 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2835 D != DEnd; ++D) { 2836 DeclarationName Name = D->first; 2837 DeclContext::lookup_result Result = D->second.getLookupResult(); 2838 if (Result.first != Result.second) { 2839 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 2840 // Hash all conversion function names to the same name. The actual 2841 // type information in conversion function name is not used in the 2842 // key (since such type information is not stable across different 2843 // modules), so the intended effect is to coalesce all of the conversion 2844 // functions under a single key. 2845 if (!ConversionName) 2846 ConversionName = Name; 2847 ConversionDecls.append(Result.first, Result.second); 2848 continue; 2849 } 2850 2851 Generator.insert(Name, Result, Trait); 2852 } 2853 } 2854 2855 // Add the conversion functions 2856 if (!ConversionDecls.empty()) { 2857 Generator.insert(ConversionName, 2858 DeclContext::lookup_result(ConversionDecls.begin(), 2859 ConversionDecls.end()), 2860 Trait); 2861 } 2862 2863 // Create the on-disk hash table in a buffer. 2864 SmallString<4096> LookupTable; 2865 uint32_t BucketOffset; 2866 { 2867 llvm::raw_svector_ostream Out(LookupTable); 2868 // Make sure that no bucket is at offset 0 2869 clang::io::Emit32(Out, 0); 2870 BucketOffset = Generator.Emit(Out, Trait); 2871 } 2872 2873 // Write the lookup table 2874 RecordData Record; 2875 Record.push_back(DECL_CONTEXT_VISIBLE); 2876 Record.push_back(BucketOffset); 2877 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 2878 LookupTable.str()); 2879 2880 Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record); 2881 ++NumVisibleDeclContexts; 2882 return Offset; 2883 } 2884 2885 /// \brief Write an UPDATE_VISIBLE block for the given context. 2886 /// 2887 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 2888 /// DeclContext in a dependent AST file. As such, they only exist for the TU 2889 /// (in C++), for namespaces, and for classes with forward-declared unscoped 2890 /// enumeration members (in C++11). 2891 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 2892 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(DC->getLookupPtr()); 2893 if (!Map || Map->empty()) 2894 return; 2895 2896 OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait> Generator; 2897 ASTDeclContextNameLookupTrait Trait(*this); 2898 2899 // Create the hash table. 2900 for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end(); 2901 D != DEnd; ++D) { 2902 DeclarationName Name = D->first; 2903 DeclContext::lookup_result Result = D->second.getLookupResult(); 2904 // For any name that appears in this table, the results are complete, i.e. 2905 // they overwrite results from previous PCHs. Merging is always a mess. 2906 if (Result.first != Result.second) 2907 Generator.insert(Name, Result, Trait); 2908 } 2909 2910 // Create the on-disk hash table in a buffer. 2911 SmallString<4096> LookupTable; 2912 uint32_t BucketOffset; 2913 { 2914 llvm::raw_svector_ostream Out(LookupTable); 2915 // Make sure that no bucket is at offset 0 2916 clang::io::Emit32(Out, 0); 2917 BucketOffset = Generator.Emit(Out, Trait); 2918 } 2919 2920 // Write the lookup table 2921 RecordData Record; 2922 Record.push_back(UPDATE_VISIBLE); 2923 Record.push_back(getDeclID(cast<Decl>(DC))); 2924 Record.push_back(BucketOffset); 2925 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str()); 2926 } 2927 2928 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 2929 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 2930 RecordData Record; 2931 Record.push_back(Opts.fp_contract); 2932 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 2933 } 2934 2935 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 2936 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 2937 if (!SemaRef.Context.getLangOpts().OpenCL) 2938 return; 2939 2940 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 2941 RecordData Record; 2942 #define OPENCLEXT(nm) Record.push_back(Opts.nm); 2943 #include "clang/Basic/OpenCLExtensions.def" 2944 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 2945 } 2946 2947 void ASTWriter::WriteRedeclarations() { 2948 RecordData LocalRedeclChains; 2949 SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap; 2950 2951 for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) { 2952 Decl *First = Redeclarations[I]; 2953 assert(First->getPreviousDecl() == 0 && "Not the first declaration?"); 2954 2955 Decl *MostRecent = First->getMostRecentDecl(); 2956 2957 // If we only have a single declaration, there is no point in storing 2958 // a redeclaration chain. 2959 if (First == MostRecent) 2960 continue; 2961 2962 unsigned Offset = LocalRedeclChains.size(); 2963 unsigned Size = 0; 2964 LocalRedeclChains.push_back(0); // Placeholder for the size. 2965 2966 // Collect the set of local redeclarations of this declaration. 2967 for (Decl *Prev = MostRecent; Prev != First; 2968 Prev = Prev->getPreviousDecl()) { 2969 if (!Prev->isFromASTFile()) { 2970 AddDeclRef(Prev, LocalRedeclChains); 2971 ++Size; 2972 } 2973 } 2974 LocalRedeclChains[Offset] = Size; 2975 2976 // Reverse the set of local redeclarations, so that we store them in 2977 // order (since we found them in reverse order). 2978 std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end()); 2979 2980 // Add the mapping from the first ID to the set of local declarations. 2981 LocalRedeclarationsInfo Info = { getDeclID(First), Offset }; 2982 LocalRedeclsMap.push_back(Info); 2983 2984 assert(N == Redeclarations.size() && 2985 "Deserialized a declaration we shouldn't have"); 2986 } 2987 2988 if (LocalRedeclChains.empty()) 2989 return; 2990 2991 // Sort the local redeclarations map by the first declaration ID, 2992 // since the reader will be performing binary searches on this information. 2993 llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end()); 2994 2995 // Emit the local redeclarations map. 2996 using namespace llvm; 2997 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 2998 Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP)); 2999 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 3000 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3001 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 3002 3003 RecordData Record; 3004 Record.push_back(LOCAL_REDECLARATIONS_MAP); 3005 Record.push_back(LocalRedeclsMap.size()); 3006 Stream.EmitRecordWithBlob(AbbrevID, Record, 3007 reinterpret_cast<char*>(LocalRedeclsMap.data()), 3008 LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo)); 3009 3010 // Emit the redeclaration chains. 3011 Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains); 3012 } 3013 3014 void ASTWriter::WriteObjCCategories() { 3015 llvm::SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 3016 RecordData Categories; 3017 3018 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 3019 unsigned Size = 0; 3020 unsigned StartIndex = Categories.size(); 3021 3022 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 3023 3024 // Allocate space for the size. 3025 Categories.push_back(0); 3026 3027 // Add the categories. 3028 for (ObjCCategoryDecl *Cat = Class->getCategoryList(); 3029 Cat; Cat = Cat->getNextClassCategory(), ++Size) { 3030 assert(getDeclID(Cat) != 0 && "Bogus category"); 3031 AddDeclRef(Cat, Categories); 3032 } 3033 3034 // Update the size. 3035 Categories[StartIndex] = Size; 3036 3037 // Record this interface -> category map. 3038 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 3039 CategoriesMap.push_back(CatInfo); 3040 } 3041 3042 // Sort the categories map by the definition ID, since the reader will be 3043 // performing binary searches on this information. 3044 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 3045 3046 // Emit the categories map. 3047 using namespace llvm; 3048 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3049 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 3050 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 3051 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3052 unsigned AbbrevID = Stream.EmitAbbrev(Abbrev); 3053 3054 RecordData Record; 3055 Record.push_back(OBJC_CATEGORIES_MAP); 3056 Record.push_back(CategoriesMap.size()); 3057 Stream.EmitRecordWithBlob(AbbrevID, Record, 3058 reinterpret_cast<char*>(CategoriesMap.data()), 3059 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 3060 3061 // Emit the category lists. 3062 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 3063 } 3064 3065 void ASTWriter::WriteMergedDecls() { 3066 if (!Chain || Chain->MergedDecls.empty()) 3067 return; 3068 3069 RecordData Record; 3070 for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(), 3071 IEnd = Chain->MergedDecls.end(); 3072 I != IEnd; ++I) { 3073 DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID() 3074 : getDeclID(I->first); 3075 assert(CanonID && "Merged declaration not known?"); 3076 3077 Record.push_back(CanonID); 3078 Record.push_back(I->second.size()); 3079 Record.append(I->second.begin(), I->second.end()); 3080 } 3081 Stream.EmitRecord(MERGED_DECLARATIONS, Record); 3082 } 3083 3084 //===----------------------------------------------------------------------===// 3085 // General Serialization Routines 3086 //===----------------------------------------------------------------------===// 3087 3088 /// \brief Write a record containing the given attributes. 3089 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs, 3090 RecordDataImpl &Record) { 3091 Record.push_back(Attrs.size()); 3092 for (ArrayRef<const Attr *>::iterator i = Attrs.begin(), 3093 e = Attrs.end(); i != e; ++i){ 3094 const Attr *A = *i; 3095 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 3096 AddSourceRange(A->getRange(), Record); 3097 3098 #include "clang/Serialization/AttrPCHWrite.inc" 3099 3100 } 3101 } 3102 3103 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 3104 Record.push_back(Str.size()); 3105 Record.insert(Record.end(), Str.begin(), Str.end()); 3106 } 3107 3108 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 3109 RecordDataImpl &Record) { 3110 Record.push_back(Version.getMajor()); 3111 if (llvm::Optional<unsigned> Minor = Version.getMinor()) 3112 Record.push_back(*Minor + 1); 3113 else 3114 Record.push_back(0); 3115 if (llvm::Optional<unsigned> Subminor = Version.getSubminor()) 3116 Record.push_back(*Subminor + 1); 3117 else 3118 Record.push_back(0); 3119 } 3120 3121 /// \brief Note that the identifier II occurs at the given offset 3122 /// within the identifier table. 3123 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 3124 IdentID ID = IdentifierIDs[II]; 3125 // Only store offsets new to this AST file. Other identifier names are looked 3126 // up earlier in the chain and thus don't need an offset. 3127 if (ID >= FirstIdentID) 3128 IdentifierOffsets[ID - FirstIdentID] = Offset; 3129 } 3130 3131 /// \brief Note that the selector Sel occurs at the given offset 3132 /// within the method pool/selector table. 3133 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 3134 unsigned ID = SelectorIDs[Sel]; 3135 assert(ID && "Unknown selector"); 3136 // Don't record offsets for selectors that are also available in a different 3137 // file. 3138 if (ID < FirstSelectorID) 3139 return; 3140 SelectorOffsets[ID - FirstSelectorID] = Offset; 3141 } 3142 3143 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream) 3144 : Stream(Stream), Context(0), PP(0), Chain(0), WritingModule(0), 3145 WritingAST(false), DoneWritingDeclsAndTypes(false), 3146 ASTHasCompilerErrors(false), 3147 FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID), 3148 FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID), 3149 FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID), 3150 FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS), 3151 NextSubmoduleID(FirstSubmoduleID), 3152 FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID), 3153 CollectedStmts(&StmtsToEmit), 3154 NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0), 3155 NumVisibleDeclContexts(0), 3156 NextCXXBaseSpecifiersID(1), 3157 DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0), 3158 DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0), 3159 DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0), 3160 DeclRecordAbbrev(0), IntegerLiteralAbbrev(0), 3161 DeclTypedefAbbrev(0), 3162 DeclVarAbbrev(0), DeclFieldAbbrev(0), 3163 DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0) 3164 { 3165 } 3166 3167 ASTWriter::~ASTWriter() { 3168 for (FileDeclIDsTy::iterator 3169 I = FileDeclIDs.begin(), E = FileDeclIDs.end(); I != E; ++I) 3170 delete I->second; 3171 } 3172 3173 void ASTWriter::WriteAST(Sema &SemaRef, MemorizeStatCalls *StatCalls, 3174 const std::string &OutputFile, 3175 Module *WritingModule, StringRef isysroot, 3176 bool hasErrors) { 3177 WritingAST = true; 3178 3179 ASTHasCompilerErrors = hasErrors; 3180 3181 // Emit the file header. 3182 Stream.Emit((unsigned)'C', 8); 3183 Stream.Emit((unsigned)'P', 8); 3184 Stream.Emit((unsigned)'C', 8); 3185 Stream.Emit((unsigned)'H', 8); 3186 3187 WriteBlockInfoBlock(); 3188 3189 Context = &SemaRef.Context; 3190 PP = &SemaRef.PP; 3191 this->WritingModule = WritingModule; 3192 WriteASTCore(SemaRef, StatCalls, isysroot, OutputFile, WritingModule); 3193 Context = 0; 3194 PP = 0; 3195 this->WritingModule = 0; 3196 3197 WritingAST = false; 3198 } 3199 3200 template<typename Vector> 3201 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 3202 ASTWriter::RecordData &Record) { 3203 for (typename Vector::iterator I = Vec.begin(0, true), E = Vec.end(); 3204 I != E; ++I) { 3205 Writer.AddDeclRef(*I, Record); 3206 } 3207 } 3208 3209 void ASTWriter::WriteASTCore(Sema &SemaRef, MemorizeStatCalls *StatCalls, 3210 StringRef isysroot, 3211 const std::string &OutputFile, 3212 Module *WritingModule) { 3213 using namespace llvm; 3214 3215 // Make sure that the AST reader knows to finalize itself. 3216 if (Chain) 3217 Chain->finalizeForWriting(); 3218 3219 ASTContext &Context = SemaRef.Context; 3220 Preprocessor &PP = SemaRef.PP; 3221 3222 // Set up predefined declaration IDs. 3223 DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID; 3224 if (Context.ObjCIdDecl) 3225 DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID; 3226 if (Context.ObjCSelDecl) 3227 DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID; 3228 if (Context.ObjCClassDecl) 3229 DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID; 3230 if (Context.ObjCProtocolClassDecl) 3231 DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID; 3232 if (Context.Int128Decl) 3233 DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID; 3234 if (Context.UInt128Decl) 3235 DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID; 3236 if (Context.ObjCInstanceTypeDecl) 3237 DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID; 3238 if (Context.BuiltinVaListDecl) 3239 DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID; 3240 3241 if (!Chain) { 3242 // Make sure that we emit IdentifierInfos (and any attached 3243 // declarations) for builtins. We don't need to do this when we're 3244 // emitting chained PCH files, because all of the builtins will be 3245 // in the original PCH file. 3246 // FIXME: Modules won't like this at all. 3247 IdentifierTable &Table = PP.getIdentifierTable(); 3248 SmallVector<const char *, 32> BuiltinNames; 3249 Context.BuiltinInfo.GetBuiltinNames(BuiltinNames, 3250 Context.getLangOpts().NoBuiltin); 3251 for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I) 3252 getIdentifierRef(&Table.get(BuiltinNames[I])); 3253 } 3254 3255 // If there are any out-of-date identifiers, bring them up to date. 3256 if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) { 3257 for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(), 3258 IDEnd = PP.getIdentifierTable().end(); 3259 ID != IDEnd; ++ID) 3260 if (ID->second->isOutOfDate()) 3261 ExtSource->updateOutOfDateIdentifier(*ID->second); 3262 } 3263 3264 // Build a record containing all of the tentative definitions in this file, in 3265 // TentativeDefinitions order. Generally, this record will be empty for 3266 // headers. 3267 RecordData TentativeDefinitions; 3268 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 3269 3270 // Build a record containing all of the file scoped decls in this file. 3271 RecordData UnusedFileScopedDecls; 3272 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 3273 UnusedFileScopedDecls); 3274 3275 // Build a record containing all of the delegating constructors we still need 3276 // to resolve. 3277 RecordData DelegatingCtorDecls; 3278 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 3279 3280 // Write the set of weak, undeclared identifiers. We always write the 3281 // entire table, since later PCH files in a PCH chain are only interested in 3282 // the results at the end of the chain. 3283 RecordData WeakUndeclaredIdentifiers; 3284 if (!SemaRef.WeakUndeclaredIdentifiers.empty()) { 3285 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 3286 I = SemaRef.WeakUndeclaredIdentifiers.begin(), 3287 E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) { 3288 AddIdentifierRef(I->first, WeakUndeclaredIdentifiers); 3289 AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers); 3290 AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers); 3291 WeakUndeclaredIdentifiers.push_back(I->second.getUsed()); 3292 } 3293 } 3294 3295 // Build a record containing all of the locally-scoped external 3296 // declarations in this header file. Generally, this record will be 3297 // empty. 3298 RecordData LocallyScopedExternalDecls; 3299 // FIXME: This is filling in the AST file in densemap order which is 3300 // nondeterminstic! 3301 for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 3302 TD = SemaRef.LocallyScopedExternalDecls.begin(), 3303 TDEnd = SemaRef.LocallyScopedExternalDecls.end(); 3304 TD != TDEnd; ++TD) { 3305 if (!TD->second->isFromASTFile()) 3306 AddDeclRef(TD->second, LocallyScopedExternalDecls); 3307 } 3308 3309 // Build a record containing all of the ext_vector declarations. 3310 RecordData ExtVectorDecls; 3311 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 3312 3313 // Build a record containing all of the VTable uses information. 3314 RecordData VTableUses; 3315 if (!SemaRef.VTableUses.empty()) { 3316 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 3317 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 3318 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 3319 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 3320 } 3321 } 3322 3323 // Build a record containing all of dynamic classes declarations. 3324 RecordData DynamicClasses; 3325 AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses); 3326 3327 // Build a record containing all of pending implicit instantiations. 3328 RecordData PendingInstantiations; 3329 for (std::deque<Sema::PendingImplicitInstantiation>::iterator 3330 I = SemaRef.PendingInstantiations.begin(), 3331 N = SemaRef.PendingInstantiations.end(); I != N; ++I) { 3332 AddDeclRef(I->first, PendingInstantiations); 3333 AddSourceLocation(I->second, PendingInstantiations); 3334 } 3335 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 3336 "There are local ones at end of translation unit!"); 3337 3338 // Build a record containing some declaration references. 3339 RecordData SemaDeclRefs; 3340 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) { 3341 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 3342 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 3343 } 3344 3345 RecordData CUDASpecialDeclRefs; 3346 if (Context.getcudaConfigureCallDecl()) { 3347 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 3348 } 3349 3350 // Build a record containing all of the known namespaces. 3351 RecordData KnownNamespaces; 3352 for (llvm::DenseMap<NamespaceDecl*, bool>::iterator 3353 I = SemaRef.KnownNamespaces.begin(), 3354 IEnd = SemaRef.KnownNamespaces.end(); 3355 I != IEnd; ++I) { 3356 if (!I->second) 3357 AddDeclRef(I->first, KnownNamespaces); 3358 } 3359 3360 // Write the remaining AST contents. 3361 RecordData Record; 3362 Stream.EnterSubblock(AST_BLOCK_ID, 5); 3363 WriteMetadata(Context, isysroot, OutputFile); 3364 WriteLanguageOptions(Context.getLangOpts()); 3365 if (StatCalls && isysroot.empty()) 3366 WriteStatCache(*StatCalls); 3367 3368 // Create a lexical update block containing all of the declarations in the 3369 // translation unit that do not come from other AST files. 3370 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 3371 SmallVector<KindDeclIDPair, 64> NewGlobalDecls; 3372 for (DeclContext::decl_iterator I = TU->noload_decls_begin(), 3373 E = TU->noload_decls_end(); 3374 I != E; ++I) { 3375 if (!(*I)->isFromASTFile()) 3376 NewGlobalDecls.push_back(std::make_pair((*I)->getKind(), GetDeclRef(*I))); 3377 } 3378 3379 llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev(); 3380 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 3381 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3382 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv); 3383 Record.clear(); 3384 Record.push_back(TU_UPDATE_LEXICAL); 3385 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 3386 data(NewGlobalDecls)); 3387 3388 // And a visible updates block for the translation unit. 3389 Abv = new llvm::BitCodeAbbrev(); 3390 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 3391 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 3392 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32)); 3393 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 3394 UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv); 3395 WriteDeclContextVisibleUpdate(TU); 3396 3397 // If the translation unit has an anonymous namespace, and we don't already 3398 // have an update block for it, write it as an update block. 3399 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 3400 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 3401 if (Record.empty()) { 3402 Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE); 3403 Record.push_back(reinterpret_cast<uint64_t>(NS)); 3404 } 3405 } 3406 3407 // Make sure visible decls, added to DeclContexts previously loaded from 3408 // an AST file, are registered for serialization. 3409 for (SmallVector<const Decl *, 16>::iterator 3410 I = UpdatingVisibleDecls.begin(), 3411 E = UpdatingVisibleDecls.end(); I != E; ++I) { 3412 GetDeclRef(*I); 3413 } 3414 3415 // Resolve any declaration pointers within the declaration updates block. 3416 ResolveDeclUpdatesBlocks(); 3417 3418 // Form the record of special types. 3419 RecordData SpecialTypes; 3420 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 3421 AddTypeRef(Context.getFILEType(), SpecialTypes); 3422 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 3423 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 3424 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 3425 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 3426 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 3427 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 3428 3429 // Keep writing types and declarations until all types and 3430 // declarations have been written. 3431 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3432 WriteDeclsBlockAbbrevs(); 3433 for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(), 3434 E = DeclsToRewrite.end(); 3435 I != E; ++I) 3436 DeclTypesToEmit.push(const_cast<Decl*>(*I)); 3437 while (!DeclTypesToEmit.empty()) { 3438 DeclOrType DOT = DeclTypesToEmit.front(); 3439 DeclTypesToEmit.pop(); 3440 if (DOT.isType()) 3441 WriteType(DOT.getType()); 3442 else 3443 WriteDecl(Context, DOT.getDecl()); 3444 } 3445 Stream.ExitBlock(); 3446 3447 DoneWritingDeclsAndTypes = true; 3448 3449 WriteFileDeclIDsMap(); 3450 WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot); 3451 WriteComments(); 3452 3453 if (Chain) { 3454 // Write the mapping information describing our module dependencies and how 3455 // each of those modules were mapped into our own offset/ID space, so that 3456 // the reader can build the appropriate mapping to its own offset/ID space. 3457 // The map consists solely of a blob with the following format: 3458 // *(module-name-len:i16 module-name:len*i8 3459 // source-location-offset:i32 3460 // identifier-id:i32 3461 // preprocessed-entity-id:i32 3462 // macro-definition-id:i32 3463 // submodule-id:i32 3464 // selector-id:i32 3465 // declaration-id:i32 3466 // c++-base-specifiers-id:i32 3467 // type-id:i32) 3468 // 3469 llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); 3470 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 3471 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3472 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev); 3473 SmallString<2048> Buffer; 3474 { 3475 llvm::raw_svector_ostream Out(Buffer); 3476 for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(), 3477 MEnd = Chain->ModuleMgr.end(); 3478 M != MEnd; ++M) { 3479 StringRef FileName = (*M)->FileName; 3480 io::Emit16(Out, FileName.size()); 3481 Out.write(FileName.data(), FileName.size()); 3482 io::Emit32(Out, (*M)->SLocEntryBaseOffset); 3483 io::Emit32(Out, (*M)->BaseIdentifierID); 3484 io::Emit32(Out, (*M)->BasePreprocessedEntityID); 3485 io::Emit32(Out, (*M)->BaseSubmoduleID); 3486 io::Emit32(Out, (*M)->BaseSelectorID); 3487 io::Emit32(Out, (*M)->BaseDeclID); 3488 io::Emit32(Out, (*M)->BaseTypeIndex); 3489 } 3490 } 3491 Record.clear(); 3492 Record.push_back(MODULE_OFFSET_MAP); 3493 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 3494 Buffer.data(), Buffer.size()); 3495 } 3496 WritePreprocessor(PP, WritingModule != 0); 3497 WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot); 3498 WriteSelectors(SemaRef); 3499 WriteReferencedSelectorsPool(SemaRef); 3500 WriteIdentifierTable(PP, SemaRef.IdResolver, WritingModule != 0); 3501 WriteFPPragmaOptions(SemaRef.getFPOptions()); 3502 WriteOpenCLExtensions(SemaRef); 3503 3504 WriteTypeDeclOffsets(); 3505 WritePragmaDiagnosticMappings(Context.getDiagnostics()); 3506 3507 WriteCXXBaseSpecifiersOffsets(); 3508 3509 // If we're emitting a module, write out the submodule information. 3510 if (WritingModule) 3511 WriteSubmodules(WritingModule); 3512 3513 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 3514 3515 // Write the record containing external, unnamed definitions. 3516 if (!ExternalDefinitions.empty()) 3517 Stream.EmitRecord(EXTERNAL_DEFINITIONS, ExternalDefinitions); 3518 3519 // Write the record containing tentative definitions. 3520 if (!TentativeDefinitions.empty()) 3521 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 3522 3523 // Write the record containing unused file scoped decls. 3524 if (!UnusedFileScopedDecls.empty()) 3525 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 3526 3527 // Write the record containing weak undeclared identifiers. 3528 if (!WeakUndeclaredIdentifiers.empty()) 3529 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 3530 WeakUndeclaredIdentifiers); 3531 3532 // Write the record containing locally-scoped external definitions. 3533 if (!LocallyScopedExternalDecls.empty()) 3534 Stream.EmitRecord(LOCALLY_SCOPED_EXTERNAL_DECLS, 3535 LocallyScopedExternalDecls); 3536 3537 // Write the record containing ext_vector type names. 3538 if (!ExtVectorDecls.empty()) 3539 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 3540 3541 // Write the record containing VTable uses information. 3542 if (!VTableUses.empty()) 3543 Stream.EmitRecord(VTABLE_USES, VTableUses); 3544 3545 // Write the record containing dynamic classes declarations. 3546 if (!DynamicClasses.empty()) 3547 Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses); 3548 3549 // Write the record containing pending implicit instantiations. 3550 if (!PendingInstantiations.empty()) 3551 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 3552 3553 // Write the record containing declaration references of Sema. 3554 if (!SemaDeclRefs.empty()) 3555 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 3556 3557 // Write the record containing CUDA-specific declaration references. 3558 if (!CUDASpecialDeclRefs.empty()) 3559 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 3560 3561 // Write the delegating constructors. 3562 if (!DelegatingCtorDecls.empty()) 3563 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 3564 3565 // Write the known namespaces. 3566 if (!KnownNamespaces.empty()) 3567 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 3568 3569 // Write the visible updates to DeclContexts. 3570 for (llvm::SmallPtrSet<const DeclContext *, 16>::iterator 3571 I = UpdatedDeclContexts.begin(), 3572 E = UpdatedDeclContexts.end(); 3573 I != E; ++I) 3574 WriteDeclContextVisibleUpdate(*I); 3575 3576 if (!WritingModule) { 3577 // Write the submodules that were imported, if any. 3578 RecordData ImportedModules; 3579 for (ASTContext::import_iterator I = Context.local_import_begin(), 3580 IEnd = Context.local_import_end(); 3581 I != IEnd; ++I) { 3582 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 3583 ImportedModules.push_back(SubmoduleIDs[I->getImportedModule()]); 3584 } 3585 if (!ImportedModules.empty()) { 3586 // Sort module IDs. 3587 llvm::array_pod_sort(ImportedModules.begin(), ImportedModules.end()); 3588 3589 // Unique module IDs. 3590 ImportedModules.erase(std::unique(ImportedModules.begin(), 3591 ImportedModules.end()), 3592 ImportedModules.end()); 3593 3594 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 3595 } 3596 } 3597 3598 WriteDeclUpdatesBlocks(); 3599 WriteDeclReplacementsBlock(); 3600 WriteMergedDecls(); 3601 WriteRedeclarations(); 3602 WriteObjCCategories(); 3603 3604 // Some simple statistics 3605 Record.clear(); 3606 Record.push_back(NumStatements); 3607 Record.push_back(NumMacros); 3608 Record.push_back(NumLexicalDeclContexts); 3609 Record.push_back(NumVisibleDeclContexts); 3610 Stream.EmitRecord(STATISTICS, Record); 3611 Stream.ExitBlock(); 3612 } 3613 3614 /// \brief Go through the declaration update blocks and resolve declaration 3615 /// pointers into declaration IDs. 3616 void ASTWriter::ResolveDeclUpdatesBlocks() { 3617 for (DeclUpdateMap::iterator 3618 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3619 const Decl *D = I->first; 3620 UpdateRecord &URec = I->second; 3621 3622 if (isRewritten(D)) 3623 continue; // The decl will be written completely 3624 3625 unsigned Idx = 0, N = URec.size(); 3626 while (Idx < N) { 3627 switch ((DeclUpdateKind)URec[Idx++]) { 3628 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 3629 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 3630 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 3631 URec[Idx] = GetDeclRef(reinterpret_cast<Decl *>(URec[Idx])); 3632 ++Idx; 3633 break; 3634 3635 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 3636 ++Idx; 3637 break; 3638 } 3639 } 3640 } 3641 } 3642 3643 void ASTWriter::WriteDeclUpdatesBlocks() { 3644 if (DeclUpdates.empty()) 3645 return; 3646 3647 RecordData OffsetsRecord; 3648 Stream.EnterSubblock(DECL_UPDATES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE); 3649 for (DeclUpdateMap::iterator 3650 I = DeclUpdates.begin(), E = DeclUpdates.end(); I != E; ++I) { 3651 const Decl *D = I->first; 3652 UpdateRecord &URec = I->second; 3653 3654 if (isRewritten(D)) 3655 continue; // The decl will be written completely,no need to store updates. 3656 3657 uint64_t Offset = Stream.GetCurrentBitNo(); 3658 Stream.EmitRecord(DECL_UPDATES, URec); 3659 3660 OffsetsRecord.push_back(GetDeclRef(D)); 3661 OffsetsRecord.push_back(Offset); 3662 } 3663 Stream.ExitBlock(); 3664 Stream.EmitRecord(DECL_UPDATE_OFFSETS, OffsetsRecord); 3665 } 3666 3667 void ASTWriter::WriteDeclReplacementsBlock() { 3668 if (ReplacedDecls.empty()) 3669 return; 3670 3671 RecordData Record; 3672 for (SmallVector<ReplacedDeclInfo, 16>::iterator 3673 I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) { 3674 Record.push_back(I->ID); 3675 Record.push_back(I->Offset); 3676 Record.push_back(I->Loc); 3677 } 3678 Stream.EmitRecord(DECL_REPLACEMENTS, Record); 3679 } 3680 3681 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 3682 Record.push_back(Loc.getRawEncoding()); 3683 } 3684 3685 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 3686 AddSourceLocation(Range.getBegin(), Record); 3687 AddSourceLocation(Range.getEnd(), Record); 3688 } 3689 3690 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) { 3691 Record.push_back(Value.getBitWidth()); 3692 const uint64_t *Words = Value.getRawData(); 3693 Record.append(Words, Words + Value.getNumWords()); 3694 } 3695 3696 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) { 3697 Record.push_back(Value.isUnsigned()); 3698 AddAPInt(Value, Record); 3699 } 3700 3701 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) { 3702 AddAPInt(Value.bitcastToAPInt(), Record); 3703 } 3704 3705 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 3706 Record.push_back(getIdentifierRef(II)); 3707 } 3708 3709 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 3710 if (II == 0) 3711 return 0; 3712 3713 IdentID &ID = IdentifierIDs[II]; 3714 if (ID == 0) 3715 ID = NextIdentID++; 3716 return ID; 3717 } 3718 3719 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) { 3720 Record.push_back(getSelectorRef(SelRef)); 3721 } 3722 3723 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 3724 if (Sel.getAsOpaquePtr() == 0) { 3725 return 0; 3726 } 3727 3728 SelectorID &SID = SelectorIDs[Sel]; 3729 if (SID == 0 && Chain) { 3730 // This might trigger a ReadSelector callback, which will set the ID for 3731 // this selector. 3732 Chain->LoadSelector(Sel); 3733 } 3734 if (SID == 0) { 3735 SID = NextSelectorID++; 3736 } 3737 return SID; 3738 } 3739 3740 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) { 3741 AddDeclRef(Temp->getDestructor(), Record); 3742 } 3743 3744 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases, 3745 CXXBaseSpecifier const *BasesEnd, 3746 RecordDataImpl &Record) { 3747 assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded"); 3748 CXXBaseSpecifiersToWrite.push_back( 3749 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID, 3750 Bases, BasesEnd)); 3751 Record.push_back(NextCXXBaseSpecifiersID++); 3752 } 3753 3754 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind, 3755 const TemplateArgumentLocInfo &Arg, 3756 RecordDataImpl &Record) { 3757 switch (Kind) { 3758 case TemplateArgument::Expression: 3759 AddStmt(Arg.getAsExpr()); 3760 break; 3761 case TemplateArgument::Type: 3762 AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record); 3763 break; 3764 case TemplateArgument::Template: 3765 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3766 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3767 break; 3768 case TemplateArgument::TemplateExpansion: 3769 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record); 3770 AddSourceLocation(Arg.getTemplateNameLoc(), Record); 3771 AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record); 3772 break; 3773 case TemplateArgument::Null: 3774 case TemplateArgument::Integral: 3775 case TemplateArgument::Declaration: 3776 case TemplateArgument::Pack: 3777 break; 3778 } 3779 } 3780 3781 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg, 3782 RecordDataImpl &Record) { 3783 AddTemplateArgument(Arg.getArgument(), Record); 3784 3785 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 3786 bool InfoHasSameExpr 3787 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 3788 Record.push_back(InfoHasSameExpr); 3789 if (InfoHasSameExpr) 3790 return; // Avoid storing the same expr twice. 3791 } 3792 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(), 3793 Record); 3794 } 3795 3796 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo, 3797 RecordDataImpl &Record) { 3798 if (TInfo == 0) { 3799 AddTypeRef(QualType(), Record); 3800 return; 3801 } 3802 3803 AddTypeLoc(TInfo->getTypeLoc(), Record); 3804 } 3805 3806 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) { 3807 AddTypeRef(TL.getType(), Record); 3808 3809 TypeLocWriter TLW(*this, Record); 3810 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 3811 TLW.Visit(TL); 3812 } 3813 3814 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 3815 Record.push_back(GetOrCreateTypeID(T)); 3816 } 3817 3818 TypeID ASTWriter::GetOrCreateTypeID( QualType T) { 3819 return MakeTypeID(*Context, T, 3820 std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this)); 3821 } 3822 3823 TypeID ASTWriter::getTypeID(QualType T) const { 3824 return MakeTypeID(*Context, T, 3825 std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this)); 3826 } 3827 3828 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) { 3829 if (T.isNull()) 3830 return TypeIdx(); 3831 assert(!T.getLocalFastQualifiers()); 3832 3833 TypeIdx &Idx = TypeIdxs[T]; 3834 if (Idx.getIndex() == 0) { 3835 if (DoneWritingDeclsAndTypes) { 3836 assert(0 && "New type seen after serializing all the types to emit!"); 3837 return TypeIdx(); 3838 } 3839 3840 // We haven't seen this type before. Assign it a new ID and put it 3841 // into the queue of types to emit. 3842 Idx = TypeIdx(NextTypeID++); 3843 DeclTypesToEmit.push(T); 3844 } 3845 return Idx; 3846 } 3847 3848 TypeIdx ASTWriter::getTypeIdx(QualType T) const { 3849 if (T.isNull()) 3850 return TypeIdx(); 3851 assert(!T.getLocalFastQualifiers()); 3852 3853 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 3854 assert(I != TypeIdxs.end() && "Type not emitted!"); 3855 return I->second; 3856 } 3857 3858 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 3859 Record.push_back(GetDeclRef(D)); 3860 } 3861 3862 DeclID ASTWriter::GetDeclRef(const Decl *D) { 3863 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 3864 3865 if (D == 0) { 3866 return 0; 3867 } 3868 3869 // If D comes from an AST file, its declaration ID is already known and 3870 // fixed. 3871 if (D->isFromASTFile()) 3872 return D->getGlobalID(); 3873 3874 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 3875 DeclID &ID = DeclIDs[D]; 3876 if (ID == 0) { 3877 if (DoneWritingDeclsAndTypes) { 3878 assert(0 && "New decl seen after serializing all the decls to emit!"); 3879 return 0; 3880 } 3881 3882 // We haven't seen this declaration before. Give it a new ID and 3883 // enqueue it in the list of declarations to emit. 3884 ID = NextDeclID++; 3885 DeclTypesToEmit.push(const_cast<Decl *>(D)); 3886 } 3887 3888 return ID; 3889 } 3890 3891 DeclID ASTWriter::getDeclID(const Decl *D) { 3892 if (D == 0) 3893 return 0; 3894 3895 // If D comes from an AST file, its declaration ID is already known and 3896 // fixed. 3897 if (D->isFromASTFile()) 3898 return D->getGlobalID(); 3899 3900 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 3901 return DeclIDs[D]; 3902 } 3903 3904 static inline bool compLocDecl(std::pair<unsigned, serialization::DeclID> L, 3905 std::pair<unsigned, serialization::DeclID> R) { 3906 return L.first < R.first; 3907 } 3908 3909 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 3910 assert(ID); 3911 assert(D); 3912 3913 SourceLocation Loc = D->getLocation(); 3914 if (Loc.isInvalid()) 3915 return; 3916 3917 // We only keep track of the file-level declarations of each file. 3918 if (!D->getLexicalDeclContext()->isFileContext()) 3919 return; 3920 // FIXME: ParmVarDecls that are part of a function type of a parameter of 3921 // a function/objc method, should not have TU as lexical context. 3922 if (isa<ParmVarDecl>(D)) 3923 return; 3924 3925 SourceManager &SM = Context->getSourceManager(); 3926 SourceLocation FileLoc = SM.getFileLoc(Loc); 3927 assert(SM.isLocalSourceLocation(FileLoc)); 3928 FileID FID; 3929 unsigned Offset; 3930 llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 3931 if (FID.isInvalid()) 3932 return; 3933 const SrcMgr::SLocEntry *Entry = &SM.getSLocEntry(FID); 3934 assert(Entry->isFile()); 3935 3936 DeclIDInFileInfo *&Info = FileDeclIDs[Entry]; 3937 if (!Info) 3938 Info = new DeclIDInFileInfo(); 3939 3940 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 3941 LocDeclIDsTy &Decls = Info->DeclIDs; 3942 3943 if (Decls.empty() || Decls.back().first <= Offset) { 3944 Decls.push_back(LocDecl); 3945 return; 3946 } 3947 3948 LocDeclIDsTy::iterator 3949 I = std::upper_bound(Decls.begin(), Decls.end(), LocDecl, compLocDecl); 3950 3951 Decls.insert(I, LocDecl); 3952 } 3953 3954 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) { 3955 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 3956 Record.push_back(Name.getNameKind()); 3957 switch (Name.getNameKind()) { 3958 case DeclarationName::Identifier: 3959 AddIdentifierRef(Name.getAsIdentifierInfo(), Record); 3960 break; 3961 3962 case DeclarationName::ObjCZeroArgSelector: 3963 case DeclarationName::ObjCOneArgSelector: 3964 case DeclarationName::ObjCMultiArgSelector: 3965 AddSelectorRef(Name.getObjCSelector(), Record); 3966 break; 3967 3968 case DeclarationName::CXXConstructorName: 3969 case DeclarationName::CXXDestructorName: 3970 case DeclarationName::CXXConversionFunctionName: 3971 AddTypeRef(Name.getCXXNameType(), Record); 3972 break; 3973 3974 case DeclarationName::CXXOperatorName: 3975 Record.push_back(Name.getCXXOverloadedOperator()); 3976 break; 3977 3978 case DeclarationName::CXXLiteralOperatorName: 3979 AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record); 3980 break; 3981 3982 case DeclarationName::CXXUsingDirective: 3983 // No extra data to emit 3984 break; 3985 } 3986 } 3987 3988 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 3989 DeclarationName Name, RecordDataImpl &Record) { 3990 switch (Name.getNameKind()) { 3991 case DeclarationName::CXXConstructorName: 3992 case DeclarationName::CXXDestructorName: 3993 case DeclarationName::CXXConversionFunctionName: 3994 AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record); 3995 break; 3996 3997 case DeclarationName::CXXOperatorName: 3998 AddSourceLocation( 3999 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc), 4000 Record); 4001 AddSourceLocation( 4002 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc), 4003 Record); 4004 break; 4005 4006 case DeclarationName::CXXLiteralOperatorName: 4007 AddSourceLocation( 4008 SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc), 4009 Record); 4010 break; 4011 4012 case DeclarationName::Identifier: 4013 case DeclarationName::ObjCZeroArgSelector: 4014 case DeclarationName::ObjCOneArgSelector: 4015 case DeclarationName::ObjCMultiArgSelector: 4016 case DeclarationName::CXXUsingDirective: 4017 break; 4018 } 4019 } 4020 4021 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 4022 RecordDataImpl &Record) { 4023 AddDeclarationName(NameInfo.getName(), Record); 4024 AddSourceLocation(NameInfo.getLoc(), Record); 4025 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record); 4026 } 4027 4028 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info, 4029 RecordDataImpl &Record) { 4030 AddNestedNameSpecifierLoc(Info.QualifierLoc, Record); 4031 Record.push_back(Info.NumTemplParamLists); 4032 for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i) 4033 AddTemplateParameterList(Info.TemplParamLists[i], Record); 4034 } 4035 4036 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS, 4037 RecordDataImpl &Record) { 4038 // Nested name specifiers usually aren't too long. I think that 8 would 4039 // typically accommodate the vast majority. 4040 SmallVector<NestedNameSpecifier *, 8> NestedNames; 4041 4042 // Push each of the NNS's onto a stack for serialization in reverse order. 4043 while (NNS) { 4044 NestedNames.push_back(NNS); 4045 NNS = NNS->getPrefix(); 4046 } 4047 4048 Record.push_back(NestedNames.size()); 4049 while(!NestedNames.empty()) { 4050 NNS = NestedNames.pop_back_val(); 4051 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 4052 Record.push_back(Kind); 4053 switch (Kind) { 4054 case NestedNameSpecifier::Identifier: 4055 AddIdentifierRef(NNS->getAsIdentifier(), Record); 4056 break; 4057 4058 case NestedNameSpecifier::Namespace: 4059 AddDeclRef(NNS->getAsNamespace(), Record); 4060 break; 4061 4062 case NestedNameSpecifier::NamespaceAlias: 4063 AddDeclRef(NNS->getAsNamespaceAlias(), Record); 4064 break; 4065 4066 case NestedNameSpecifier::TypeSpec: 4067 case NestedNameSpecifier::TypeSpecWithTemplate: 4068 AddTypeRef(QualType(NNS->getAsType(), 0), Record); 4069 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 4070 break; 4071 4072 case NestedNameSpecifier::Global: 4073 // Don't need to write an associated value. 4074 break; 4075 } 4076 } 4077 } 4078 4079 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 4080 RecordDataImpl &Record) { 4081 // Nested name specifiers usually aren't too long. I think that 8 would 4082 // typically accommodate the vast majority. 4083 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 4084 4085 // Push each of the nested-name-specifiers's onto a stack for 4086 // serialization in reverse order. 4087 while (NNS) { 4088 NestedNames.push_back(NNS); 4089 NNS = NNS.getPrefix(); 4090 } 4091 4092 Record.push_back(NestedNames.size()); 4093 while(!NestedNames.empty()) { 4094 NNS = NestedNames.pop_back_val(); 4095 NestedNameSpecifier::SpecifierKind Kind 4096 = NNS.getNestedNameSpecifier()->getKind(); 4097 Record.push_back(Kind); 4098 switch (Kind) { 4099 case NestedNameSpecifier::Identifier: 4100 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record); 4101 AddSourceRange(NNS.getLocalSourceRange(), Record); 4102 break; 4103 4104 case NestedNameSpecifier::Namespace: 4105 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record); 4106 AddSourceRange(NNS.getLocalSourceRange(), Record); 4107 break; 4108 4109 case NestedNameSpecifier::NamespaceAlias: 4110 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record); 4111 AddSourceRange(NNS.getLocalSourceRange(), Record); 4112 break; 4113 4114 case NestedNameSpecifier::TypeSpec: 4115 case NestedNameSpecifier::TypeSpecWithTemplate: 4116 Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 4117 AddTypeLoc(NNS.getTypeLoc(), Record); 4118 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 4119 break; 4120 4121 case NestedNameSpecifier::Global: 4122 AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record); 4123 break; 4124 } 4125 } 4126 } 4127 4128 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) { 4129 TemplateName::NameKind Kind = Name.getKind(); 4130 Record.push_back(Kind); 4131 switch (Kind) { 4132 case TemplateName::Template: 4133 AddDeclRef(Name.getAsTemplateDecl(), Record); 4134 break; 4135 4136 case TemplateName::OverloadedTemplate: { 4137 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 4138 Record.push_back(OvT->size()); 4139 for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end(); 4140 I != E; ++I) 4141 AddDeclRef(*I, Record); 4142 break; 4143 } 4144 4145 case TemplateName::QualifiedTemplate: { 4146 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 4147 AddNestedNameSpecifier(QualT->getQualifier(), Record); 4148 Record.push_back(QualT->hasTemplateKeyword()); 4149 AddDeclRef(QualT->getTemplateDecl(), Record); 4150 break; 4151 } 4152 4153 case TemplateName::DependentTemplate: { 4154 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 4155 AddNestedNameSpecifier(DepT->getQualifier(), Record); 4156 Record.push_back(DepT->isIdentifier()); 4157 if (DepT->isIdentifier()) 4158 AddIdentifierRef(DepT->getIdentifier(), Record); 4159 else 4160 Record.push_back(DepT->getOperator()); 4161 break; 4162 } 4163 4164 case TemplateName::SubstTemplateTemplateParm: { 4165 SubstTemplateTemplateParmStorage *subst 4166 = Name.getAsSubstTemplateTemplateParm(); 4167 AddDeclRef(subst->getParameter(), Record); 4168 AddTemplateName(subst->getReplacement(), Record); 4169 break; 4170 } 4171 4172 case TemplateName::SubstTemplateTemplateParmPack: { 4173 SubstTemplateTemplateParmPackStorage *SubstPack 4174 = Name.getAsSubstTemplateTemplateParmPack(); 4175 AddDeclRef(SubstPack->getParameterPack(), Record); 4176 AddTemplateArgument(SubstPack->getArgumentPack(), Record); 4177 break; 4178 } 4179 } 4180 } 4181 4182 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg, 4183 RecordDataImpl &Record) { 4184 Record.push_back(Arg.getKind()); 4185 switch (Arg.getKind()) { 4186 case TemplateArgument::Null: 4187 break; 4188 case TemplateArgument::Type: 4189 AddTypeRef(Arg.getAsType(), Record); 4190 break; 4191 case TemplateArgument::Declaration: 4192 AddDeclRef(Arg.getAsDecl(), Record); 4193 break; 4194 case TemplateArgument::Integral: 4195 AddAPSInt(Arg.getAsIntegral(), Record); 4196 AddTypeRef(Arg.getIntegralType(), Record); 4197 break; 4198 case TemplateArgument::Template: 4199 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 4200 break; 4201 case TemplateArgument::TemplateExpansion: 4202 AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record); 4203 if (llvm::Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 4204 Record.push_back(*NumExpansions + 1); 4205 else 4206 Record.push_back(0); 4207 break; 4208 case TemplateArgument::Expression: 4209 AddStmt(Arg.getAsExpr()); 4210 break; 4211 case TemplateArgument::Pack: 4212 Record.push_back(Arg.pack_size()); 4213 for (TemplateArgument::pack_iterator I=Arg.pack_begin(), E=Arg.pack_end(); 4214 I != E; ++I) 4215 AddTemplateArgument(*I, Record); 4216 break; 4217 } 4218 } 4219 4220 void 4221 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams, 4222 RecordDataImpl &Record) { 4223 assert(TemplateParams && "No TemplateParams!"); 4224 AddSourceLocation(TemplateParams->getTemplateLoc(), Record); 4225 AddSourceLocation(TemplateParams->getLAngleLoc(), Record); 4226 AddSourceLocation(TemplateParams->getRAngleLoc(), Record); 4227 Record.push_back(TemplateParams->size()); 4228 for (TemplateParameterList::const_iterator 4229 P = TemplateParams->begin(), PEnd = TemplateParams->end(); 4230 P != PEnd; ++P) 4231 AddDeclRef(*P, Record); 4232 } 4233 4234 /// \brief Emit a template argument list. 4235 void 4236 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs, 4237 RecordDataImpl &Record) { 4238 assert(TemplateArgs && "No TemplateArgs!"); 4239 Record.push_back(TemplateArgs->size()); 4240 for (int i=0, e = TemplateArgs->size(); i != e; ++i) 4241 AddTemplateArgument(TemplateArgs->get(i), Record); 4242 } 4243 4244 4245 void 4246 ASTWriter::AddUnresolvedSet(const UnresolvedSetImpl &Set, RecordDataImpl &Record) { 4247 Record.push_back(Set.size()); 4248 for (UnresolvedSetImpl::const_iterator 4249 I = Set.begin(), E = Set.end(); I != E; ++I) { 4250 AddDeclRef(I.getDecl(), Record); 4251 Record.push_back(I.getAccess()); 4252 } 4253 } 4254 4255 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base, 4256 RecordDataImpl &Record) { 4257 Record.push_back(Base.isVirtual()); 4258 Record.push_back(Base.isBaseOfClass()); 4259 Record.push_back(Base.getAccessSpecifierAsWritten()); 4260 Record.push_back(Base.getInheritConstructors()); 4261 AddTypeSourceInfo(Base.getTypeSourceInfo(), Record); 4262 AddSourceRange(Base.getSourceRange(), Record); 4263 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 4264 : SourceLocation(), 4265 Record); 4266 } 4267 4268 void ASTWriter::FlushCXXBaseSpecifiers() { 4269 RecordData Record; 4270 for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) { 4271 Record.clear(); 4272 4273 // Record the offset of this base-specifier set. 4274 unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1; 4275 if (Index == CXXBaseSpecifiersOffsets.size()) 4276 CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo()); 4277 else { 4278 if (Index > CXXBaseSpecifiersOffsets.size()) 4279 CXXBaseSpecifiersOffsets.resize(Index + 1); 4280 CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo(); 4281 } 4282 4283 const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases, 4284 *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd; 4285 Record.push_back(BEnd - B); 4286 for (; B != BEnd; ++B) 4287 AddCXXBaseSpecifier(*B, Record); 4288 Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record); 4289 4290 // Flush any expressions that were written as part of the base specifiers. 4291 FlushStmts(); 4292 } 4293 4294 CXXBaseSpecifiersToWrite.clear(); 4295 } 4296 4297 void ASTWriter::AddCXXCtorInitializers( 4298 const CXXCtorInitializer * const *CtorInitializers, 4299 unsigned NumCtorInitializers, 4300 RecordDataImpl &Record) { 4301 Record.push_back(NumCtorInitializers); 4302 for (unsigned i=0; i != NumCtorInitializers; ++i) { 4303 const CXXCtorInitializer *Init = CtorInitializers[i]; 4304 4305 if (Init->isBaseInitializer()) { 4306 Record.push_back(CTOR_INITIALIZER_BASE); 4307 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4308 Record.push_back(Init->isBaseVirtual()); 4309 } else if (Init->isDelegatingInitializer()) { 4310 Record.push_back(CTOR_INITIALIZER_DELEGATING); 4311 AddTypeSourceInfo(Init->getTypeSourceInfo(), Record); 4312 } else if (Init->isMemberInitializer()){ 4313 Record.push_back(CTOR_INITIALIZER_MEMBER); 4314 AddDeclRef(Init->getMember(), Record); 4315 } else { 4316 Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 4317 AddDeclRef(Init->getIndirectMember(), Record); 4318 } 4319 4320 AddSourceLocation(Init->getMemberLocation(), Record); 4321 AddStmt(Init->getInit()); 4322 AddSourceLocation(Init->getLParenLoc(), Record); 4323 AddSourceLocation(Init->getRParenLoc(), Record); 4324 Record.push_back(Init->isWritten()); 4325 if (Init->isWritten()) { 4326 Record.push_back(Init->getSourceOrder()); 4327 } else { 4328 Record.push_back(Init->getNumArrayIndices()); 4329 for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i) 4330 AddDeclRef(Init->getArrayIndex(i), Record); 4331 } 4332 } 4333 } 4334 4335 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) { 4336 assert(D->DefinitionData); 4337 struct CXXRecordDecl::DefinitionData &Data = *D->DefinitionData; 4338 Record.push_back(Data.IsLambda); 4339 Record.push_back(Data.UserDeclaredConstructor); 4340 Record.push_back(Data.UserDeclaredCopyConstructor); 4341 Record.push_back(Data.UserDeclaredMoveConstructor); 4342 Record.push_back(Data.UserDeclaredCopyAssignment); 4343 Record.push_back(Data.UserDeclaredMoveAssignment); 4344 Record.push_back(Data.UserDeclaredDestructor); 4345 Record.push_back(Data.Aggregate); 4346 Record.push_back(Data.PlainOldData); 4347 Record.push_back(Data.Empty); 4348 Record.push_back(Data.Polymorphic); 4349 Record.push_back(Data.Abstract); 4350 Record.push_back(Data.IsStandardLayout); 4351 Record.push_back(Data.HasNoNonEmptyBases); 4352 Record.push_back(Data.HasPrivateFields); 4353 Record.push_back(Data.HasProtectedFields); 4354 Record.push_back(Data.HasPublicFields); 4355 Record.push_back(Data.HasMutableFields); 4356 Record.push_back(Data.HasOnlyCMembers); 4357 Record.push_back(Data.HasInClassInitializer); 4358 Record.push_back(Data.HasTrivialDefaultConstructor); 4359 Record.push_back(Data.HasConstexprNonCopyMoveConstructor); 4360 Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr); 4361 Record.push_back(Data.HasConstexprDefaultConstructor); 4362 Record.push_back(Data.HasTrivialCopyConstructor); 4363 Record.push_back(Data.HasTrivialMoveConstructor); 4364 Record.push_back(Data.HasTrivialCopyAssignment); 4365 Record.push_back(Data.HasTrivialMoveAssignment); 4366 Record.push_back(Data.HasTrivialDestructor); 4367 Record.push_back(Data.HasIrrelevantDestructor); 4368 Record.push_back(Data.HasNonLiteralTypeFieldsOrBases); 4369 Record.push_back(Data.ComputedVisibleConversions); 4370 Record.push_back(Data.UserProvidedDefaultConstructor); 4371 Record.push_back(Data.DeclaredDefaultConstructor); 4372 Record.push_back(Data.DeclaredCopyConstructor); 4373 Record.push_back(Data.DeclaredMoveConstructor); 4374 Record.push_back(Data.DeclaredCopyAssignment); 4375 Record.push_back(Data.DeclaredMoveAssignment); 4376 Record.push_back(Data.DeclaredDestructor); 4377 Record.push_back(Data.FailedImplicitMoveConstructor); 4378 Record.push_back(Data.FailedImplicitMoveAssignment); 4379 // IsLambda bit is already saved. 4380 4381 Record.push_back(Data.NumBases); 4382 if (Data.NumBases > 0) 4383 AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases, 4384 Record); 4385 4386 // FIXME: Make VBases lazily computed when needed to avoid storing them. 4387 Record.push_back(Data.NumVBases); 4388 if (Data.NumVBases > 0) 4389 AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases, 4390 Record); 4391 4392 AddUnresolvedSet(Data.Conversions, Record); 4393 AddUnresolvedSet(Data.VisibleConversions, Record); 4394 // Data.Definition is the owning decl, no need to write it. 4395 AddDeclRef(Data.FirstFriend, Record); 4396 4397 // Add lambda-specific data. 4398 if (Data.IsLambda) { 4399 CXXRecordDecl::LambdaDefinitionData &Lambda = D->getLambdaData(); 4400 Record.push_back(Lambda.Dependent); 4401 Record.push_back(Lambda.NumCaptures); 4402 Record.push_back(Lambda.NumExplicitCaptures); 4403 Record.push_back(Lambda.ManglingNumber); 4404 AddDeclRef(Lambda.ContextDecl, Record); 4405 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 4406 LambdaExpr::Capture &Capture = Lambda.Captures[I]; 4407 AddSourceLocation(Capture.getLocation(), Record); 4408 Record.push_back(Capture.isImplicit()); 4409 Record.push_back(Capture.getCaptureKind()); // FIXME: stable! 4410 VarDecl *Var = Capture.capturesVariable()? Capture.getCapturedVar() : 0; 4411 AddDeclRef(Var, Record); 4412 AddSourceLocation(Capture.isPackExpansion()? Capture.getEllipsisLoc() 4413 : SourceLocation(), 4414 Record); 4415 } 4416 } 4417 } 4418 4419 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 4420 assert(Reader && "Cannot remove chain"); 4421 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 4422 assert(FirstDeclID == NextDeclID && 4423 FirstTypeID == NextTypeID && 4424 FirstIdentID == NextIdentID && 4425 FirstSubmoduleID == NextSubmoduleID && 4426 FirstSelectorID == NextSelectorID && 4427 "Setting chain after writing has started."); 4428 4429 Chain = Reader; 4430 4431 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 4432 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 4433 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 4434 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 4435 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 4436 NextDeclID = FirstDeclID; 4437 NextTypeID = FirstTypeID; 4438 NextIdentID = FirstIdentID; 4439 NextSelectorID = FirstSelectorID; 4440 NextSubmoduleID = FirstSubmoduleID; 4441 } 4442 4443 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 4444 IdentifierIDs[II] = ID; 4445 if (II->hasMacroDefinition()) 4446 DeserializedMacroNames.push_back(II); 4447 } 4448 4449 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 4450 // Always take the highest-numbered type index. This copes with an interesting 4451 // case for chained AST writing where we schedule writing the type and then, 4452 // later, deserialize the type from another AST. In this case, we want to 4453 // keep the higher-numbered entry so that we can properly write it out to 4454 // the AST file. 4455 TypeIdx &StoredIdx = TypeIdxs[T]; 4456 if (Idx.getIndex() >= StoredIdx.getIndex()) 4457 StoredIdx = Idx; 4458 } 4459 4460 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 4461 SelectorIDs[S] = ID; 4462 } 4463 4464 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 4465 MacroDefinition *MD) { 4466 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 4467 MacroDefinitions[MD] = ID; 4468 } 4469 4470 void ASTWriter::MacroVisible(IdentifierInfo *II) { 4471 DeserializedMacroNames.push_back(II); 4472 } 4473 4474 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 4475 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 4476 SubmoduleIDs[Mod] = ID; 4477 } 4478 4479 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 4480 assert(D->isCompleteDefinition()); 4481 assert(!WritingAST && "Already writing the AST!"); 4482 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 4483 // We are interested when a PCH decl is modified. 4484 if (RD->isFromASTFile()) { 4485 // A forward reference was mutated into a definition. Rewrite it. 4486 // FIXME: This happens during template instantiation, should we 4487 // have created a new definition decl instead ? 4488 RewriteDecl(RD); 4489 } 4490 } 4491 } 4492 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 4493 assert(!WritingAST && "Already writing the AST!"); 4494 4495 // TU and namespaces are handled elsewhere. 4496 if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC)) 4497 return; 4498 4499 if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile())) 4500 return; // Not a source decl added to a DeclContext from PCH. 4501 4502 AddUpdatedDeclContext(DC); 4503 UpdatingVisibleDecls.push_back(D); 4504 } 4505 4506 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 4507 assert(!WritingAST && "Already writing the AST!"); 4508 assert(D->isImplicit()); 4509 if (!(!D->isFromASTFile() && RD->isFromASTFile())) 4510 return; // Not a source member added to a class from PCH. 4511 if (!isa<CXXMethodDecl>(D)) 4512 return; // We are interested in lazily declared implicit methods. 4513 4514 // A decl coming from PCH was modified. 4515 assert(RD->isCompleteDefinition()); 4516 UpdateRecord &Record = DeclUpdates[RD]; 4517 Record.push_back(UPD_CXX_ADDED_IMPLICIT_MEMBER); 4518 Record.push_back(reinterpret_cast<uint64_t>(D)); 4519 } 4520 4521 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD, 4522 const ClassTemplateSpecializationDecl *D) { 4523 // The specializations set is kept in the canonical template. 4524 assert(!WritingAST && "Already writing the AST!"); 4525 TD = TD->getCanonicalDecl(); 4526 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4527 return; // Not a source specialization added to a template from PCH. 4528 4529 UpdateRecord &Record = DeclUpdates[TD]; 4530 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4531 Record.push_back(reinterpret_cast<uint64_t>(D)); 4532 } 4533 4534 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 4535 const FunctionDecl *D) { 4536 // The specializations set is kept in the canonical template. 4537 assert(!WritingAST && "Already writing the AST!"); 4538 TD = TD->getCanonicalDecl(); 4539 if (!(!D->isFromASTFile() && TD->isFromASTFile())) 4540 return; // Not a source specialization added to a template from PCH. 4541 4542 UpdateRecord &Record = DeclUpdates[TD]; 4543 Record.push_back(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION); 4544 Record.push_back(reinterpret_cast<uint64_t>(D)); 4545 } 4546 4547 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 4548 assert(!WritingAST && "Already writing the AST!"); 4549 if (!D->isFromASTFile()) 4550 return; // Declaration not imported from PCH. 4551 4552 // Implicit decl from a PCH was defined. 4553 // FIXME: Should implicit definition be a separate FunctionDecl? 4554 RewriteDecl(D); 4555 } 4556 4557 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 4558 assert(!WritingAST && "Already writing the AST!"); 4559 if (!D->isFromASTFile()) 4560 return; 4561 4562 // Since the actual instantiation is delayed, this really means that we need 4563 // to update the instantiation location. 4564 UpdateRecord &Record = DeclUpdates[D]; 4565 Record.push_back(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER); 4566 AddSourceLocation( 4567 D->getMemberSpecializationInfo()->getPointOfInstantiation(), Record); 4568 } 4569 4570 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 4571 const ObjCInterfaceDecl *IFD) { 4572 assert(!WritingAST && "Already writing the AST!"); 4573 if (!IFD->isFromASTFile()) 4574 return; // Declaration not imported from PCH. 4575 4576 assert(IFD->getDefinition() && "Category on a class without a definition?"); 4577 ObjCClassesWithCategories.insert( 4578 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 4579 } 4580 4581 4582 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop, 4583 const ObjCPropertyDecl *OrigProp, 4584 const ObjCCategoryDecl *ClassExt) { 4585 const ObjCInterfaceDecl *D = ClassExt->getClassInterface(); 4586 if (!D) 4587 return; 4588 4589 assert(!WritingAST && "Already writing the AST!"); 4590 if (!D->isFromASTFile()) 4591 return; // Declaration not imported from PCH. 4592 4593 RewriteDecl(D); 4594 } 4595