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