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