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