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