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