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