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