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