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