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