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