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