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