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