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