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