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