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