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