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