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(I.second.serializeBits()); 2883 } 2884 } 2885 // Update the placeholder. 2886 Record[SizeIdx] = (Record.size() - SizeIdx) / 2; 2887 } 2888 }; 2889 2890 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule); 2891 2892 // Reserve a spot for the number of locations with state transitions. 2893 auto NumLocationsIdx = Record.size(); 2894 Record.emplace_back(); 2895 2896 // Emit the state transitions. 2897 unsigned NumLocations = 0; 2898 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) { 2899 if (!FileIDAndFile.first.isValid() || 2900 !FileIDAndFile.second.HasLocalTransitions) 2901 continue; 2902 ++NumLocations; 2903 AddSourceLocation(Diag.SourceMgr->getLocForStartOfFile(FileIDAndFile.first), 2904 Record); 2905 Record.push_back(FileIDAndFile.second.StateTransitions.size()); 2906 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) { 2907 Record.push_back(StatePoint.Offset); 2908 AddDiagState(StatePoint.State, false); 2909 } 2910 } 2911 2912 // Backpatch the number of locations. 2913 Record[NumLocationsIdx] = NumLocations; 2914 2915 // Emit CurDiagStateLoc. Do it last in order to match source order. 2916 // 2917 // This also protects against a hypothetical corner case with simulating 2918 // -Werror settings for implicit modules in the ASTReader, where reading 2919 // CurDiagState out of context could change whether warning pragmas are 2920 // treated as errors. 2921 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record); 2922 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false); 2923 2924 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 2925 } 2926 2927 //===----------------------------------------------------------------------===// 2928 // Type Serialization 2929 //===----------------------------------------------------------------------===// 2930 2931 /// \brief Write the representation of a type to the AST stream. 2932 void ASTWriter::WriteType(QualType T) { 2933 TypeIdx &IdxRef = TypeIdxs[T]; 2934 if (IdxRef.getIndex() == 0) // we haven't seen this type before. 2935 IdxRef = TypeIdx(NextTypeID++); 2936 TypeIdx Idx = IdxRef; 2937 2938 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 2939 2940 RecordData Record; 2941 2942 // Emit the type's representation. 2943 ASTTypeWriter W(*this, Record); 2944 W.Visit(T); 2945 uint64_t Offset = W.Emit(); 2946 2947 // Record the offset for this type. 2948 unsigned Index = Idx.getIndex() - FirstTypeID; 2949 if (TypeOffsets.size() == Index) 2950 TypeOffsets.push_back(Offset); 2951 else if (TypeOffsets.size() < Index) { 2952 TypeOffsets.resize(Index + 1); 2953 TypeOffsets[Index] = Offset; 2954 } else { 2955 llvm_unreachable("Types emitted in wrong order"); 2956 } 2957 } 2958 2959 //===----------------------------------------------------------------------===// 2960 // Declaration Serialization 2961 //===----------------------------------------------------------------------===// 2962 2963 /// \brief Write the block containing all of the declaration IDs 2964 /// lexically declared within the given DeclContext. 2965 /// 2966 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 2967 /// bistream, or 0 if no block was written. 2968 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 2969 DeclContext *DC) { 2970 if (DC->decls_empty()) 2971 return 0; 2972 2973 uint64_t Offset = Stream.GetCurrentBitNo(); 2974 SmallVector<uint32_t, 128> KindDeclPairs; 2975 for (const auto *D : DC->decls()) { 2976 KindDeclPairs.push_back(D->getKind()); 2977 KindDeclPairs.push_back(GetDeclRef(D)); 2978 } 2979 2980 ++NumLexicalDeclContexts; 2981 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL}; 2982 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, 2983 bytes(KindDeclPairs)); 2984 return Offset; 2985 } 2986 2987 void ASTWriter::WriteTypeDeclOffsets() { 2988 using namespace llvm; 2989 2990 // Write the type offsets array 2991 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2992 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 2993 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 2994 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 2995 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 2996 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2997 { 2998 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(), 2999 FirstTypeID - NUM_PREDEF_TYPE_IDS}; 3000 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets)); 3001 } 3002 3003 // Write the declaration offsets array 3004 Abbrev = std::make_shared<BitCodeAbbrev>(); 3005 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 3006 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 3007 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 3008 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 3009 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3010 { 3011 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(), 3012 FirstDeclID - NUM_PREDEF_DECL_IDS}; 3013 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets)); 3014 } 3015 } 3016 3017 void ASTWriter::WriteFileDeclIDsMap() { 3018 using namespace llvm; 3019 3020 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs( 3021 FileDeclIDs.begin(), FileDeclIDs.end()); 3022 std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(), 3023 llvm::less_first()); 3024 3025 // Join the vectors of DeclIDs from all files. 3026 SmallVector<DeclID, 256> FileGroupedDeclIDs; 3027 for (auto &FileDeclEntry : SortedFileDeclIDs) { 3028 DeclIDInFileInfo &Info = *FileDeclEntry.second; 3029 Info.FirstDeclIndex = FileGroupedDeclIDs.size(); 3030 for (auto &LocDeclEntry : Info.DeclIDs) 3031 FileGroupedDeclIDs.push_back(LocDeclEntry.second); 3032 } 3033 3034 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3035 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 3036 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3037 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3038 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 3039 RecordData::value_type Record[] = {FILE_SORTED_DECLS, 3040 FileGroupedDeclIDs.size()}; 3041 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs)); 3042 } 3043 3044 void ASTWriter::WriteComments() { 3045 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 3046 ArrayRef<RawComment *> RawComments = Context->Comments.getComments(); 3047 RecordData Record; 3048 for (const auto *I : RawComments) { 3049 Record.clear(); 3050 AddSourceRange(I->getSourceRange(), Record); 3051 Record.push_back(I->getKind()); 3052 Record.push_back(I->isTrailingComment()); 3053 Record.push_back(I->isAlmostTrailingComment()); 3054 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 3055 } 3056 Stream.ExitBlock(); 3057 } 3058 3059 //===----------------------------------------------------------------------===// 3060 // Global Method Pool and Selector Serialization 3061 //===----------------------------------------------------------------------===// 3062 3063 namespace { 3064 3065 // Trait used for the on-disk hash table used in the method pool. 3066 class ASTMethodPoolTrait { 3067 ASTWriter &Writer; 3068 3069 public: 3070 typedef Selector key_type; 3071 typedef key_type key_type_ref; 3072 3073 struct data_type { 3074 SelectorID ID; 3075 ObjCMethodList Instance, Factory; 3076 }; 3077 typedef const data_type& data_type_ref; 3078 3079 typedef unsigned hash_value_type; 3080 typedef unsigned offset_type; 3081 3082 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { } 3083 3084 static hash_value_type ComputeHash(Selector Sel) { 3085 return serialization::ComputeHash(Sel); 3086 } 3087 3088 std::pair<unsigned,unsigned> 3089 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 3090 data_type_ref Methods) { 3091 using namespace llvm::support; 3092 endian::Writer<little> LE(Out); 3093 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 3094 LE.write<uint16_t>(KeyLen); 3095 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 3096 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3097 Method = Method->getNext()) 3098 if (Method->getMethod()) 3099 DataLen += 4; 3100 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3101 Method = Method->getNext()) 3102 if (Method->getMethod()) 3103 DataLen += 4; 3104 LE.write<uint16_t>(DataLen); 3105 return std::make_pair(KeyLen, DataLen); 3106 } 3107 3108 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 3109 using namespace llvm::support; 3110 endian::Writer<little> LE(Out); 3111 uint64_t Start = Out.tell(); 3112 assert((Start >> 32) == 0 && "Selector key offset too large"); 3113 Writer.SetSelectorOffset(Sel, Start); 3114 unsigned N = Sel.getNumArgs(); 3115 LE.write<uint16_t>(N); 3116 if (N == 0) 3117 N = 1; 3118 for (unsigned I = 0; I != N; ++I) 3119 LE.write<uint32_t>( 3120 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 3121 } 3122 3123 void EmitData(raw_ostream& Out, key_type_ref, 3124 data_type_ref Methods, unsigned DataLen) { 3125 using namespace llvm::support; 3126 endian::Writer<little> LE(Out); 3127 uint64_t Start = Out.tell(); (void)Start; 3128 LE.write<uint32_t>(Methods.ID); 3129 unsigned NumInstanceMethods = 0; 3130 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3131 Method = Method->getNext()) 3132 if (Method->getMethod()) 3133 ++NumInstanceMethods; 3134 3135 unsigned NumFactoryMethods = 0; 3136 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3137 Method = Method->getNext()) 3138 if (Method->getMethod()) 3139 ++NumFactoryMethods; 3140 3141 unsigned InstanceBits = Methods.Instance.getBits(); 3142 assert(InstanceBits < 4); 3143 unsigned InstanceHasMoreThanOneDeclBit = 3144 Methods.Instance.hasMoreThanOneDecl(); 3145 unsigned FullInstanceBits = (NumInstanceMethods << 3) | 3146 (InstanceHasMoreThanOneDeclBit << 2) | 3147 InstanceBits; 3148 unsigned FactoryBits = Methods.Factory.getBits(); 3149 assert(FactoryBits < 4); 3150 unsigned FactoryHasMoreThanOneDeclBit = 3151 Methods.Factory.hasMoreThanOneDecl(); 3152 unsigned FullFactoryBits = (NumFactoryMethods << 3) | 3153 (FactoryHasMoreThanOneDeclBit << 2) | 3154 FactoryBits; 3155 LE.write<uint16_t>(FullInstanceBits); 3156 LE.write<uint16_t>(FullFactoryBits); 3157 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3158 Method = Method->getNext()) 3159 if (Method->getMethod()) 3160 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3161 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3162 Method = Method->getNext()) 3163 if (Method->getMethod()) 3164 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3165 3166 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3167 } 3168 }; 3169 3170 } // end anonymous namespace 3171 3172 /// \brief Write ObjC data: selectors and the method pool. 3173 /// 3174 /// The method pool contains both instance and factory methods, stored 3175 /// in an on-disk hash table indexed by the selector. The hash table also 3176 /// contains an empty entry for every other selector known to Sema. 3177 void ASTWriter::WriteSelectors(Sema &SemaRef) { 3178 using namespace llvm; 3179 3180 // Do we have to do anything at all? 3181 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 3182 return; 3183 unsigned NumTableEntries = 0; 3184 // Create and write out the blob that contains selectors and the method pool. 3185 { 3186 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 3187 ASTMethodPoolTrait Trait(*this); 3188 3189 // Create the on-disk hash table representation. We walk through every 3190 // selector we've seen and look it up in the method pool. 3191 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 3192 for (auto &SelectorAndID : SelectorIDs) { 3193 Selector S = SelectorAndID.first; 3194 SelectorID ID = SelectorAndID.second; 3195 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 3196 ASTMethodPoolTrait::data_type Data = { 3197 ID, 3198 ObjCMethodList(), 3199 ObjCMethodList() 3200 }; 3201 if (F != SemaRef.MethodPool.end()) { 3202 Data.Instance = F->second.first; 3203 Data.Factory = F->second.second; 3204 } 3205 // Only write this selector if it's not in an existing AST or something 3206 // changed. 3207 if (Chain && ID < FirstSelectorID) { 3208 // Selector already exists. Did it change? 3209 bool changed = false; 3210 for (ObjCMethodList *M = &Data.Instance; 3211 !changed && M && M->getMethod(); M = M->getNext()) { 3212 if (!M->getMethod()->isFromASTFile()) 3213 changed = true; 3214 } 3215 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod(); 3216 M = M->getNext()) { 3217 if (!M->getMethod()->isFromASTFile()) 3218 changed = true; 3219 } 3220 if (!changed) 3221 continue; 3222 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) { 3223 // A new method pool entry. 3224 ++NumTableEntries; 3225 } 3226 Generator.insert(S, Data, Trait); 3227 } 3228 3229 // Create the on-disk hash table in a buffer. 3230 SmallString<4096> MethodPool; 3231 uint32_t BucketOffset; 3232 { 3233 using namespace llvm::support; 3234 ASTMethodPoolTrait Trait(*this); 3235 llvm::raw_svector_ostream Out(MethodPool); 3236 // Make sure that no bucket is at offset 0 3237 endian::Writer<little>(Out).write<uint32_t>(0); 3238 BucketOffset = Generator.Emit(Out, Trait); 3239 } 3240 3241 // Create a blob abbreviation 3242 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3243 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 3244 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3245 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3246 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3247 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3248 3249 // Write the method pool 3250 { 3251 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset, 3252 NumTableEntries}; 3253 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool); 3254 } 3255 3256 // Create a blob abbreviation for the selector table offsets. 3257 Abbrev = std::make_shared<BitCodeAbbrev>(); 3258 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 3259 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 3260 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3261 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3262 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3263 3264 // Write the selector offsets table. 3265 { 3266 RecordData::value_type Record[] = { 3267 SELECTOR_OFFSETS, SelectorOffsets.size(), 3268 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS}; 3269 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 3270 bytes(SelectorOffsets)); 3271 } 3272 } 3273 } 3274 3275 /// \brief Write the selectors referenced in @selector expression into AST file. 3276 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 3277 using namespace llvm; 3278 if (SemaRef.ReferencedSelectors.empty()) 3279 return; 3280 3281 RecordData Record; 3282 ASTRecordWriter Writer(*this, Record); 3283 3284 // Note: this writes out all references even for a dependent AST. But it is 3285 // very tricky to fix, and given that @selector shouldn't really appear in 3286 // headers, probably not worth it. It's not a correctness issue. 3287 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) { 3288 Selector Sel = SelectorAndLocation.first; 3289 SourceLocation Loc = SelectorAndLocation.second; 3290 Writer.AddSelectorRef(Sel); 3291 Writer.AddSourceLocation(Loc); 3292 } 3293 Writer.Emit(REFERENCED_SELECTOR_POOL); 3294 } 3295 3296 //===----------------------------------------------------------------------===// 3297 // Identifier Table Serialization 3298 //===----------------------------------------------------------------------===// 3299 3300 /// Determine the declaration that should be put into the name lookup table to 3301 /// represent the given declaration in this module. This is usually D itself, 3302 /// but if D was imported and merged into a local declaration, we want the most 3303 /// recent local declaration instead. The chosen declaration will be the most 3304 /// recent declaration in any module that imports this one. 3305 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts, 3306 NamedDecl *D) { 3307 if (!LangOpts.Modules || !D->isFromASTFile()) 3308 return D; 3309 3310 if (Decl *Redecl = D->getPreviousDecl()) { 3311 // For Redeclarable decls, a prior declaration might be local. 3312 for (; Redecl; Redecl = Redecl->getPreviousDecl()) { 3313 // If we find a local decl, we're done. 3314 if (!Redecl->isFromASTFile()) { 3315 // Exception: in very rare cases (for injected-class-names), not all 3316 // redeclarations are in the same semantic context. Skip ones in a 3317 // different context. They don't go in this lookup table at all. 3318 if (!Redecl->getDeclContext()->getRedeclContext()->Equals( 3319 D->getDeclContext()->getRedeclContext())) 3320 continue; 3321 return cast<NamedDecl>(Redecl); 3322 } 3323 3324 // If we find a decl from a (chained-)PCH stop since we won't find a 3325 // local one. 3326 if (Redecl->getOwningModuleID() == 0) 3327 break; 3328 } 3329 } else if (Decl *First = D->getCanonicalDecl()) { 3330 // For Mergeable decls, the first decl might be local. 3331 if (!First->isFromASTFile()) 3332 return cast<NamedDecl>(First); 3333 } 3334 3335 // All declarations are imported. Our most recent declaration will also be 3336 // the most recent one in anyone who imports us. 3337 return D; 3338 } 3339 3340 namespace { 3341 3342 class ASTIdentifierTableTrait { 3343 ASTWriter &Writer; 3344 Preprocessor &PP; 3345 IdentifierResolver &IdResolver; 3346 bool IsModule; 3347 bool NeedDecls; 3348 ASTWriter::RecordData *InterestingIdentifierOffsets; 3349 3350 /// \brief Determines whether this is an "interesting" identifier that needs a 3351 /// full IdentifierInfo structure written into the hash table. Notably, this 3352 /// doesn't check whether the name has macros defined; use PublicMacroIterator 3353 /// to check that. 3354 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) { 3355 if (MacroOffset || 3356 II->isPoisoned() || 3357 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) || 3358 II->hasRevertedTokenIDToIdentifier() || 3359 (NeedDecls && II->getFETokenInfo<void>())) 3360 return true; 3361 3362 return false; 3363 } 3364 3365 public: 3366 typedef IdentifierInfo* key_type; 3367 typedef key_type key_type_ref; 3368 3369 typedef IdentID data_type; 3370 typedef data_type data_type_ref; 3371 3372 typedef unsigned hash_value_type; 3373 typedef unsigned offset_type; 3374 3375 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 3376 IdentifierResolver &IdResolver, bool IsModule, 3377 ASTWriter::RecordData *InterestingIdentifierOffsets) 3378 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule), 3379 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus), 3380 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {} 3381 3382 bool needDecls() const { return NeedDecls; } 3383 3384 static hash_value_type ComputeHash(const IdentifierInfo* II) { 3385 return llvm::HashString(II->getName()); 3386 } 3387 3388 bool isInterestingIdentifier(const IdentifierInfo *II) { 3389 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3390 return isInterestingIdentifier(II, MacroOffset); 3391 } 3392 3393 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) { 3394 return isInterestingIdentifier(II, 0); 3395 } 3396 3397 std::pair<unsigned,unsigned> 3398 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 3399 unsigned KeyLen = II->getLength() + 1; 3400 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 3401 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3402 if (isInterestingIdentifier(II, MacroOffset)) { 3403 DataLen += 2; // 2 bytes for builtin ID 3404 DataLen += 2; // 2 bytes for flags 3405 if (MacroOffset) 3406 DataLen += 4; // MacroDirectives offset. 3407 3408 if (NeedDecls) { 3409 for (IdentifierResolver::iterator D = IdResolver.begin(II), 3410 DEnd = IdResolver.end(); 3411 D != DEnd; ++D) 3412 DataLen += 4; 3413 } 3414 } 3415 using namespace llvm::support; 3416 endian::Writer<little> LE(Out); 3417 3418 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen); 3419 LE.write<uint16_t>(DataLen); 3420 // We emit the key length after the data length so that every 3421 // string is preceded by a 16-bit length. This matches the PTH 3422 // format for storing identifiers. 3423 LE.write<uint16_t>(KeyLen); 3424 return std::make_pair(KeyLen, DataLen); 3425 } 3426 3427 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 3428 unsigned KeyLen) { 3429 // Record the location of the key data. This is used when generating 3430 // the mapping from persistent IDs to strings. 3431 Writer.SetIdentifierOffset(II, Out.tell()); 3432 3433 // Emit the offset of the key/data length information to the interesting 3434 // identifiers table if necessary. 3435 if (InterestingIdentifierOffsets && isInterestingIdentifier(II)) 3436 InterestingIdentifierOffsets->push_back(Out.tell() - 4); 3437 3438 Out.write(II->getNameStart(), KeyLen); 3439 } 3440 3441 void EmitData(raw_ostream& Out, IdentifierInfo* II, 3442 IdentID ID, unsigned) { 3443 using namespace llvm::support; 3444 endian::Writer<little> LE(Out); 3445 3446 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3447 if (!isInterestingIdentifier(II, MacroOffset)) { 3448 LE.write<uint32_t>(ID << 1); 3449 return; 3450 } 3451 3452 LE.write<uint32_t>((ID << 1) | 0x01); 3453 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID(); 3454 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 3455 LE.write<uint16_t>(Bits); 3456 Bits = 0; 3457 bool HadMacroDefinition = MacroOffset != 0; 3458 Bits = (Bits << 1) | unsigned(HadMacroDefinition); 3459 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 3460 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 3461 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin()); 3462 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 3463 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 3464 LE.write<uint16_t>(Bits); 3465 3466 if (HadMacroDefinition) 3467 LE.write<uint32_t>(MacroOffset); 3468 3469 if (NeedDecls) { 3470 // Emit the declaration IDs in reverse order, because the 3471 // IdentifierResolver provides the declarations as they would be 3472 // visible (e.g., the function "stat" would come before the struct 3473 // "stat"), but the ASTReader adds declarations to the end of the list 3474 // (so we need to see the struct "stat" before the function "stat"). 3475 // Only emit declarations that aren't from a chained PCH, though. 3476 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), 3477 IdResolver.end()); 3478 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(), 3479 DEnd = Decls.rend(); 3480 D != DEnd; ++D) 3481 LE.write<uint32_t>( 3482 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D))); 3483 } 3484 } 3485 }; 3486 3487 } // end anonymous namespace 3488 3489 /// \brief Write the identifier table into the AST file. 3490 /// 3491 /// The identifier table consists of a blob containing string data 3492 /// (the actual identifiers themselves) and a separate "offsets" index 3493 /// that maps identifier IDs to locations within the blob. 3494 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 3495 IdentifierResolver &IdResolver, 3496 bool IsModule) { 3497 using namespace llvm; 3498 3499 RecordData InterestingIdents; 3500 3501 // Create and write out the blob that contains the identifier 3502 // strings. 3503 { 3504 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 3505 ASTIdentifierTableTrait Trait( 3506 *this, PP, IdResolver, IsModule, 3507 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr); 3508 3509 // Look for any identifiers that were named while processing the 3510 // headers, but are otherwise not needed. We add these to the hash 3511 // table to enable checking of the predefines buffer in the case 3512 // where the user adds new macro definitions when building the AST 3513 // file. 3514 SmallVector<const IdentifierInfo *, 128> IIs; 3515 for (const auto &ID : PP.getIdentifierTable()) 3516 IIs.push_back(ID.second); 3517 // Sort the identifiers lexicographically before getting them references so 3518 // that their order is stable. 3519 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>()); 3520 for (const IdentifierInfo *II : IIs) 3521 if (Trait.isInterestingNonMacroIdentifier(II)) 3522 getIdentifierRef(II); 3523 3524 // Create the on-disk hash table representation. We only store offsets 3525 // for identifiers that appear here for the first time. 3526 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 3527 for (auto IdentIDPair : IdentifierIDs) { 3528 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first); 3529 IdentID ID = IdentIDPair.second; 3530 assert(II && "NULL identifier in identifier table"); 3531 // Write out identifiers if either the ID is local or the identifier has 3532 // changed since it was loaded. 3533 if (ID >= FirstIdentID || !Chain || !II->isFromAST() 3534 || II->hasChangedSinceDeserialization() || 3535 (Trait.needDecls() && 3536 II->hasFETokenInfoChangedSinceDeserialization())) 3537 Generator.insert(II, ID, Trait); 3538 } 3539 3540 // Create the on-disk hash table in a buffer. 3541 SmallString<4096> IdentifierTable; 3542 uint32_t BucketOffset; 3543 { 3544 using namespace llvm::support; 3545 llvm::raw_svector_ostream Out(IdentifierTable); 3546 // Make sure that no bucket is at offset 0 3547 endian::Writer<little>(Out).write<uint32_t>(0); 3548 BucketOffset = Generator.Emit(Out, Trait); 3549 } 3550 3551 // Create a blob abbreviation 3552 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3553 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 3554 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3555 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3556 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3557 3558 // Write the identifier table 3559 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset}; 3560 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable); 3561 } 3562 3563 // Write the offsets table for identifier IDs. 3564 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3565 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 3566 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 3567 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3568 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3569 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3570 3571 #ifndef NDEBUG 3572 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I) 3573 assert(IdentifierOffsets[I] && "Missing identifier offset?"); 3574 #endif 3575 3576 RecordData::value_type Record[] = {IDENTIFIER_OFFSET, 3577 IdentifierOffsets.size(), 3578 FirstIdentID - NUM_PREDEF_IDENT_IDS}; 3579 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 3580 bytes(IdentifierOffsets)); 3581 3582 // In C++, write the list of interesting identifiers (those that are 3583 // defined as macros, poisoned, or similar unusual things). 3584 if (!InterestingIdents.empty()) 3585 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents); 3586 } 3587 3588 //===----------------------------------------------------------------------===// 3589 // DeclContext's Name Lookup Table Serialization 3590 //===----------------------------------------------------------------------===// 3591 3592 namespace { 3593 3594 // Trait used for the on-disk hash table used in the method pool. 3595 class ASTDeclContextNameLookupTrait { 3596 ASTWriter &Writer; 3597 llvm::SmallVector<DeclID, 64> DeclIDs; 3598 3599 public: 3600 typedef DeclarationNameKey key_type; 3601 typedef key_type key_type_ref; 3602 3603 /// A start and end index into DeclIDs, representing a sequence of decls. 3604 typedef std::pair<unsigned, unsigned> data_type; 3605 typedef const data_type& data_type_ref; 3606 3607 typedef unsigned hash_value_type; 3608 typedef unsigned offset_type; 3609 3610 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { } 3611 3612 template<typename Coll> 3613 data_type getData(const Coll &Decls) { 3614 unsigned Start = DeclIDs.size(); 3615 for (NamedDecl *D : Decls) { 3616 DeclIDs.push_back( 3617 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D))); 3618 } 3619 return std::make_pair(Start, DeclIDs.size()); 3620 } 3621 3622 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) { 3623 unsigned Start = DeclIDs.size(); 3624 for (auto ID : FromReader) 3625 DeclIDs.push_back(ID); 3626 return std::make_pair(Start, DeclIDs.size()); 3627 } 3628 3629 static bool EqualKey(key_type_ref a, key_type_ref b) { 3630 return a == b; 3631 } 3632 3633 hash_value_type ComputeHash(DeclarationNameKey Name) { 3634 return Name.getHash(); 3635 } 3636 3637 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const { 3638 assert(Writer.hasChain() && 3639 "have reference to loaded module file but no chain?"); 3640 3641 using namespace llvm::support; 3642 endian::Writer<little>(Out) 3643 .write<uint32_t>(Writer.getChain()->getModuleFileID(F)); 3644 } 3645 3646 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out, 3647 DeclarationNameKey Name, 3648 data_type_ref Lookup) { 3649 using namespace llvm::support; 3650 endian::Writer<little> LE(Out); 3651 unsigned KeyLen = 1; 3652 switch (Name.getKind()) { 3653 case DeclarationName::Identifier: 3654 case DeclarationName::ObjCZeroArgSelector: 3655 case DeclarationName::ObjCOneArgSelector: 3656 case DeclarationName::ObjCMultiArgSelector: 3657 case DeclarationName::CXXLiteralOperatorName: 3658 case DeclarationName::CXXDeductionGuideName: 3659 KeyLen += 4; 3660 break; 3661 case DeclarationName::CXXOperatorName: 3662 KeyLen += 1; 3663 break; 3664 case DeclarationName::CXXConstructorName: 3665 case DeclarationName::CXXDestructorName: 3666 case DeclarationName::CXXConversionFunctionName: 3667 case DeclarationName::CXXUsingDirective: 3668 break; 3669 } 3670 LE.write<uint16_t>(KeyLen); 3671 3672 // 4 bytes for each DeclID. 3673 unsigned DataLen = 4 * (Lookup.second - Lookup.first); 3674 assert(uint16_t(DataLen) == DataLen && 3675 "too many decls for serialized lookup result"); 3676 LE.write<uint16_t>(DataLen); 3677 3678 return std::make_pair(KeyLen, DataLen); 3679 } 3680 3681 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) { 3682 using namespace llvm::support; 3683 endian::Writer<little> LE(Out); 3684 LE.write<uint8_t>(Name.getKind()); 3685 switch (Name.getKind()) { 3686 case DeclarationName::Identifier: 3687 case DeclarationName::CXXLiteralOperatorName: 3688 case DeclarationName::CXXDeductionGuideName: 3689 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier())); 3690 return; 3691 case DeclarationName::ObjCZeroArgSelector: 3692 case DeclarationName::ObjCOneArgSelector: 3693 case DeclarationName::ObjCMultiArgSelector: 3694 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector())); 3695 return; 3696 case DeclarationName::CXXOperatorName: 3697 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && 3698 "Invalid operator?"); 3699 LE.write<uint8_t>(Name.getOperatorKind()); 3700 return; 3701 case DeclarationName::CXXConstructorName: 3702 case DeclarationName::CXXDestructorName: 3703 case DeclarationName::CXXConversionFunctionName: 3704 case DeclarationName::CXXUsingDirective: 3705 return; 3706 } 3707 3708 llvm_unreachable("Invalid name kind?"); 3709 } 3710 3711 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup, 3712 unsigned DataLen) { 3713 using namespace llvm::support; 3714 endian::Writer<little> LE(Out); 3715 uint64_t Start = Out.tell(); (void)Start; 3716 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) 3717 LE.write<uint32_t>(DeclIDs[I]); 3718 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3719 } 3720 }; 3721 3722 } // end anonymous namespace 3723 3724 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result, 3725 DeclContext *DC) { 3726 return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage; 3727 } 3728 3729 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result, 3730 DeclContext *DC) { 3731 for (auto *D : Result.getLookupResult()) 3732 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile()) 3733 return false; 3734 3735 return true; 3736 } 3737 3738 void 3739 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC, 3740 llvm::SmallVectorImpl<char> &LookupTable) { 3741 assert(!ConstDC->HasLazyLocalLexicalLookups && 3742 !ConstDC->HasLazyExternalLexicalLookups && 3743 "must call buildLookups first"); 3744 3745 // FIXME: We need to build the lookups table, which is logically const. 3746 auto *DC = const_cast<DeclContext*>(ConstDC); 3747 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table"); 3748 3749 // Create the on-disk hash table representation. 3750 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait, 3751 ASTDeclContextNameLookupTrait> Generator; 3752 ASTDeclContextNameLookupTrait Trait(*this); 3753 3754 // The first step is to collect the declaration names which we need to 3755 // serialize into the name lookup table, and to collect them in a stable 3756 // order. 3757 SmallVector<DeclarationName, 16> Names; 3758 3759 // We also build up small sets of the constructor and conversion function 3760 // names which are visible. 3761 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet; 3762 3763 for (auto &Lookup : *DC->buildLookup()) { 3764 auto &Name = Lookup.first; 3765 auto &Result = Lookup.second; 3766 3767 // If there are no local declarations in our lookup result, we 3768 // don't need to write an entry for the name at all. If we can't 3769 // write out a lookup set without performing more deserialization, 3770 // just skip this entry. 3771 if (isLookupResultExternal(Result, DC) && 3772 isLookupResultEntirelyExternal(Result, DC)) 3773 continue; 3774 3775 // We also skip empty results. If any of the results could be external and 3776 // the currently available results are empty, then all of the results are 3777 // external and we skip it above. So the only way we get here with an empty 3778 // results is when no results could have been external *and* we have 3779 // external results. 3780 // 3781 // FIXME: While we might want to start emitting on-disk entries for negative 3782 // lookups into a decl context as an optimization, today we *have* to skip 3783 // them because there are names with empty lookup results in decl contexts 3784 // which we can't emit in any stable ordering: we lookup constructors and 3785 // conversion functions in the enclosing namespace scope creating empty 3786 // results for them. This in almost certainly a bug in Clang's name lookup, 3787 // but that is likely to be hard or impossible to fix and so we tolerate it 3788 // here by omitting lookups with empty results. 3789 if (Lookup.second.getLookupResult().empty()) 3790 continue; 3791 3792 switch (Lookup.first.getNameKind()) { 3793 default: 3794 Names.push_back(Lookup.first); 3795 break; 3796 3797 case DeclarationName::CXXConstructorName: 3798 assert(isa<CXXRecordDecl>(DC) && 3799 "Cannot have a constructor name outside of a class!"); 3800 ConstructorNameSet.insert(Name); 3801 break; 3802 3803 case DeclarationName::CXXConversionFunctionName: 3804 assert(isa<CXXRecordDecl>(DC) && 3805 "Cannot have a conversion function name outside of a class!"); 3806 ConversionNameSet.insert(Name); 3807 break; 3808 } 3809 } 3810 3811 // Sort the names into a stable order. 3812 std::sort(Names.begin(), Names.end()); 3813 3814 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) { 3815 // We need to establish an ordering of constructor and conversion function 3816 // names, and they don't have an intrinsic ordering. 3817 3818 // First we try the easy case by forming the current context's constructor 3819 // name and adding that name first. This is a very useful optimization to 3820 // avoid walking the lexical declarations in many cases, and it also 3821 // handles the only case where a constructor name can come from some other 3822 // lexical context -- when that name is an implicit constructor merged from 3823 // another declaration in the redecl chain. Any non-implicit constructor or 3824 // conversion function which doesn't occur in all the lexical contexts 3825 // would be an ODR violation. 3826 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName( 3827 Context->getCanonicalType(Context->getRecordType(D))); 3828 if (ConstructorNameSet.erase(ImplicitCtorName)) 3829 Names.push_back(ImplicitCtorName); 3830 3831 // If we still have constructors or conversion functions, we walk all the 3832 // names in the decl and add the constructors and conversion functions 3833 // which are visible in the order they lexically occur within the context. 3834 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty()) 3835 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) 3836 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) { 3837 auto Name = ChildND->getDeclName(); 3838 switch (Name.getNameKind()) { 3839 default: 3840 continue; 3841 3842 case DeclarationName::CXXConstructorName: 3843 if (ConstructorNameSet.erase(Name)) 3844 Names.push_back(Name); 3845 break; 3846 3847 case DeclarationName::CXXConversionFunctionName: 3848 if (ConversionNameSet.erase(Name)) 3849 Names.push_back(Name); 3850 break; 3851 } 3852 3853 if (ConstructorNameSet.empty() && ConversionNameSet.empty()) 3854 break; 3855 } 3856 3857 assert(ConstructorNameSet.empty() && "Failed to find all of the visible " 3858 "constructors by walking all the " 3859 "lexical members of the context."); 3860 assert(ConversionNameSet.empty() && "Failed to find all of the visible " 3861 "conversion functions by walking all " 3862 "the lexical members of the context."); 3863 } 3864 3865 // Next we need to do a lookup with each name into this decl context to fully 3866 // populate any results from external sources. We don't actually use the 3867 // results of these lookups because we only want to use the results after all 3868 // results have been loaded and the pointers into them will be stable. 3869 for (auto &Name : Names) 3870 DC->lookup(Name); 3871 3872 // Now we need to insert the results for each name into the hash table. For 3873 // constructor names and conversion function names, we actually need to merge 3874 // all of the results for them into one list of results each and insert 3875 // those. 3876 SmallVector<NamedDecl *, 8> ConstructorDecls; 3877 SmallVector<NamedDecl *, 8> ConversionDecls; 3878 3879 // Now loop over the names, either inserting them or appending for the two 3880 // special cases. 3881 for (auto &Name : Names) { 3882 DeclContext::lookup_result Result = DC->noload_lookup(Name); 3883 3884 switch (Name.getNameKind()) { 3885 default: 3886 Generator.insert(Name, Trait.getData(Result), Trait); 3887 break; 3888 3889 case DeclarationName::CXXConstructorName: 3890 ConstructorDecls.append(Result.begin(), Result.end()); 3891 break; 3892 3893 case DeclarationName::CXXConversionFunctionName: 3894 ConversionDecls.append(Result.begin(), Result.end()); 3895 break; 3896 } 3897 } 3898 3899 // Handle our two special cases if we ended up having any. We arbitrarily use 3900 // the first declaration's name here because the name itself isn't part of 3901 // the key, only the kind of name is used. 3902 if (!ConstructorDecls.empty()) 3903 Generator.insert(ConstructorDecls.front()->getDeclName(), 3904 Trait.getData(ConstructorDecls), Trait); 3905 if (!ConversionDecls.empty()) 3906 Generator.insert(ConversionDecls.front()->getDeclName(), 3907 Trait.getData(ConversionDecls), Trait); 3908 3909 // Create the on-disk hash table. Also emit the existing imported and 3910 // merged table if there is one. 3911 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr; 3912 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr); 3913 } 3914 3915 /// \brief Write the block containing all of the declaration IDs 3916 /// visible from the given DeclContext. 3917 /// 3918 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 3919 /// bitstream, or 0 if no block was written. 3920 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 3921 DeclContext *DC) { 3922 // If we imported a key declaration of this namespace, write the visible 3923 // lookup results as an update record for it rather than including them 3924 // on this declaration. We will only look at key declarations on reload. 3925 if (isa<NamespaceDecl>(DC) && Chain && 3926 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) { 3927 // Only do this once, for the first local declaration of the namespace. 3928 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev; 3929 Prev = Prev->getPreviousDecl()) 3930 if (!Prev->isFromASTFile()) 3931 return 0; 3932 3933 // Note that we need to emit an update record for the primary context. 3934 UpdatedDeclContexts.insert(DC->getPrimaryContext()); 3935 3936 // Make sure all visible decls are written. They will be recorded later. We 3937 // do this using a side data structure so we can sort the names into 3938 // a deterministic order. 3939 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup(); 3940 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16> 3941 LookupResults; 3942 if (Map) { 3943 LookupResults.reserve(Map->size()); 3944 for (auto &Entry : *Map) 3945 LookupResults.push_back( 3946 std::make_pair(Entry.first, Entry.second.getLookupResult())); 3947 } 3948 3949 std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first()); 3950 for (auto &NameAndResult : LookupResults) { 3951 DeclarationName Name = NameAndResult.first; 3952 DeclContext::lookup_result Result = NameAndResult.second; 3953 if (Name.getNameKind() == DeclarationName::CXXConstructorName || 3954 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 3955 // We have to work around a name lookup bug here where negative lookup 3956 // results for these names get cached in namespace lookup tables (these 3957 // names should never be looked up in a namespace). 3958 assert(Result.empty() && "Cannot have a constructor or conversion " 3959 "function name in a namespace!"); 3960 continue; 3961 } 3962 3963 for (NamedDecl *ND : Result) 3964 if (!ND->isFromASTFile()) 3965 GetDeclRef(ND); 3966 } 3967 3968 return 0; 3969 } 3970 3971 if (DC->getPrimaryContext() != DC) 3972 return 0; 3973 3974 // Skip contexts which don't support name lookup. 3975 if (!DC->isLookupContext()) 3976 return 0; 3977 3978 // If not in C++, we perform name lookup for the translation unit via the 3979 // IdentifierInfo chains, don't bother to build a visible-declarations table. 3980 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 3981 return 0; 3982 3983 // Serialize the contents of the mapping used for lookup. Note that, 3984 // although we have two very different code paths, the serialized 3985 // representation is the same for both cases: a declaration name, 3986 // followed by a size, followed by references to the visible 3987 // declarations that have that name. 3988 uint64_t Offset = Stream.GetCurrentBitNo(); 3989 StoredDeclsMap *Map = DC->buildLookup(); 3990 if (!Map || Map->empty()) 3991 return 0; 3992 3993 // Create the on-disk hash table in a buffer. 3994 SmallString<4096> LookupTable; 3995 GenerateNameLookupTable(DC, LookupTable); 3996 3997 // Write the lookup table 3998 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE}; 3999 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 4000 LookupTable); 4001 ++NumVisibleDeclContexts; 4002 return Offset; 4003 } 4004 4005 /// \brief Write an UPDATE_VISIBLE block for the given context. 4006 /// 4007 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 4008 /// DeclContext in a dependent AST file. As such, they only exist for the TU 4009 /// (in C++), for namespaces, and for classes with forward-declared unscoped 4010 /// enumeration members (in C++11). 4011 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 4012 StoredDeclsMap *Map = DC->getLookupPtr(); 4013 if (!Map || Map->empty()) 4014 return; 4015 4016 // Create the on-disk hash table in a buffer. 4017 SmallString<4096> LookupTable; 4018 GenerateNameLookupTable(DC, LookupTable); 4019 4020 // If we're updating a namespace, select a key declaration as the key for the 4021 // update record; those are the only ones that will be checked on reload. 4022 if (isa<NamespaceDecl>(DC)) 4023 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC))); 4024 4025 // Write the lookup table 4026 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))}; 4027 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable); 4028 } 4029 4030 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 4031 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 4032 RecordData::value_type Record[] = {Opts.getInt()}; 4033 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 4034 } 4035 4036 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 4037 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 4038 if (!SemaRef.Context.getLangOpts().OpenCL) 4039 return; 4040 4041 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 4042 RecordData Record; 4043 for (const auto &I:Opts.OptMap) { 4044 AddString(I.getKey(), Record); 4045 auto V = I.getValue(); 4046 Record.push_back(V.Supported ? 1 : 0); 4047 Record.push_back(V.Enabled ? 1 : 0); 4048 Record.push_back(V.Avail); 4049 Record.push_back(V.Core); 4050 } 4051 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 4052 } 4053 4054 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) { 4055 if (!SemaRef.Context.getLangOpts().OpenCL) 4056 return; 4057 4058 RecordData Record; 4059 for (const auto &I : SemaRef.OpenCLTypeExtMap) { 4060 Record.push_back( 4061 static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal()))); 4062 Record.push_back(I.second.size()); 4063 for (auto Ext : I.second) 4064 AddString(Ext, Record); 4065 } 4066 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record); 4067 } 4068 4069 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) { 4070 if (!SemaRef.Context.getLangOpts().OpenCL) 4071 return; 4072 4073 RecordData Record; 4074 for (const auto &I : SemaRef.OpenCLDeclExtMap) { 4075 Record.push_back(getDeclID(I.first)); 4076 Record.push_back(static_cast<unsigned>(I.second.size())); 4077 for (auto Ext : I.second) 4078 AddString(Ext, Record); 4079 } 4080 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record); 4081 } 4082 4083 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) { 4084 if (SemaRef.ForceCUDAHostDeviceDepth > 0) { 4085 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth}; 4086 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record); 4087 } 4088 } 4089 4090 void ASTWriter::WriteObjCCategories() { 4091 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 4092 RecordData Categories; 4093 4094 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 4095 unsigned Size = 0; 4096 unsigned StartIndex = Categories.size(); 4097 4098 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 4099 4100 // Allocate space for the size. 4101 Categories.push_back(0); 4102 4103 // Add the categories. 4104 for (ObjCInterfaceDecl::known_categories_iterator 4105 Cat = Class->known_categories_begin(), 4106 CatEnd = Class->known_categories_end(); 4107 Cat != CatEnd; ++Cat, ++Size) { 4108 assert(getDeclID(*Cat) != 0 && "Bogus category"); 4109 AddDeclRef(*Cat, Categories); 4110 } 4111 4112 // Update the size. 4113 Categories[StartIndex] = Size; 4114 4115 // Record this interface -> category map. 4116 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 4117 CategoriesMap.push_back(CatInfo); 4118 } 4119 4120 // Sort the categories map by the definition ID, since the reader will be 4121 // performing binary searches on this information. 4122 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 4123 4124 // Emit the categories map. 4125 using namespace llvm; 4126 4127 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4128 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 4129 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 4130 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4131 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev)); 4132 4133 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()}; 4134 Stream.EmitRecordWithBlob(AbbrevID, Record, 4135 reinterpret_cast<char *>(CategoriesMap.data()), 4136 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 4137 4138 // Emit the category lists. 4139 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 4140 } 4141 4142 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) { 4143 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap; 4144 4145 if (LPTMap.empty()) 4146 return; 4147 4148 RecordData Record; 4149 for (auto &LPTMapEntry : LPTMap) { 4150 const FunctionDecl *FD = LPTMapEntry.first; 4151 LateParsedTemplate &LPT = *LPTMapEntry.second; 4152 AddDeclRef(FD, Record); 4153 AddDeclRef(LPT.D, Record); 4154 Record.push_back(LPT.Toks.size()); 4155 4156 for (const auto &Tok : LPT.Toks) { 4157 AddToken(Tok, Record); 4158 } 4159 } 4160 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record); 4161 } 4162 4163 /// \brief Write the state of 'pragma clang optimize' at the end of the module. 4164 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) { 4165 RecordData Record; 4166 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation(); 4167 AddSourceLocation(PragmaLoc, Record); 4168 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record); 4169 } 4170 4171 /// \brief Write the state of 'pragma ms_struct' at the end of the module. 4172 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) { 4173 RecordData Record; 4174 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF); 4175 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record); 4176 } 4177 4178 /// \brief Write the state of 'pragma pointers_to_members' at the end of the 4179 //module. 4180 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) { 4181 RecordData Record; 4182 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod); 4183 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record); 4184 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record); 4185 } 4186 4187 /// \brief Write the state of 'pragma pack' at the end of the module. 4188 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) { 4189 RecordData Record; 4190 Record.push_back(SemaRef.PackStack.CurrentValue); 4191 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record); 4192 Record.push_back(SemaRef.PackStack.Stack.size()); 4193 for (const auto &StackEntry : SemaRef.PackStack.Stack) { 4194 Record.push_back(StackEntry.Value); 4195 AddSourceLocation(StackEntry.PragmaLocation, Record); 4196 AddString(StackEntry.StackSlotLabel, Record); 4197 } 4198 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record); 4199 } 4200 4201 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef, 4202 ModuleFileExtensionWriter &Writer) { 4203 // Enter the extension block. 4204 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4); 4205 4206 // Emit the metadata record abbreviation. 4207 auto Abv = std::make_shared<llvm::BitCodeAbbrev>(); 4208 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA)); 4209 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4210 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4211 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4212 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4213 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4214 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv)); 4215 4216 // Emit the metadata record. 4217 RecordData Record; 4218 auto Metadata = Writer.getExtension()->getExtensionMetadata(); 4219 Record.push_back(EXTENSION_METADATA); 4220 Record.push_back(Metadata.MajorVersion); 4221 Record.push_back(Metadata.MinorVersion); 4222 Record.push_back(Metadata.BlockName.size()); 4223 Record.push_back(Metadata.UserInfo.size()); 4224 SmallString<64> Buffer; 4225 Buffer += Metadata.BlockName; 4226 Buffer += Metadata.UserInfo; 4227 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer); 4228 4229 // Emit the contents of the extension block. 4230 Writer.writeExtensionContents(SemaRef, Stream); 4231 4232 // Exit the extension block. 4233 Stream.ExitBlock(); 4234 } 4235 4236 //===----------------------------------------------------------------------===// 4237 // General Serialization Routines 4238 //===----------------------------------------------------------------------===// 4239 4240 /// \brief Emit the list of attributes to the specified record. 4241 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) { 4242 auto &Record = *this; 4243 Record.push_back(Attrs.size()); 4244 for (const auto *A : Attrs) { 4245 Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs 4246 Record.AddSourceRange(A->getRange()); 4247 4248 #include "clang/Serialization/AttrPCHWrite.inc" 4249 4250 } 4251 } 4252 4253 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 4254 AddSourceLocation(Tok.getLocation(), Record); 4255 Record.push_back(Tok.getLength()); 4256 4257 // FIXME: When reading literal tokens, reconstruct the literal pointer 4258 // if it is needed. 4259 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 4260 // FIXME: Should translate token kind to a stable encoding. 4261 Record.push_back(Tok.getKind()); 4262 // FIXME: Should translate token flags to a stable encoding. 4263 Record.push_back(Tok.getFlags()); 4264 } 4265 4266 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 4267 Record.push_back(Str.size()); 4268 Record.insert(Record.end(), Str.begin(), Str.end()); 4269 } 4270 4271 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) { 4272 assert(Context && "should have context when outputting path"); 4273 4274 bool Changed = 4275 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path); 4276 4277 // Remove a prefix to make the path relative, if relevant. 4278 const char *PathBegin = Path.data(); 4279 const char *PathPtr = 4280 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory); 4281 if (PathPtr != PathBegin) { 4282 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin)); 4283 Changed = true; 4284 } 4285 4286 return Changed; 4287 } 4288 4289 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) { 4290 SmallString<128> FilePath(Path); 4291 PreparePathForOutput(FilePath); 4292 AddString(FilePath, Record); 4293 } 4294 4295 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, 4296 StringRef Path) { 4297 SmallString<128> FilePath(Path); 4298 PreparePathForOutput(FilePath); 4299 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath); 4300 } 4301 4302 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 4303 RecordDataImpl &Record) { 4304 Record.push_back(Version.getMajor()); 4305 if (Optional<unsigned> Minor = Version.getMinor()) 4306 Record.push_back(*Minor + 1); 4307 else 4308 Record.push_back(0); 4309 if (Optional<unsigned> Subminor = Version.getSubminor()) 4310 Record.push_back(*Subminor + 1); 4311 else 4312 Record.push_back(0); 4313 } 4314 4315 /// \brief Note that the identifier II occurs at the given offset 4316 /// within the identifier table. 4317 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 4318 IdentID ID = IdentifierIDs[II]; 4319 // Only store offsets new to this AST file. Other identifier names are looked 4320 // up earlier in the chain and thus don't need an offset. 4321 if (ID >= FirstIdentID) 4322 IdentifierOffsets[ID - FirstIdentID] = Offset; 4323 } 4324 4325 /// \brief Note that the selector Sel occurs at the given offset 4326 /// within the method pool/selector table. 4327 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 4328 unsigned ID = SelectorIDs[Sel]; 4329 assert(ID && "Unknown selector"); 4330 // Don't record offsets for selectors that are also available in a different 4331 // file. 4332 if (ID < FirstSelectorID) 4333 return; 4334 SelectorOffsets[ID - FirstSelectorID] = Offset; 4335 } 4336 4337 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream, 4338 SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache, 4339 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 4340 bool IncludeTimestamps) 4341 : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache), 4342 IncludeTimestamps(IncludeTimestamps) { 4343 for (const auto &Ext : Extensions) { 4344 if (auto Writer = Ext->createExtensionWriter(*this)) 4345 ModuleFileExtensionWriters.push_back(std::move(Writer)); 4346 } 4347 } 4348 4349 ASTWriter::~ASTWriter() { 4350 llvm::DeleteContainerSeconds(FileDeclIDs); 4351 } 4352 4353 const LangOptions &ASTWriter::getLangOpts() const { 4354 assert(WritingAST && "can't determine lang opts when not writing AST"); 4355 return Context->getLangOpts(); 4356 } 4357 4358 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const { 4359 return IncludeTimestamps ? E->getModificationTime() : 0; 4360 } 4361 4362 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 4363 const std::string &OutputFile, 4364 Module *WritingModule, StringRef isysroot, 4365 bool hasErrors) { 4366 WritingAST = true; 4367 4368 ASTHasCompilerErrors = hasErrors; 4369 4370 // Emit the file header. 4371 Stream.Emit((unsigned)'C', 8); 4372 Stream.Emit((unsigned)'P', 8); 4373 Stream.Emit((unsigned)'C', 8); 4374 Stream.Emit((unsigned)'H', 8); 4375 4376 WriteBlockInfoBlock(); 4377 4378 Context = &SemaRef.Context; 4379 PP = &SemaRef.PP; 4380 this->WritingModule = WritingModule; 4381 ASTFileSignature Signature = 4382 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 4383 Context = nullptr; 4384 PP = nullptr; 4385 this->WritingModule = nullptr; 4386 this->BaseDirectory.clear(); 4387 4388 WritingAST = false; 4389 if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) { 4390 // Construct MemoryBuffer and update buffer manager. 4391 PCMCache.addBuffer(OutputFile, 4392 llvm::MemoryBuffer::getMemBufferCopy( 4393 StringRef(Buffer.begin(), Buffer.size()))); 4394 } 4395 return Signature; 4396 } 4397 4398 template<typename Vector> 4399 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 4400 ASTWriter::RecordData &Record) { 4401 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 4402 I != E; ++I) { 4403 Writer.AddDeclRef(*I, Record); 4404 } 4405 } 4406 4407 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot, 4408 const std::string &OutputFile, 4409 Module *WritingModule) { 4410 using namespace llvm; 4411 4412 bool isModule = WritingModule != nullptr; 4413 4414 // Make sure that the AST reader knows to finalize itself. 4415 if (Chain) 4416 Chain->finalizeForWriting(); 4417 4418 ASTContext &Context = SemaRef.Context; 4419 Preprocessor &PP = SemaRef.PP; 4420 4421 // Set up predefined declaration IDs. 4422 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) { 4423 if (D) { 4424 assert(D->isCanonicalDecl() && "predefined decl is not canonical"); 4425 DeclIDs[D] = ID; 4426 } 4427 }; 4428 RegisterPredefDecl(Context.getTranslationUnitDecl(), 4429 PREDEF_DECL_TRANSLATION_UNIT_ID); 4430 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID); 4431 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID); 4432 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID); 4433 RegisterPredefDecl(Context.ObjCProtocolClassDecl, 4434 PREDEF_DECL_OBJC_PROTOCOL_ID); 4435 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID); 4436 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID); 4437 RegisterPredefDecl(Context.ObjCInstanceTypeDecl, 4438 PREDEF_DECL_OBJC_INSTANCETYPE_ID); 4439 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID); 4440 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG); 4441 RegisterPredefDecl(Context.BuiltinMSVaListDecl, 4442 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID); 4443 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID); 4444 RegisterPredefDecl(Context.MakeIntegerSeqDecl, 4445 PREDEF_DECL_MAKE_INTEGER_SEQ_ID); 4446 RegisterPredefDecl(Context.CFConstantStringTypeDecl, 4447 PREDEF_DECL_CF_CONSTANT_STRING_ID); 4448 RegisterPredefDecl(Context.CFConstantStringTagDecl, 4449 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID); 4450 RegisterPredefDecl(Context.TypePackElementDecl, 4451 PREDEF_DECL_TYPE_PACK_ELEMENT_ID); 4452 4453 // Build a record containing all of the tentative definitions in this file, in 4454 // TentativeDefinitions order. Generally, this record will be empty for 4455 // headers. 4456 RecordData TentativeDefinitions; 4457 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 4458 4459 // Build a record containing all of the file scoped decls in this file. 4460 RecordData UnusedFileScopedDecls; 4461 if (!isModule) 4462 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 4463 UnusedFileScopedDecls); 4464 4465 // Build a record containing all of the delegating constructors we still need 4466 // to resolve. 4467 RecordData DelegatingCtorDecls; 4468 if (!isModule) 4469 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 4470 4471 // Write the set of weak, undeclared identifiers. We always write the 4472 // entire table, since later PCH files in a PCH chain are only interested in 4473 // the results at the end of the chain. 4474 RecordData WeakUndeclaredIdentifiers; 4475 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) { 4476 IdentifierInfo *II = WeakUndeclaredIdentifier.first; 4477 WeakInfo &WI = WeakUndeclaredIdentifier.second; 4478 AddIdentifierRef(II, WeakUndeclaredIdentifiers); 4479 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers); 4480 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers); 4481 WeakUndeclaredIdentifiers.push_back(WI.getUsed()); 4482 } 4483 4484 // Build a record containing all of the ext_vector declarations. 4485 RecordData ExtVectorDecls; 4486 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 4487 4488 // Build a record containing all of the VTable uses information. 4489 RecordData VTableUses; 4490 if (!SemaRef.VTableUses.empty()) { 4491 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 4492 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 4493 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 4494 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 4495 } 4496 } 4497 4498 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 4499 RecordData UnusedLocalTypedefNameCandidates; 4500 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 4501 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 4502 4503 // Build a record containing all of pending implicit instantiations. 4504 RecordData PendingInstantiations; 4505 for (const auto &I : SemaRef.PendingInstantiations) { 4506 AddDeclRef(I.first, PendingInstantiations); 4507 AddSourceLocation(I.second, PendingInstantiations); 4508 } 4509 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 4510 "There are local ones at end of translation unit!"); 4511 4512 // Build a record containing some declaration references. 4513 RecordData SemaDeclRefs; 4514 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) { 4515 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 4516 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 4517 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs); 4518 } 4519 4520 RecordData CUDASpecialDeclRefs; 4521 if (Context.getcudaConfigureCallDecl()) { 4522 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 4523 } 4524 4525 // Build a record containing all of the known namespaces. 4526 RecordData KnownNamespaces; 4527 for (const auto &I : SemaRef.KnownNamespaces) { 4528 if (!I.second) 4529 AddDeclRef(I.first, KnownNamespaces); 4530 } 4531 4532 // Build a record of all used, undefined objects that require definitions. 4533 RecordData UndefinedButUsed; 4534 4535 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 4536 SemaRef.getUndefinedButUsed(Undefined); 4537 for (const auto &I : Undefined) { 4538 AddDeclRef(I.first, UndefinedButUsed); 4539 AddSourceLocation(I.second, UndefinedButUsed); 4540 } 4541 4542 // Build a record containing all delete-expressions that we would like to 4543 // analyze later in AST. 4544 RecordData DeleteExprsToAnalyze; 4545 4546 for (const auto &DeleteExprsInfo : 4547 SemaRef.getMismatchingDeleteExpressions()) { 4548 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze); 4549 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size()); 4550 for (const auto &DeleteLoc : DeleteExprsInfo.second) { 4551 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze); 4552 DeleteExprsToAnalyze.push_back(DeleteLoc.second); 4553 } 4554 } 4555 4556 // Write the control block 4557 WriteControlBlock(PP, Context, isysroot, OutputFile); 4558 4559 // Write the remaining AST contents. 4560 Stream.EnterSubblock(AST_BLOCK_ID, 5); 4561 4562 // This is so that older clang versions, before the introduction 4563 // of the control block, can read and reject the newer PCH format. 4564 { 4565 RecordData Record = {VERSION_MAJOR}; 4566 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 4567 } 4568 4569 // Create a lexical update block containing all of the declarations in the 4570 // translation unit that do not come from other AST files. 4571 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 4572 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs; 4573 for (const auto *D : TU->noload_decls()) { 4574 if (!D->isFromASTFile()) { 4575 NewGlobalKindDeclPairs.push_back(D->getKind()); 4576 NewGlobalKindDeclPairs.push_back(GetDeclRef(D)); 4577 } 4578 } 4579 4580 auto Abv = std::make_shared<BitCodeAbbrev>(); 4581 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 4582 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4583 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4584 { 4585 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL}; 4586 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 4587 bytes(NewGlobalKindDeclPairs)); 4588 } 4589 4590 // And a visible updates block for the translation unit. 4591 Abv = std::make_shared<BitCodeAbbrev>(); 4592 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 4593 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4594 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4595 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4596 WriteDeclContextVisibleUpdate(TU); 4597 4598 // If we have any extern "C" names, write out a visible update for them. 4599 if (Context.ExternCContext) 4600 WriteDeclContextVisibleUpdate(Context.ExternCContext); 4601 4602 // If the translation unit has an anonymous namespace, and we don't already 4603 // have an update block for it, write it as an update block. 4604 // FIXME: Why do we not do this if there's already an update block? 4605 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 4606 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 4607 if (Record.empty()) 4608 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 4609 } 4610 4611 // Add update records for all mangling numbers and static local numbers. 4612 // These aren't really update records, but this is a convenient way of 4613 // tagging this rare extra data onto the declarations. 4614 for (const auto &Number : Context.MangleNumbers) 4615 if (!Number.first->isFromASTFile()) 4616 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 4617 Number.second)); 4618 for (const auto &Number : Context.StaticLocalNumbers) 4619 if (!Number.first->isFromASTFile()) 4620 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 4621 Number.second)); 4622 4623 // Make sure visible decls, added to DeclContexts previously loaded from 4624 // an AST file, are registered for serialization. Likewise for template 4625 // specializations added to imported templates. 4626 for (const auto *I : DeclsToEmitEvenIfUnreferenced) { 4627 GetDeclRef(I); 4628 } 4629 4630 // Make sure all decls associated with an identifier are registered for 4631 // serialization, if we're storing decls with identifiers. 4632 if (!WritingModule || !getLangOpts().CPlusPlus) { 4633 llvm::SmallVector<const IdentifierInfo*, 256> IIs; 4634 for (const auto &ID : PP.getIdentifierTable()) { 4635 const IdentifierInfo *II = ID.second; 4636 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) 4637 IIs.push_back(II); 4638 } 4639 // Sort the identifiers to visit based on their name. 4640 std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>()); 4641 for (const IdentifierInfo *II : IIs) { 4642 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 4643 DEnd = SemaRef.IdResolver.end(); 4644 D != DEnd; ++D) { 4645 GetDeclRef(*D); 4646 } 4647 } 4648 } 4649 4650 // For method pool in the module, if it contains an entry for a selector, 4651 // the entry should be complete, containing everything introduced by that 4652 // module and all modules it imports. It's possible that the entry is out of 4653 // date, so we need to pull in the new content here. 4654 4655 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be 4656 // safe, we copy all selectors out. 4657 llvm::SmallVector<Selector, 256> AllSelectors; 4658 for (auto &SelectorAndID : SelectorIDs) 4659 AllSelectors.push_back(SelectorAndID.first); 4660 for (auto &Selector : AllSelectors) 4661 SemaRef.updateOutOfDateSelector(Selector); 4662 4663 // Form the record of special types. 4664 RecordData SpecialTypes; 4665 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 4666 AddTypeRef(Context.getFILEType(), SpecialTypes); 4667 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 4668 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 4669 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 4670 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 4671 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 4672 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 4673 4674 if (Chain) { 4675 // Write the mapping information describing our module dependencies and how 4676 // each of those modules were mapped into our own offset/ID space, so that 4677 // the reader can build the appropriate mapping to its own offset/ID space. 4678 // The map consists solely of a blob with the following format: 4679 // *(module-name-len:i16 module-name:len*i8 4680 // source-location-offset:i32 4681 // identifier-id:i32 4682 // preprocessed-entity-id:i32 4683 // macro-definition-id:i32 4684 // submodule-id:i32 4685 // selector-id:i32 4686 // declaration-id:i32 4687 // c++-base-specifiers-id:i32 4688 // type-id:i32) 4689 // 4690 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4691 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 4692 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4693 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 4694 SmallString<2048> Buffer; 4695 { 4696 llvm::raw_svector_ostream Out(Buffer); 4697 for (ModuleFile &M : Chain->ModuleMgr) { 4698 using namespace llvm::support; 4699 endian::Writer<little> LE(Out); 4700 StringRef FileName = M.FileName; 4701 LE.write<uint16_t>(FileName.size()); 4702 Out.write(FileName.data(), FileName.size()); 4703 4704 // Note: if a base ID was uint max, it would not be possible to load 4705 // another module after it or have more than one entity inside it. 4706 uint32_t None = std::numeric_limits<uint32_t>::max(); 4707 4708 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) { 4709 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 4710 if (ShouldWrite) 4711 LE.write<uint32_t>(BaseID); 4712 else 4713 LE.write<uint32_t>(None); 4714 }; 4715 4716 // These values should be unique within a chain, since they will be read 4717 // as keys into ContinuousRangeMaps. 4718 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries); 4719 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers); 4720 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros); 4721 writeBaseIDOrNone(M.BasePreprocessedEntityID, 4722 M.NumPreprocessedEntities); 4723 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules); 4724 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors); 4725 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls); 4726 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes); 4727 } 4728 } 4729 RecordData::value_type Record[] = {MODULE_OFFSET_MAP}; 4730 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 4731 Buffer.data(), Buffer.size()); 4732 } 4733 4734 RecordData DeclUpdatesOffsetsRecord; 4735 4736 // Keep writing types, declarations, and declaration update records 4737 // until we've emitted all of them. 4738 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 4739 WriteTypeAbbrevs(); 4740 WriteDeclAbbrevs(); 4741 do { 4742 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 4743 while (!DeclTypesToEmit.empty()) { 4744 DeclOrType DOT = DeclTypesToEmit.front(); 4745 DeclTypesToEmit.pop(); 4746 if (DOT.isType()) 4747 WriteType(DOT.getType()); 4748 else 4749 WriteDecl(Context, DOT.getDecl()); 4750 } 4751 } while (!DeclUpdates.empty()); 4752 Stream.ExitBlock(); 4753 4754 DoneWritingDeclsAndTypes = true; 4755 4756 // These things can only be done once we've written out decls and types. 4757 WriteTypeDeclOffsets(); 4758 if (!DeclUpdatesOffsetsRecord.empty()) 4759 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 4760 WriteFileDeclIDsMap(); 4761 WriteSourceManagerBlock(Context.getSourceManager(), PP); 4762 WriteComments(); 4763 WritePreprocessor(PP, isModule); 4764 WriteHeaderSearch(PP.getHeaderSearchInfo()); 4765 WriteSelectors(SemaRef); 4766 WriteReferencedSelectorsPool(SemaRef); 4767 WriteLateParsedTemplates(SemaRef); 4768 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 4769 WriteFPPragmaOptions(SemaRef.getFPOptions()); 4770 WriteOpenCLExtensions(SemaRef); 4771 WriteOpenCLExtensionTypes(SemaRef); 4772 WriteOpenCLExtensionDecls(SemaRef); 4773 WriteCUDAPragmas(SemaRef); 4774 4775 // If we're emitting a module, write out the submodule information. 4776 if (WritingModule) 4777 WriteSubmodules(WritingModule); 4778 4779 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 4780 4781 // Write the record containing external, unnamed definitions. 4782 if (!EagerlyDeserializedDecls.empty()) 4783 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 4784 4785 if (!ModularCodegenDecls.empty()) 4786 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls); 4787 4788 // Write the record containing tentative definitions. 4789 if (!TentativeDefinitions.empty()) 4790 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 4791 4792 // Write the record containing unused file scoped decls. 4793 if (!UnusedFileScopedDecls.empty()) 4794 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 4795 4796 // Write the record containing weak undeclared identifiers. 4797 if (!WeakUndeclaredIdentifiers.empty()) 4798 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 4799 WeakUndeclaredIdentifiers); 4800 4801 // Write the record containing ext_vector type names. 4802 if (!ExtVectorDecls.empty()) 4803 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 4804 4805 // Write the record containing VTable uses information. 4806 if (!VTableUses.empty()) 4807 Stream.EmitRecord(VTABLE_USES, VTableUses); 4808 4809 // Write the record containing potentially unused local typedefs. 4810 if (!UnusedLocalTypedefNameCandidates.empty()) 4811 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 4812 UnusedLocalTypedefNameCandidates); 4813 4814 // Write the record containing pending implicit instantiations. 4815 if (!PendingInstantiations.empty()) 4816 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 4817 4818 // Write the record containing declaration references of Sema. 4819 if (!SemaDeclRefs.empty()) 4820 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 4821 4822 // Write the record containing CUDA-specific declaration references. 4823 if (!CUDASpecialDeclRefs.empty()) 4824 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 4825 4826 // Write the delegating constructors. 4827 if (!DelegatingCtorDecls.empty()) 4828 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 4829 4830 // Write the known namespaces. 4831 if (!KnownNamespaces.empty()) 4832 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 4833 4834 // Write the undefined internal functions and variables, and inline functions. 4835 if (!UndefinedButUsed.empty()) 4836 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 4837 4838 if (!DeleteExprsToAnalyze.empty()) 4839 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze); 4840 4841 // Write the visible updates to DeclContexts. 4842 for (auto *DC : UpdatedDeclContexts) 4843 WriteDeclContextVisibleUpdate(DC); 4844 4845 if (!WritingModule) { 4846 // Write the submodules that were imported, if any. 4847 struct ModuleInfo { 4848 uint64_t ID; 4849 Module *M; 4850 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 4851 }; 4852 llvm::SmallVector<ModuleInfo, 64> Imports; 4853 for (const auto *I : Context.local_imports()) { 4854 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 4855 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 4856 I->getImportedModule())); 4857 } 4858 4859 if (!Imports.empty()) { 4860 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 4861 return A.ID < B.ID; 4862 }; 4863 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 4864 return A.ID == B.ID; 4865 }; 4866 4867 // Sort and deduplicate module IDs. 4868 std::sort(Imports.begin(), Imports.end(), Cmp); 4869 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 4870 Imports.end()); 4871 4872 RecordData ImportedModules; 4873 for (const auto &Import : Imports) { 4874 ImportedModules.push_back(Import.ID); 4875 // FIXME: If the module has macros imported then later has declarations 4876 // imported, this location won't be the right one as a location for the 4877 // declaration imports. 4878 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules); 4879 } 4880 4881 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 4882 } 4883 } 4884 4885 WriteObjCCategories(); 4886 if(!WritingModule) { 4887 WriteOptimizePragmaOptions(SemaRef); 4888 WriteMSStructPragmaOptions(SemaRef); 4889 WriteMSPointersToMembersPragmaOptions(SemaRef); 4890 } 4891 WritePackPragmaOptions(SemaRef); 4892 4893 // Some simple statistics 4894 RecordData::value_type Record[] = { 4895 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts}; 4896 Stream.EmitRecord(STATISTICS, Record); 4897 Stream.ExitBlock(); 4898 4899 // Write the module file extension blocks. 4900 for (const auto &ExtWriter : ModuleFileExtensionWriters) 4901 WriteModuleFileExtension(SemaRef, *ExtWriter); 4902 4903 return writeUnhashedControlBlock(PP, Context); 4904 } 4905 4906 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 4907 if (DeclUpdates.empty()) 4908 return; 4909 4910 DeclUpdateMap LocalUpdates; 4911 LocalUpdates.swap(DeclUpdates); 4912 4913 for (auto &DeclUpdate : LocalUpdates) { 4914 const Decl *D = DeclUpdate.first; 4915 4916 bool HasUpdatedBody = false; 4917 RecordData RecordData; 4918 ASTRecordWriter Record(*this, RecordData); 4919 for (auto &Update : DeclUpdate.second) { 4920 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 4921 4922 // An updated body is emitted last, so that the reader doesn't need 4923 // to skip over the lazy body to reach statements for other records. 4924 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION) 4925 HasUpdatedBody = true; 4926 else 4927 Record.push_back(Kind); 4928 4929 switch (Kind) { 4930 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 4931 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 4932 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 4933 assert(Update.getDecl() && "no decl to add?"); 4934 Record.push_back(GetDeclRef(Update.getDecl())); 4935 break; 4936 4937 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 4938 break; 4939 4940 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: 4941 Record.AddSourceLocation(Update.getLoc()); 4942 break; 4943 4944 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: 4945 Record.AddStmt(const_cast<Expr *>( 4946 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg())); 4947 break; 4948 4949 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: 4950 Record.AddStmt( 4951 cast<FieldDecl>(Update.getDecl())->getInClassInitializer()); 4952 break; 4953 4954 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 4955 auto *RD = cast<CXXRecordDecl>(D); 4956 UpdatedDeclContexts.insert(RD->getPrimaryContext()); 4957 Record.AddCXXDefinitionData(RD); 4958 Record.AddOffset(WriteDeclContextLexicalBlock( 4959 *Context, const_cast<CXXRecordDecl *>(RD))); 4960 4961 // This state is sometimes updated by template instantiation, when we 4962 // switch from the specialization referring to the template declaration 4963 // to it referring to the template definition. 4964 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 4965 Record.push_back(MSInfo->getTemplateSpecializationKind()); 4966 Record.AddSourceLocation(MSInfo->getPointOfInstantiation()); 4967 } else { 4968 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 4969 Record.push_back(Spec->getTemplateSpecializationKind()); 4970 Record.AddSourceLocation(Spec->getPointOfInstantiation()); 4971 4972 // The instantiation might have been resolved to a partial 4973 // specialization. If so, record which one. 4974 auto From = Spec->getInstantiatedFrom(); 4975 if (auto PartialSpec = 4976 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 4977 Record.push_back(true); 4978 Record.AddDeclRef(PartialSpec); 4979 Record.AddTemplateArgumentList( 4980 &Spec->getTemplateInstantiationArgs()); 4981 } else { 4982 Record.push_back(false); 4983 } 4984 } 4985 Record.push_back(RD->getTagKind()); 4986 Record.AddSourceLocation(RD->getLocation()); 4987 Record.AddSourceLocation(RD->getLocStart()); 4988 Record.AddSourceRange(RD->getBraceRange()); 4989 4990 // Instantiation may change attributes; write them all out afresh. 4991 Record.push_back(D->hasAttrs()); 4992 if (D->hasAttrs()) 4993 Record.AddAttributes(D->getAttrs()); 4994 4995 // FIXME: Ensure we don't get here for explicit instantiations. 4996 break; 4997 } 4998 4999 case UPD_CXX_RESOLVED_DTOR_DELETE: 5000 Record.AddDeclRef(Update.getDecl()); 5001 break; 5002 5003 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: 5004 addExceptionSpec( 5005 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(), 5006 Record); 5007 break; 5008 5009 case UPD_CXX_DEDUCED_RETURN_TYPE: 5010 Record.push_back(GetOrCreateTypeID(Update.getType())); 5011 break; 5012 5013 case UPD_DECL_MARKED_USED: 5014 break; 5015 5016 case UPD_MANGLING_NUMBER: 5017 case UPD_STATIC_LOCAL_NUMBER: 5018 Record.push_back(Update.getNumber()); 5019 break; 5020 5021 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 5022 Record.AddSourceRange( 5023 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange()); 5024 break; 5025 5026 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 5027 Record.AddSourceRange( 5028 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange()); 5029 break; 5030 5031 case UPD_DECL_EXPORTED: 5032 Record.push_back(getSubmoduleID(Update.getModule())); 5033 break; 5034 5035 case UPD_ADDED_ATTR_TO_RECORD: 5036 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr())); 5037 break; 5038 } 5039 } 5040 5041 if (HasUpdatedBody) { 5042 const auto *Def = cast<FunctionDecl>(D); 5043 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 5044 Record.push_back(Def->isInlined()); 5045 Record.AddSourceLocation(Def->getInnerLocStart()); 5046 Record.AddFunctionDefinition(Def); 5047 } 5048 5049 OffsetsRecord.push_back(GetDeclRef(D)); 5050 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES)); 5051 } 5052 } 5053 5054 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 5055 uint32_t Raw = Loc.getRawEncoding(); 5056 Record.push_back((Raw << 1) | (Raw >> 31)); 5057 } 5058 5059 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 5060 AddSourceLocation(Range.getBegin(), Record); 5061 AddSourceLocation(Range.getEnd(), Record); 5062 } 5063 5064 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) { 5065 Record->push_back(Value.getBitWidth()); 5066 const uint64_t *Words = Value.getRawData(); 5067 Record->append(Words, Words + Value.getNumWords()); 5068 } 5069 5070 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) { 5071 Record->push_back(Value.isUnsigned()); 5072 AddAPInt(Value); 5073 } 5074 5075 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) { 5076 AddAPInt(Value.bitcastToAPInt()); 5077 } 5078 5079 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 5080 Record.push_back(getIdentifierRef(II)); 5081 } 5082 5083 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 5084 if (!II) 5085 return 0; 5086 5087 IdentID &ID = IdentifierIDs[II]; 5088 if (ID == 0) 5089 ID = NextIdentID++; 5090 return ID; 5091 } 5092 5093 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 5094 // Don't emit builtin macros like __LINE__ to the AST file unless they 5095 // have been redefined by the header (in which case they are not 5096 // isBuiltinMacro). 5097 if (!MI || MI->isBuiltinMacro()) 5098 return 0; 5099 5100 MacroID &ID = MacroIDs[MI]; 5101 if (ID == 0) { 5102 ID = NextMacroID++; 5103 MacroInfoToEmitData Info = { Name, MI, ID }; 5104 MacroInfosToEmit.push_back(Info); 5105 } 5106 return ID; 5107 } 5108 5109 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 5110 if (!MI || MI->isBuiltinMacro()) 5111 return 0; 5112 5113 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 5114 return MacroIDs[MI]; 5115 } 5116 5117 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 5118 return IdentMacroDirectivesOffsetMap.lookup(Name); 5119 } 5120 5121 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) { 5122 Record->push_back(Writer->getSelectorRef(SelRef)); 5123 } 5124 5125 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 5126 if (Sel.getAsOpaquePtr() == nullptr) { 5127 return 0; 5128 } 5129 5130 SelectorID SID = SelectorIDs[Sel]; 5131 if (SID == 0 && Chain) { 5132 // This might trigger a ReadSelector callback, which will set the ID for 5133 // this selector. 5134 Chain->LoadSelector(Sel); 5135 SID = SelectorIDs[Sel]; 5136 } 5137 if (SID == 0) { 5138 SID = NextSelectorID++; 5139 SelectorIDs[Sel] = SID; 5140 } 5141 return SID; 5142 } 5143 5144 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) { 5145 AddDeclRef(Temp->getDestructor()); 5146 } 5147 5148 void ASTRecordWriter::AddTemplateArgumentLocInfo( 5149 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) { 5150 switch (Kind) { 5151 case TemplateArgument::Expression: 5152 AddStmt(Arg.getAsExpr()); 5153 break; 5154 case TemplateArgument::Type: 5155 AddTypeSourceInfo(Arg.getAsTypeSourceInfo()); 5156 break; 5157 case TemplateArgument::Template: 5158 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5159 AddSourceLocation(Arg.getTemplateNameLoc()); 5160 break; 5161 case TemplateArgument::TemplateExpansion: 5162 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5163 AddSourceLocation(Arg.getTemplateNameLoc()); 5164 AddSourceLocation(Arg.getTemplateEllipsisLoc()); 5165 break; 5166 case TemplateArgument::Null: 5167 case TemplateArgument::Integral: 5168 case TemplateArgument::Declaration: 5169 case TemplateArgument::NullPtr: 5170 case TemplateArgument::Pack: 5171 // FIXME: Is this right? 5172 break; 5173 } 5174 } 5175 5176 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) { 5177 AddTemplateArgument(Arg.getArgument()); 5178 5179 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 5180 bool InfoHasSameExpr 5181 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 5182 Record->push_back(InfoHasSameExpr); 5183 if (InfoHasSameExpr) 5184 return; // Avoid storing the same expr twice. 5185 } 5186 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo()); 5187 } 5188 5189 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) { 5190 if (!TInfo) { 5191 AddTypeRef(QualType()); 5192 return; 5193 } 5194 5195 AddTypeLoc(TInfo->getTypeLoc()); 5196 } 5197 5198 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) { 5199 AddTypeRef(TL.getType()); 5200 5201 TypeLocWriter TLW(*this); 5202 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 5203 TLW.Visit(TL); 5204 } 5205 5206 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 5207 Record.push_back(GetOrCreateTypeID(T)); 5208 } 5209 5210 TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 5211 assert(Context); 5212 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5213 if (T.isNull()) 5214 return TypeIdx(); 5215 assert(!T.getLocalFastQualifiers()); 5216 5217 TypeIdx &Idx = TypeIdxs[T]; 5218 if (Idx.getIndex() == 0) { 5219 if (DoneWritingDeclsAndTypes) { 5220 assert(0 && "New type seen after serializing all the types to emit!"); 5221 return TypeIdx(); 5222 } 5223 5224 // We haven't seen this type before. Assign it a new ID and put it 5225 // into the queue of types to emit. 5226 Idx = TypeIdx(NextTypeID++); 5227 DeclTypesToEmit.push(T); 5228 } 5229 return Idx; 5230 }); 5231 } 5232 5233 TypeID ASTWriter::getTypeID(QualType T) const { 5234 assert(Context); 5235 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5236 if (T.isNull()) 5237 return TypeIdx(); 5238 assert(!T.getLocalFastQualifiers()); 5239 5240 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 5241 assert(I != TypeIdxs.end() && "Type not emitted!"); 5242 return I->second; 5243 }); 5244 } 5245 5246 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 5247 Record.push_back(GetDeclRef(D)); 5248 } 5249 5250 DeclID ASTWriter::GetDeclRef(const Decl *D) { 5251 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 5252 5253 if (!D) { 5254 return 0; 5255 } 5256 5257 // If D comes from an AST file, its declaration ID is already known and 5258 // fixed. 5259 if (D->isFromASTFile()) 5260 return D->getGlobalID(); 5261 5262 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 5263 DeclID &ID = DeclIDs[D]; 5264 if (ID == 0) { 5265 if (DoneWritingDeclsAndTypes) { 5266 assert(0 && "New decl seen after serializing all the decls to emit!"); 5267 return 0; 5268 } 5269 5270 // We haven't seen this declaration before. Give it a new ID and 5271 // enqueue it in the list of declarations to emit. 5272 ID = NextDeclID++; 5273 DeclTypesToEmit.push(const_cast<Decl *>(D)); 5274 } 5275 5276 return ID; 5277 } 5278 5279 DeclID ASTWriter::getDeclID(const Decl *D) { 5280 if (!D) 5281 return 0; 5282 5283 // If D comes from an AST file, its declaration ID is already known and 5284 // fixed. 5285 if (D->isFromASTFile()) 5286 return D->getGlobalID(); 5287 5288 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 5289 return DeclIDs[D]; 5290 } 5291 5292 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 5293 assert(ID); 5294 assert(D); 5295 5296 SourceLocation Loc = D->getLocation(); 5297 if (Loc.isInvalid()) 5298 return; 5299 5300 // We only keep track of the file-level declarations of each file. 5301 if (!D->getLexicalDeclContext()->isFileContext()) 5302 return; 5303 // FIXME: ParmVarDecls that are part of a function type of a parameter of 5304 // a function/objc method, should not have TU as lexical context. 5305 if (isa<ParmVarDecl>(D)) 5306 return; 5307 5308 SourceManager &SM = Context->getSourceManager(); 5309 SourceLocation FileLoc = SM.getFileLoc(Loc); 5310 assert(SM.isLocalSourceLocation(FileLoc)); 5311 FileID FID; 5312 unsigned Offset; 5313 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 5314 if (FID.isInvalid()) 5315 return; 5316 assert(SM.getSLocEntry(FID).isFile()); 5317 5318 DeclIDInFileInfo *&Info = FileDeclIDs[FID]; 5319 if (!Info) 5320 Info = new DeclIDInFileInfo(); 5321 5322 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 5323 LocDeclIDsTy &Decls = Info->DeclIDs; 5324 5325 if (Decls.empty() || Decls.back().first <= Offset) { 5326 Decls.push_back(LocDecl); 5327 return; 5328 } 5329 5330 LocDeclIDsTy::iterator I = 5331 std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first()); 5332 5333 Decls.insert(I, LocDecl); 5334 } 5335 5336 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) { 5337 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 5338 Record->push_back(Name.getNameKind()); 5339 switch (Name.getNameKind()) { 5340 case DeclarationName::Identifier: 5341 AddIdentifierRef(Name.getAsIdentifierInfo()); 5342 break; 5343 5344 case DeclarationName::ObjCZeroArgSelector: 5345 case DeclarationName::ObjCOneArgSelector: 5346 case DeclarationName::ObjCMultiArgSelector: 5347 AddSelectorRef(Name.getObjCSelector()); 5348 break; 5349 5350 case DeclarationName::CXXConstructorName: 5351 case DeclarationName::CXXDestructorName: 5352 case DeclarationName::CXXConversionFunctionName: 5353 AddTypeRef(Name.getCXXNameType()); 5354 break; 5355 5356 case DeclarationName::CXXDeductionGuideName: 5357 AddDeclRef(Name.getCXXDeductionGuideTemplate()); 5358 break; 5359 5360 case DeclarationName::CXXOperatorName: 5361 Record->push_back(Name.getCXXOverloadedOperator()); 5362 break; 5363 5364 case DeclarationName::CXXLiteralOperatorName: 5365 AddIdentifierRef(Name.getCXXLiteralIdentifier()); 5366 break; 5367 5368 case DeclarationName::CXXUsingDirective: 5369 // No extra data to emit 5370 break; 5371 } 5372 } 5373 5374 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 5375 assert(needsAnonymousDeclarationNumber(D) && 5376 "expected an anonymous declaration"); 5377 5378 // Number the anonymous declarations within this context, if we've not 5379 // already done so. 5380 auto It = AnonymousDeclarationNumbers.find(D); 5381 if (It == AnonymousDeclarationNumbers.end()) { 5382 auto *DC = D->getLexicalDeclContext(); 5383 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) { 5384 AnonymousDeclarationNumbers[ND] = Number; 5385 }); 5386 5387 It = AnonymousDeclarationNumbers.find(D); 5388 assert(It != AnonymousDeclarationNumbers.end() && 5389 "declaration not found within its lexical context"); 5390 } 5391 5392 return It->second; 5393 } 5394 5395 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 5396 DeclarationName Name) { 5397 switch (Name.getNameKind()) { 5398 case DeclarationName::CXXConstructorName: 5399 case DeclarationName::CXXDestructorName: 5400 case DeclarationName::CXXConversionFunctionName: 5401 AddTypeSourceInfo(DNLoc.NamedType.TInfo); 5402 break; 5403 5404 case DeclarationName::CXXOperatorName: 5405 AddSourceLocation(SourceLocation::getFromRawEncoding( 5406 DNLoc.CXXOperatorName.BeginOpNameLoc)); 5407 AddSourceLocation( 5408 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc)); 5409 break; 5410 5411 case DeclarationName::CXXLiteralOperatorName: 5412 AddSourceLocation(SourceLocation::getFromRawEncoding( 5413 DNLoc.CXXLiteralOperatorName.OpNameLoc)); 5414 break; 5415 5416 case DeclarationName::Identifier: 5417 case DeclarationName::ObjCZeroArgSelector: 5418 case DeclarationName::ObjCOneArgSelector: 5419 case DeclarationName::ObjCMultiArgSelector: 5420 case DeclarationName::CXXUsingDirective: 5421 case DeclarationName::CXXDeductionGuideName: 5422 break; 5423 } 5424 } 5425 5426 void ASTRecordWriter::AddDeclarationNameInfo( 5427 const DeclarationNameInfo &NameInfo) { 5428 AddDeclarationName(NameInfo.getName()); 5429 AddSourceLocation(NameInfo.getLoc()); 5430 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName()); 5431 } 5432 5433 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) { 5434 AddNestedNameSpecifierLoc(Info.QualifierLoc); 5435 Record->push_back(Info.NumTemplParamLists); 5436 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i) 5437 AddTemplateParameterList(Info.TemplParamLists[i]); 5438 } 5439 5440 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) { 5441 // Nested name specifiers usually aren't too long. I think that 8 would 5442 // typically accommodate the vast majority. 5443 SmallVector<NestedNameSpecifier *, 8> NestedNames; 5444 5445 // Push each of the NNS's onto a stack for serialization in reverse order. 5446 while (NNS) { 5447 NestedNames.push_back(NNS); 5448 NNS = NNS->getPrefix(); 5449 } 5450 5451 Record->push_back(NestedNames.size()); 5452 while(!NestedNames.empty()) { 5453 NNS = NestedNames.pop_back_val(); 5454 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 5455 Record->push_back(Kind); 5456 switch (Kind) { 5457 case NestedNameSpecifier::Identifier: 5458 AddIdentifierRef(NNS->getAsIdentifier()); 5459 break; 5460 5461 case NestedNameSpecifier::Namespace: 5462 AddDeclRef(NNS->getAsNamespace()); 5463 break; 5464 5465 case NestedNameSpecifier::NamespaceAlias: 5466 AddDeclRef(NNS->getAsNamespaceAlias()); 5467 break; 5468 5469 case NestedNameSpecifier::TypeSpec: 5470 case NestedNameSpecifier::TypeSpecWithTemplate: 5471 AddTypeRef(QualType(NNS->getAsType(), 0)); 5472 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5473 break; 5474 5475 case NestedNameSpecifier::Global: 5476 // Don't need to write an associated value. 5477 break; 5478 5479 case NestedNameSpecifier::Super: 5480 AddDeclRef(NNS->getAsRecordDecl()); 5481 break; 5482 } 5483 } 5484 } 5485 5486 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 5487 // Nested name specifiers usually aren't too long. I think that 8 would 5488 // typically accommodate the vast majority. 5489 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 5490 5491 // Push each of the nested-name-specifiers's onto a stack for 5492 // serialization in reverse order. 5493 while (NNS) { 5494 NestedNames.push_back(NNS); 5495 NNS = NNS.getPrefix(); 5496 } 5497 5498 Record->push_back(NestedNames.size()); 5499 while(!NestedNames.empty()) { 5500 NNS = NestedNames.pop_back_val(); 5501 NestedNameSpecifier::SpecifierKind Kind 5502 = NNS.getNestedNameSpecifier()->getKind(); 5503 Record->push_back(Kind); 5504 switch (Kind) { 5505 case NestedNameSpecifier::Identifier: 5506 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier()); 5507 AddSourceRange(NNS.getLocalSourceRange()); 5508 break; 5509 5510 case NestedNameSpecifier::Namespace: 5511 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace()); 5512 AddSourceRange(NNS.getLocalSourceRange()); 5513 break; 5514 5515 case NestedNameSpecifier::NamespaceAlias: 5516 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias()); 5517 AddSourceRange(NNS.getLocalSourceRange()); 5518 break; 5519 5520 case NestedNameSpecifier::TypeSpec: 5521 case NestedNameSpecifier::TypeSpecWithTemplate: 5522 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5523 AddTypeLoc(NNS.getTypeLoc()); 5524 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5525 break; 5526 5527 case NestedNameSpecifier::Global: 5528 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5529 break; 5530 5531 case NestedNameSpecifier::Super: 5532 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl()); 5533 AddSourceRange(NNS.getLocalSourceRange()); 5534 break; 5535 } 5536 } 5537 } 5538 5539 void ASTRecordWriter::AddTemplateName(TemplateName Name) { 5540 TemplateName::NameKind Kind = Name.getKind(); 5541 Record->push_back(Kind); 5542 switch (Kind) { 5543 case TemplateName::Template: 5544 AddDeclRef(Name.getAsTemplateDecl()); 5545 break; 5546 5547 case TemplateName::OverloadedTemplate: { 5548 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 5549 Record->push_back(OvT->size()); 5550 for (const auto &I : *OvT) 5551 AddDeclRef(I); 5552 break; 5553 } 5554 5555 case TemplateName::QualifiedTemplate: { 5556 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 5557 AddNestedNameSpecifier(QualT->getQualifier()); 5558 Record->push_back(QualT->hasTemplateKeyword()); 5559 AddDeclRef(QualT->getTemplateDecl()); 5560 break; 5561 } 5562 5563 case TemplateName::DependentTemplate: { 5564 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 5565 AddNestedNameSpecifier(DepT->getQualifier()); 5566 Record->push_back(DepT->isIdentifier()); 5567 if (DepT->isIdentifier()) 5568 AddIdentifierRef(DepT->getIdentifier()); 5569 else 5570 Record->push_back(DepT->getOperator()); 5571 break; 5572 } 5573 5574 case TemplateName::SubstTemplateTemplateParm: { 5575 SubstTemplateTemplateParmStorage *subst 5576 = Name.getAsSubstTemplateTemplateParm(); 5577 AddDeclRef(subst->getParameter()); 5578 AddTemplateName(subst->getReplacement()); 5579 break; 5580 } 5581 5582 case TemplateName::SubstTemplateTemplateParmPack: { 5583 SubstTemplateTemplateParmPackStorage *SubstPack 5584 = Name.getAsSubstTemplateTemplateParmPack(); 5585 AddDeclRef(SubstPack->getParameterPack()); 5586 AddTemplateArgument(SubstPack->getArgumentPack()); 5587 break; 5588 } 5589 } 5590 } 5591 5592 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) { 5593 Record->push_back(Arg.getKind()); 5594 switch (Arg.getKind()) { 5595 case TemplateArgument::Null: 5596 break; 5597 case TemplateArgument::Type: 5598 AddTypeRef(Arg.getAsType()); 5599 break; 5600 case TemplateArgument::Declaration: 5601 AddDeclRef(Arg.getAsDecl()); 5602 AddTypeRef(Arg.getParamTypeForDecl()); 5603 break; 5604 case TemplateArgument::NullPtr: 5605 AddTypeRef(Arg.getNullPtrType()); 5606 break; 5607 case TemplateArgument::Integral: 5608 AddAPSInt(Arg.getAsIntegral()); 5609 AddTypeRef(Arg.getIntegralType()); 5610 break; 5611 case TemplateArgument::Template: 5612 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 5613 break; 5614 case TemplateArgument::TemplateExpansion: 5615 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 5616 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 5617 Record->push_back(*NumExpansions + 1); 5618 else 5619 Record->push_back(0); 5620 break; 5621 case TemplateArgument::Expression: 5622 AddStmt(Arg.getAsExpr()); 5623 break; 5624 case TemplateArgument::Pack: 5625 Record->push_back(Arg.pack_size()); 5626 for (const auto &P : Arg.pack_elements()) 5627 AddTemplateArgument(P); 5628 break; 5629 } 5630 } 5631 5632 void ASTRecordWriter::AddTemplateParameterList( 5633 const TemplateParameterList *TemplateParams) { 5634 assert(TemplateParams && "No TemplateParams!"); 5635 AddSourceLocation(TemplateParams->getTemplateLoc()); 5636 AddSourceLocation(TemplateParams->getLAngleLoc()); 5637 AddSourceLocation(TemplateParams->getRAngleLoc()); 5638 // TODO: Concepts 5639 Record->push_back(TemplateParams->size()); 5640 for (const auto &P : *TemplateParams) 5641 AddDeclRef(P); 5642 } 5643 5644 /// \brief Emit a template argument list. 5645 void ASTRecordWriter::AddTemplateArgumentList( 5646 const TemplateArgumentList *TemplateArgs) { 5647 assert(TemplateArgs && "No TemplateArgs!"); 5648 Record->push_back(TemplateArgs->size()); 5649 for (int i = 0, e = TemplateArgs->size(); i != e; ++i) 5650 AddTemplateArgument(TemplateArgs->get(i)); 5651 } 5652 5653 void ASTRecordWriter::AddASTTemplateArgumentListInfo( 5654 const ASTTemplateArgumentListInfo *ASTTemplArgList) { 5655 assert(ASTTemplArgList && "No ASTTemplArgList!"); 5656 AddSourceLocation(ASTTemplArgList->LAngleLoc); 5657 AddSourceLocation(ASTTemplArgList->RAngleLoc); 5658 Record->push_back(ASTTemplArgList->NumTemplateArgs); 5659 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 5660 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 5661 AddTemplateArgumentLoc(TemplArgs[i]); 5662 } 5663 5664 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) { 5665 Record->push_back(Set.size()); 5666 for (ASTUnresolvedSet::const_iterator 5667 I = Set.begin(), E = Set.end(); I != E; ++I) { 5668 AddDeclRef(I.getDecl()); 5669 Record->push_back(I.getAccess()); 5670 } 5671 } 5672 5673 // FIXME: Move this out of the main ASTRecordWriter interface. 5674 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 5675 Record->push_back(Base.isVirtual()); 5676 Record->push_back(Base.isBaseOfClass()); 5677 Record->push_back(Base.getAccessSpecifierAsWritten()); 5678 Record->push_back(Base.getInheritConstructors()); 5679 AddTypeSourceInfo(Base.getTypeSourceInfo()); 5680 AddSourceRange(Base.getSourceRange()); 5681 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 5682 : SourceLocation()); 5683 } 5684 5685 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, 5686 ArrayRef<CXXBaseSpecifier> Bases) { 5687 ASTWriter::RecordData Record; 5688 ASTRecordWriter Writer(W, Record); 5689 Writer.push_back(Bases.size()); 5690 5691 for (auto &Base : Bases) 5692 Writer.AddCXXBaseSpecifier(Base); 5693 5694 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS); 5695 } 5696 5697 // FIXME: Move this out of the main ASTRecordWriter interface. 5698 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) { 5699 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases)); 5700 } 5701 5702 static uint64_t 5703 EmitCXXCtorInitializers(ASTWriter &W, 5704 ArrayRef<CXXCtorInitializer *> CtorInits) { 5705 ASTWriter::RecordData Record; 5706 ASTRecordWriter Writer(W, Record); 5707 Writer.push_back(CtorInits.size()); 5708 5709 for (auto *Init : CtorInits) { 5710 if (Init->isBaseInitializer()) { 5711 Writer.push_back(CTOR_INITIALIZER_BASE); 5712 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5713 Writer.push_back(Init->isBaseVirtual()); 5714 } else if (Init->isDelegatingInitializer()) { 5715 Writer.push_back(CTOR_INITIALIZER_DELEGATING); 5716 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 5717 } else if (Init->isMemberInitializer()){ 5718 Writer.push_back(CTOR_INITIALIZER_MEMBER); 5719 Writer.AddDeclRef(Init->getMember()); 5720 } else { 5721 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 5722 Writer.AddDeclRef(Init->getIndirectMember()); 5723 } 5724 5725 Writer.AddSourceLocation(Init->getMemberLocation()); 5726 Writer.AddStmt(Init->getInit()); 5727 Writer.AddSourceLocation(Init->getLParenLoc()); 5728 Writer.AddSourceLocation(Init->getRParenLoc()); 5729 Writer.push_back(Init->isWritten()); 5730 if (Init->isWritten()) 5731 Writer.push_back(Init->getSourceOrder()); 5732 } 5733 5734 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS); 5735 } 5736 5737 // FIXME: Move this out of the main ASTRecordWriter interface. 5738 void ASTRecordWriter::AddCXXCtorInitializers( 5739 ArrayRef<CXXCtorInitializer *> CtorInits) { 5740 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits)); 5741 } 5742 5743 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) { 5744 auto &Data = D->data(); 5745 Record->push_back(Data.IsLambda); 5746 Record->push_back(Data.UserDeclaredConstructor); 5747 Record->push_back(Data.UserDeclaredSpecialMembers); 5748 Record->push_back(Data.Aggregate); 5749 Record->push_back(Data.PlainOldData); 5750 Record->push_back(Data.Empty); 5751 Record->push_back(Data.Polymorphic); 5752 Record->push_back(Data.Abstract); 5753 Record->push_back(Data.IsStandardLayout); 5754 Record->push_back(Data.HasNoNonEmptyBases); 5755 Record->push_back(Data.HasPrivateFields); 5756 Record->push_back(Data.HasProtectedFields); 5757 Record->push_back(Data.HasPublicFields); 5758 Record->push_back(Data.HasMutableFields); 5759 Record->push_back(Data.HasVariantMembers); 5760 Record->push_back(Data.HasOnlyCMembers); 5761 Record->push_back(Data.HasInClassInitializer); 5762 Record->push_back(Data.HasUninitializedReferenceMember); 5763 Record->push_back(Data.HasUninitializedFields); 5764 Record->push_back(Data.HasInheritedConstructor); 5765 Record->push_back(Data.HasInheritedAssignment); 5766 Record->push_back(Data.NeedOverloadResolutionForMoveConstructor); 5767 Record->push_back(Data.NeedOverloadResolutionForMoveAssignment); 5768 Record->push_back(Data.NeedOverloadResolutionForDestructor); 5769 Record->push_back(Data.DefaultedMoveConstructorIsDeleted); 5770 Record->push_back(Data.DefaultedMoveAssignmentIsDeleted); 5771 Record->push_back(Data.DefaultedDestructorIsDeleted); 5772 Record->push_back(Data.HasTrivialSpecialMembers); 5773 Record->push_back(Data.DeclaredNonTrivialSpecialMembers); 5774 Record->push_back(Data.HasIrrelevantDestructor); 5775 Record->push_back(Data.HasConstexprNonCopyMoveConstructor); 5776 Record->push_back(Data.HasDefaultedDefaultConstructor); 5777 Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr); 5778 Record->push_back(Data.HasConstexprDefaultConstructor); 5779 Record->push_back(Data.HasNonLiteralTypeFieldsOrBases); 5780 Record->push_back(Data.ComputedVisibleConversions); 5781 Record->push_back(Data.UserProvidedDefaultConstructor); 5782 Record->push_back(Data.DeclaredSpecialMembers); 5783 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase); 5784 Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase); 5785 Record->push_back(Data.ImplicitCopyAssignmentHasConstParam); 5786 Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam); 5787 Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam); 5788 5789 // getODRHash will compute the ODRHash if it has not been previously computed. 5790 Record->push_back(D->getODRHash()); 5791 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo && 5792 Writer->WritingModule && !D->isDependentType(); 5793 Record->push_back(ModulesDebugInfo); 5794 if (ModulesDebugInfo) 5795 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D)); 5796 5797 // IsLambda bit is already saved. 5798 5799 Record->push_back(Data.NumBases); 5800 if (Data.NumBases > 0) 5801 AddCXXBaseSpecifiers(Data.bases()); 5802 5803 // FIXME: Make VBases lazily computed when needed to avoid storing them. 5804 Record->push_back(Data.NumVBases); 5805 if (Data.NumVBases > 0) 5806 AddCXXBaseSpecifiers(Data.vbases()); 5807 5808 AddUnresolvedSet(Data.Conversions.get(*Writer->Context)); 5809 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context)); 5810 // Data.Definition is the owning decl, no need to write it. 5811 AddDeclRef(D->getFirstFriend()); 5812 5813 // Add lambda-specific data. 5814 if (Data.IsLambda) { 5815 auto &Lambda = D->getLambdaData(); 5816 Record->push_back(Lambda.Dependent); 5817 Record->push_back(Lambda.IsGenericLambda); 5818 Record->push_back(Lambda.CaptureDefault); 5819 Record->push_back(Lambda.NumCaptures); 5820 Record->push_back(Lambda.NumExplicitCaptures); 5821 Record->push_back(Lambda.ManglingNumber); 5822 AddDeclRef(D->getLambdaContextDecl()); 5823 AddTypeSourceInfo(Lambda.MethodTyInfo); 5824 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 5825 const LambdaCapture &Capture = Lambda.Captures[I]; 5826 AddSourceLocation(Capture.getLocation()); 5827 Record->push_back(Capture.isImplicit()); 5828 Record->push_back(Capture.getCaptureKind()); 5829 switch (Capture.getCaptureKind()) { 5830 case LCK_StarThis: 5831 case LCK_This: 5832 case LCK_VLAType: 5833 break; 5834 case LCK_ByCopy: 5835 case LCK_ByRef: 5836 VarDecl *Var = 5837 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 5838 AddDeclRef(Var); 5839 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 5840 : SourceLocation()); 5841 break; 5842 } 5843 } 5844 } 5845 } 5846 5847 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 5848 assert(Reader && "Cannot remove chain"); 5849 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 5850 assert(FirstDeclID == NextDeclID && 5851 FirstTypeID == NextTypeID && 5852 FirstIdentID == NextIdentID && 5853 FirstMacroID == NextMacroID && 5854 FirstSubmoduleID == NextSubmoduleID && 5855 FirstSelectorID == NextSelectorID && 5856 "Setting chain after writing has started."); 5857 5858 Chain = Reader; 5859 5860 // Note, this will get called multiple times, once one the reader starts up 5861 // and again each time it's done reading a PCH or module. 5862 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 5863 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 5864 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 5865 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 5866 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 5867 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 5868 NextDeclID = FirstDeclID; 5869 NextTypeID = FirstTypeID; 5870 NextIdentID = FirstIdentID; 5871 NextMacroID = FirstMacroID; 5872 NextSelectorID = FirstSelectorID; 5873 NextSubmoduleID = FirstSubmoduleID; 5874 } 5875 5876 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 5877 // Always keep the highest ID. See \p TypeRead() for more information. 5878 IdentID &StoredID = IdentifierIDs[II]; 5879 if (ID > StoredID) 5880 StoredID = ID; 5881 } 5882 5883 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 5884 // Always keep the highest ID. See \p TypeRead() for more information. 5885 MacroID &StoredID = MacroIDs[MI]; 5886 if (ID > StoredID) 5887 StoredID = ID; 5888 } 5889 5890 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 5891 // Always take the highest-numbered type index. This copes with an interesting 5892 // case for chained AST writing where we schedule writing the type and then, 5893 // later, deserialize the type from another AST. In this case, we want to 5894 // keep the higher-numbered entry so that we can properly write it out to 5895 // the AST file. 5896 TypeIdx &StoredIdx = TypeIdxs[T]; 5897 if (Idx.getIndex() >= StoredIdx.getIndex()) 5898 StoredIdx = Idx; 5899 } 5900 5901 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 5902 // Always keep the highest ID. See \p TypeRead() for more information. 5903 SelectorID &StoredID = SelectorIDs[S]; 5904 if (ID > StoredID) 5905 StoredID = ID; 5906 } 5907 5908 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 5909 MacroDefinitionRecord *MD) { 5910 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 5911 MacroDefinitions[MD] = ID; 5912 } 5913 5914 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 5915 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 5916 SubmoduleIDs[Mod] = ID; 5917 } 5918 5919 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 5920 if (Chain && Chain->isProcessingUpdateRecords()) return; 5921 assert(D->isCompleteDefinition()); 5922 assert(!WritingAST && "Already writing the AST!"); 5923 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5924 // We are interested when a PCH decl is modified. 5925 if (RD->isFromASTFile()) { 5926 // A forward reference was mutated into a definition. Rewrite it. 5927 // FIXME: This happens during template instantiation, should we 5928 // have created a new definition decl instead ? 5929 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 5930 "completed a tag from another module but not by instantiation?"); 5931 DeclUpdates[RD].push_back( 5932 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 5933 } 5934 } 5935 } 5936 5937 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) { 5938 if (D->isFromASTFile()) 5939 return true; 5940 5941 // The predefined __va_list_tag struct is imported if we imported any decls. 5942 // FIXME: This is a gross hack. 5943 return D == D->getASTContext().getVaListTagDecl(); 5944 } 5945 5946 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 5947 if (Chain && Chain->isProcessingUpdateRecords()) return; 5948 assert(DC->isLookupContext() && 5949 "Should not add lookup results to non-lookup contexts!"); 5950 5951 // TU is handled elsewhere. 5952 if (isa<TranslationUnitDecl>(DC)) 5953 return; 5954 5955 // Namespaces are handled elsewhere, except for template instantiations of 5956 // FunctionTemplateDecls in namespaces. We are interested in cases where the 5957 // local instantiations are added to an imported context. Only happens when 5958 // adding ADL lookup candidates, for example templated friends. 5959 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None && 5960 !isa<FunctionTemplateDecl>(D)) 5961 return; 5962 5963 // We're only interested in cases where a local declaration is added to an 5964 // imported context. 5965 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC))) 5966 return; 5967 5968 assert(DC == DC->getPrimaryContext() && "added to non-primary context"); 5969 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 5970 assert(!WritingAST && "Already writing the AST!"); 5971 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) { 5972 // We're adding a visible declaration to a predefined decl context. Ensure 5973 // that we write out all of its lookup results so we don't get a nasty 5974 // surprise when we try to emit its lookup table. 5975 for (auto *Child : DC->decls()) 5976 DeclsToEmitEvenIfUnreferenced.push_back(Child); 5977 } 5978 DeclsToEmitEvenIfUnreferenced.push_back(D); 5979 } 5980 5981 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 5982 if (Chain && Chain->isProcessingUpdateRecords()) return; 5983 assert(D->isImplicit()); 5984 5985 // We're only interested in cases where a local declaration is added to an 5986 // imported context. 5987 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD)) 5988 return; 5989 5990 if (!isa<CXXMethodDecl>(D)) 5991 return; 5992 5993 // A decl coming from PCH was modified. 5994 assert(RD->isCompleteDefinition()); 5995 assert(!WritingAST && "Already writing the AST!"); 5996 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 5997 } 5998 5999 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 6000 if (Chain && Chain->isProcessingUpdateRecords()) return; 6001 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!"); 6002 if (!Chain) return; 6003 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6004 // If we don't already know the exception specification for this redecl 6005 // chain, add an update record for it. 6006 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D) 6007 ->getType() 6008 ->castAs<FunctionProtoType>() 6009 ->getExceptionSpecType())) 6010 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 6011 }); 6012 } 6013 6014 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 6015 if (Chain && Chain->isProcessingUpdateRecords()) return; 6016 assert(!WritingAST && "Already writing the AST!"); 6017 if (!Chain) return; 6018 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6019 DeclUpdates[D].push_back( 6020 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 6021 }); 6022 } 6023 6024 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD, 6025 const FunctionDecl *Delete) { 6026 if (Chain && Chain->isProcessingUpdateRecords()) return; 6027 assert(!WritingAST && "Already writing the AST!"); 6028 assert(Delete && "Not given an operator delete"); 6029 if (!Chain) return; 6030 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) { 6031 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete)); 6032 }); 6033 } 6034 6035 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 6036 if (Chain && Chain->isProcessingUpdateRecords()) return; 6037 assert(!WritingAST && "Already writing the AST!"); 6038 if (!D->isFromASTFile()) 6039 return; // Declaration not imported from PCH. 6040 6041 // Implicit function decl from a PCH was defined. 6042 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6043 } 6044 6045 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 6046 if (Chain && Chain->isProcessingUpdateRecords()) return; 6047 assert(!WritingAST && "Already writing the AST!"); 6048 if (!D->isFromASTFile()) 6049 return; 6050 6051 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6052 } 6053 6054 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) { 6055 if (Chain && Chain->isProcessingUpdateRecords()) return; 6056 assert(!WritingAST && "Already writing the AST!"); 6057 if (!D->isFromASTFile()) 6058 return; 6059 6060 // Since the actual instantiation is delayed, this really means that we need 6061 // to update the instantiation location. 6062 DeclUpdates[D].push_back( 6063 DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER, 6064 D->getMemberSpecializationInfo()->getPointOfInstantiation())); 6065 } 6066 6067 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) { 6068 if (Chain && Chain->isProcessingUpdateRecords()) return; 6069 assert(!WritingAST && "Already writing the AST!"); 6070 if (!D->isFromASTFile()) 6071 return; 6072 6073 DeclUpdates[D].push_back( 6074 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D)); 6075 } 6076 6077 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) { 6078 assert(!WritingAST && "Already writing the AST!"); 6079 if (!D->isFromASTFile()) 6080 return; 6081 6082 DeclUpdates[D].push_back( 6083 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D)); 6084 } 6085 6086 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 6087 const ObjCInterfaceDecl *IFD) { 6088 if (Chain && Chain->isProcessingUpdateRecords()) return; 6089 assert(!WritingAST && "Already writing the AST!"); 6090 if (!IFD->isFromASTFile()) 6091 return; // Declaration not imported from PCH. 6092 6093 assert(IFD->getDefinition() && "Category on a class without a definition?"); 6094 ObjCClassesWithCategories.insert( 6095 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 6096 } 6097 6098 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 6099 if (Chain && Chain->isProcessingUpdateRecords()) return; 6100 assert(!WritingAST && "Already writing the AST!"); 6101 6102 // If there is *any* declaration of the entity that's not from an AST file, 6103 // we can skip writing the update record. We make sure that isUsed() triggers 6104 // completion of the redeclaration chain of the entity. 6105 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl()) 6106 if (IsLocalDecl(Prev)) 6107 return; 6108 6109 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 6110 } 6111 6112 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 6113 if (Chain && Chain->isProcessingUpdateRecords()) return; 6114 assert(!WritingAST && "Already writing the AST!"); 6115 if (!D->isFromASTFile()) 6116 return; 6117 6118 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 6119 } 6120 6121 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D, 6122 const Attr *Attr) { 6123 if (Chain && Chain->isProcessingUpdateRecords()) return; 6124 assert(!WritingAST && "Already writing the AST!"); 6125 if (!D->isFromASTFile()) 6126 return; 6127 6128 DeclUpdates[D].push_back( 6129 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr)); 6130 } 6131 6132 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) { 6133 if (Chain && Chain->isProcessingUpdateRecords()) return; 6134 assert(!WritingAST && "Already writing the AST!"); 6135 assert(D->isHidden() && "expected a hidden declaration"); 6136 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M)); 6137 } 6138 6139 void ASTWriter::AddedAttributeToRecord(const Attr *Attr, 6140 const RecordDecl *Record) { 6141 if (Chain && Chain->isProcessingUpdateRecords()) return; 6142 assert(!WritingAST && "Already writing the AST!"); 6143 if (!Record->isFromASTFile()) 6144 return; 6145 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr)); 6146 } 6147 6148 void ASTWriter::AddedCXXTemplateSpecialization( 6149 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *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 6160 void ASTWriter::AddedCXXTemplateSpecialization( 6161 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 6162 assert(!WritingAST && "Already writing the AST!"); 6163 6164 if (!TD->getFirstDecl()->isFromASTFile()) 6165 return; 6166 if (Chain && Chain->isProcessingUpdateRecords()) 6167 return; 6168 6169 DeclsToEmitEvenIfUnreferenced.push_back(D); 6170 } 6171 6172 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 6173 const FunctionDecl *D) { 6174 assert(!WritingAST && "Already writing the AST!"); 6175 6176 if (!TD->getFirstDecl()->isFromASTFile()) 6177 return; 6178 if (Chain && Chain->isProcessingUpdateRecords()) 6179 return; 6180 6181 DeclsToEmitEvenIfUnreferenced.push_back(D); 6182 } 6183