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