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