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