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