1 //===- ASTWriter.cpp - AST File Writer ------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ASTWriter class, which writes AST files. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Serialization/ASTWriter.h" 14 #include "ASTCommon.h" 15 #include "ASTReaderInternals.h" 16 #include "MultiOnDiskHashTable.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTUnresolvedSet.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclBase.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclContextInternals.h" 24 #include "clang/AST/DeclFriend.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/AST/DeclTemplate.h" 27 #include "clang/AST/DeclarationName.h" 28 #include "clang/AST/Expr.h" 29 #include "clang/AST/ExprCXX.h" 30 #include "clang/AST/LambdaCapture.h" 31 #include "clang/AST/NestedNameSpecifier.h" 32 #include "clang/AST/RawCommentList.h" 33 #include "clang/AST/TemplateName.h" 34 #include "clang/AST/Type.h" 35 #include "clang/AST/TypeLocVisitor.h" 36 #include "clang/Basic/Diagnostic.h" 37 #include "clang/Basic/DiagnosticOptions.h" 38 #include "clang/Basic/FileManager.h" 39 #include "clang/Basic/FileSystemOptions.h" 40 #include "clang/Basic/IdentifierTable.h" 41 #include "clang/Basic/LLVM.h" 42 #include "clang/Basic/Lambda.h" 43 #include "clang/Basic/LangOptions.h" 44 #include "clang/Basic/Module.h" 45 #include "clang/Basic/ObjCRuntime.h" 46 #include "clang/Basic/OpenCLOptions.h" 47 #include "clang/Basic/SourceLocation.h" 48 #include "clang/Basic/SourceManager.h" 49 #include "clang/Basic/SourceManagerInternals.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/TargetInfo.h" 52 #include "clang/Basic/TargetOptions.h" 53 #include "clang/Basic/Version.h" 54 #include "clang/Lex/HeaderSearch.h" 55 #include "clang/Lex/HeaderSearchOptions.h" 56 #include "clang/Lex/MacroInfo.h" 57 #include "clang/Lex/ModuleMap.h" 58 #include "clang/Lex/PreprocessingRecord.h" 59 #include "clang/Lex/Preprocessor.h" 60 #include "clang/Lex/PreprocessorOptions.h" 61 #include "clang/Lex/Token.h" 62 #include "clang/Sema/IdentifierResolver.h" 63 #include "clang/Sema/ObjCMethodList.h" 64 #include "clang/Sema/Sema.h" 65 #include "clang/Sema/Weak.h" 66 #include "clang/Serialization/ASTReader.h" 67 #include "clang/Serialization/InMemoryModuleCache.h" 68 #include "clang/Serialization/Module.h" 69 #include "clang/Serialization/ModuleFileExtension.h" 70 #include "clang/Serialization/SerializationDiagnostic.h" 71 #include "llvm/ADT/APFloat.h" 72 #include "llvm/ADT/APInt.h" 73 #include "llvm/ADT/APSInt.h" 74 #include "llvm/ADT/ArrayRef.h" 75 #include "llvm/ADT/DenseMap.h" 76 #include "llvm/ADT/Hashing.h" 77 #include "llvm/ADT/Optional.h" 78 #include "llvm/ADT/PointerIntPair.h" 79 #include "llvm/ADT/STLExtras.h" 80 #include "llvm/ADT/ScopeExit.h" 81 #include "llvm/ADT/SmallSet.h" 82 #include "llvm/ADT/SmallString.h" 83 #include "llvm/ADT/SmallVector.h" 84 #include "llvm/ADT/StringMap.h" 85 #include "llvm/ADT/StringRef.h" 86 #include "llvm/Bitstream/BitCodes.h" 87 #include "llvm/Bitstream/BitstreamWriter.h" 88 #include "llvm/Support/Casting.h" 89 #include "llvm/Support/Compression.h" 90 #include "llvm/Support/DJB.h" 91 #include "llvm/Support/Endian.h" 92 #include "llvm/Support/EndianStream.h" 93 #include "llvm/Support/Error.h" 94 #include "llvm/Support/ErrorHandling.h" 95 #include "llvm/Support/MemoryBuffer.h" 96 #include "llvm/Support/OnDiskHashTable.h" 97 #include "llvm/Support/Path.h" 98 #include "llvm/Support/SHA1.h" 99 #include "llvm/Support/VersionTuple.h" 100 #include "llvm/Support/raw_ostream.h" 101 #include <algorithm> 102 #include <cassert> 103 #include <cstdint> 104 #include <cstdlib> 105 #include <cstring> 106 #include <ctime> 107 #include <deque> 108 #include <limits> 109 #include <memory> 110 #include <queue> 111 #include <tuple> 112 #include <utility> 113 #include <vector> 114 115 using namespace clang; 116 using namespace clang::serialization; 117 118 template <typename T, typename Allocator> 119 static StringRef bytes(const std::vector<T, Allocator> &v) { 120 if (v.empty()) return StringRef(); 121 return StringRef(reinterpret_cast<const char*>(&v[0]), 122 sizeof(T) * v.size()); 123 } 124 125 template <typename T> 126 static StringRef bytes(const SmallVectorImpl<T> &v) { 127 return StringRef(reinterpret_cast<const char*>(v.data()), 128 sizeof(T) * v.size()); 129 } 130 131 //===----------------------------------------------------------------------===// 132 // Type serialization 133 //===----------------------------------------------------------------------===// 134 135 namespace clang { 136 137 class ASTTypeWriter { 138 ASTWriter &Writer; 139 ASTRecordWriter Record; 140 141 /// Type code that corresponds to the record generated. 142 TypeCode Code = static_cast<TypeCode>(0); 143 144 /// Abbreviation to use for the record, if any. 145 unsigned AbbrevToUse = 0; 146 147 public: 148 ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record) 149 : Writer(Writer), Record(Writer, Record) {} 150 151 uint64_t Emit() { 152 return Record.Emit(Code, AbbrevToUse); 153 } 154 155 void Visit(QualType T) { 156 if (T.hasLocalNonFastQualifiers()) { 157 Qualifiers Qs = T.getLocalQualifiers(); 158 Record.AddTypeRef(T.getLocalUnqualifiedType()); 159 Record.push_back(Qs.getAsOpaqueValue()); 160 Code = TYPE_EXT_QUAL; 161 AbbrevToUse = Writer.TypeExtQualAbbrev; 162 } else { 163 switch (T->getTypeClass()) { 164 // For all of the concrete, non-dependent types, call the 165 // appropriate visitor function. 166 #define TYPE(Class, Base) \ 167 case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break; 168 #define ABSTRACT_TYPE(Class, Base) 169 #include "clang/AST/TypeNodes.inc" 170 } 171 } 172 } 173 174 void VisitArrayType(const ArrayType *T); 175 void VisitFunctionType(const FunctionType *T); 176 void VisitTagType(const TagType *T); 177 178 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T); 179 #define ABSTRACT_TYPE(Class, Base) 180 #include "clang/AST/TypeNodes.inc" 181 }; 182 183 } // namespace clang 184 185 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) { 186 llvm_unreachable("Built-in types are never serialized"); 187 } 188 189 void ASTTypeWriter::VisitComplexType(const ComplexType *T) { 190 Record.AddTypeRef(T->getElementType()); 191 Code = TYPE_COMPLEX; 192 } 193 194 void ASTTypeWriter::VisitPointerType(const PointerType *T) { 195 Record.AddTypeRef(T->getPointeeType()); 196 Code = TYPE_POINTER; 197 } 198 199 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) { 200 Record.AddTypeRef(T->getOriginalType()); 201 Code = TYPE_DECAYED; 202 } 203 204 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) { 205 Record.AddTypeRef(T->getOriginalType()); 206 Record.AddTypeRef(T->getAdjustedType()); 207 Code = TYPE_ADJUSTED; 208 } 209 210 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) { 211 Record.AddTypeRef(T->getPointeeType()); 212 Code = TYPE_BLOCK_POINTER; 213 } 214 215 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) { 216 Record.AddTypeRef(T->getPointeeTypeAsWritten()); 217 Record.push_back(T->isSpelledAsLValue()); 218 Code = TYPE_LVALUE_REFERENCE; 219 } 220 221 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) { 222 Record.AddTypeRef(T->getPointeeTypeAsWritten()); 223 Code = TYPE_RVALUE_REFERENCE; 224 } 225 226 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) { 227 Record.AddTypeRef(T->getPointeeType()); 228 Record.AddTypeRef(QualType(T->getClass(), 0)); 229 Code = TYPE_MEMBER_POINTER; 230 } 231 232 void ASTTypeWriter::VisitArrayType(const ArrayType *T) { 233 Record.AddTypeRef(T->getElementType()); 234 Record.push_back(T->getSizeModifier()); // FIXME: stable values 235 Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values 236 } 237 238 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) { 239 VisitArrayType(T); 240 Record.AddAPInt(T->getSize()); 241 Record.AddStmt(const_cast<Expr*>(T->getSizeExpr())); 242 Code = TYPE_CONSTANT_ARRAY; 243 } 244 245 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 246 VisitArrayType(T); 247 Code = TYPE_INCOMPLETE_ARRAY; 248 } 249 250 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) { 251 VisitArrayType(T); 252 Record.AddSourceLocation(T->getLBracketLoc()); 253 Record.AddSourceLocation(T->getRBracketLoc()); 254 Record.AddStmt(T->getSizeExpr()); 255 Code = TYPE_VARIABLE_ARRAY; 256 } 257 258 void ASTTypeWriter::VisitVectorType(const VectorType *T) { 259 Record.AddTypeRef(T->getElementType()); 260 Record.push_back(T->getNumElements()); 261 Record.push_back(T->getVectorKind()); 262 Code = TYPE_VECTOR; 263 } 264 265 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) { 266 VisitVectorType(T); 267 Code = TYPE_EXT_VECTOR; 268 } 269 270 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) { 271 Record.AddTypeRef(T->getReturnType()); 272 FunctionType::ExtInfo C = T->getExtInfo(); 273 Record.push_back(C.getNoReturn()); 274 Record.push_back(C.getHasRegParm()); 275 Record.push_back(C.getRegParm()); 276 // FIXME: need to stabilize encoding of calling convention... 277 Record.push_back(C.getCC()); 278 Record.push_back(C.getProducesResult()); 279 Record.push_back(C.getNoCallerSavedRegs()); 280 Record.push_back(C.getNoCfCheck()); 281 282 if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult()) 283 AbbrevToUse = 0; 284 } 285 286 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 287 VisitFunctionType(T); 288 Code = TYPE_FUNCTION_NO_PROTO; 289 } 290 291 static void addExceptionSpec(const FunctionProtoType *T, 292 ASTRecordWriter &Record) { 293 Record.push_back(T->getExceptionSpecType()); 294 if (T->getExceptionSpecType() == EST_Dynamic) { 295 Record.push_back(T->getNumExceptions()); 296 for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I) 297 Record.AddTypeRef(T->getExceptionType(I)); 298 } else if (isComputedNoexcept(T->getExceptionSpecType())) { 299 Record.AddStmt(T->getNoexceptExpr()); 300 } else if (T->getExceptionSpecType() == EST_Uninstantiated) { 301 Record.AddDeclRef(T->getExceptionSpecDecl()); 302 Record.AddDeclRef(T->getExceptionSpecTemplate()); 303 } else if (T->getExceptionSpecType() == EST_Unevaluated) { 304 Record.AddDeclRef(T->getExceptionSpecDecl()); 305 } 306 } 307 308 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) { 309 VisitFunctionType(T); 310 311 Record.push_back(T->isVariadic()); 312 Record.push_back(T->hasTrailingReturn()); 313 Record.push_back(T->getMethodQuals().getAsOpaqueValue()); 314 Record.push_back(static_cast<unsigned>(T->getRefQualifier())); 315 addExceptionSpec(T, Record); 316 317 Record.push_back(T->getNumParams()); 318 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I) 319 Record.AddTypeRef(T->getParamType(I)); 320 321 if (T->hasExtParameterInfos()) { 322 for (unsigned I = 0, N = T->getNumParams(); I != N; ++I) 323 Record.push_back(T->getExtParameterInfo(I).getOpaqueValue()); 324 } 325 326 if (T->isVariadic() || T->hasTrailingReturn() || T->getMethodQuals() || 327 T->getRefQualifier() || T->getExceptionSpecType() != EST_None || 328 T->hasExtParameterInfos()) 329 AbbrevToUse = 0; 330 331 Code = TYPE_FUNCTION_PROTO; 332 } 333 334 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) { 335 Record.AddDeclRef(T->getDecl()); 336 Code = TYPE_UNRESOLVED_USING; 337 } 338 339 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) { 340 Record.AddDeclRef(T->getDecl()); 341 assert(!T->isCanonicalUnqualified() && "Invalid typedef ?"); 342 Record.AddTypeRef(T->getCanonicalTypeInternal()); 343 Code = TYPE_TYPEDEF; 344 } 345 346 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) { 347 Record.AddStmt(T->getUnderlyingExpr()); 348 Code = TYPE_TYPEOF_EXPR; 349 } 350 351 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) { 352 Record.AddTypeRef(T->getUnderlyingType()); 353 Code = TYPE_TYPEOF; 354 } 355 356 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) { 357 Record.AddTypeRef(T->getUnderlyingType()); 358 Record.AddStmt(T->getUnderlyingExpr()); 359 Code = TYPE_DECLTYPE; 360 } 361 362 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) { 363 Record.AddTypeRef(T->getBaseType()); 364 Record.AddTypeRef(T->getUnderlyingType()); 365 Record.push_back(T->getUTTKind()); 366 Code = TYPE_UNARY_TRANSFORM; 367 } 368 369 void ASTTypeWriter::VisitAutoType(const AutoType *T) { 370 Record.AddTypeRef(T->getDeducedType()); 371 Record.push_back((unsigned)T->getKeyword()); 372 if (T->getDeducedType().isNull()) 373 Record.push_back(T->containsUnexpandedParameterPack() ? 2 : 374 T->isDependentType() ? 1 : 0); 375 Code = TYPE_AUTO; 376 } 377 378 void ASTTypeWriter::VisitDeducedTemplateSpecializationType( 379 const DeducedTemplateSpecializationType *T) { 380 Record.AddTemplateName(T->getTemplateName()); 381 Record.AddTypeRef(T->getDeducedType()); 382 if (T->getDeducedType().isNull()) 383 Record.push_back(T->isDependentType()); 384 Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION; 385 } 386 387 void ASTTypeWriter::VisitTagType(const TagType *T) { 388 Record.push_back(T->isDependentType()); 389 Record.AddDeclRef(T->getDecl()->getCanonicalDecl()); 390 assert(!T->isBeingDefined() && 391 "Cannot serialize in the middle of a type definition"); 392 } 393 394 void ASTTypeWriter::VisitRecordType(const RecordType *T) { 395 VisitTagType(T); 396 Code = TYPE_RECORD; 397 } 398 399 void ASTTypeWriter::VisitEnumType(const EnumType *T) { 400 VisitTagType(T); 401 Code = TYPE_ENUM; 402 } 403 404 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) { 405 Record.AddTypeRef(T->getModifiedType()); 406 Record.AddTypeRef(T->getEquivalentType()); 407 Record.push_back(T->getAttrKind()); 408 Code = TYPE_ATTRIBUTED; 409 } 410 411 void 412 ASTTypeWriter::VisitSubstTemplateTypeParmType( 413 const SubstTemplateTypeParmType *T) { 414 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0)); 415 Record.AddTypeRef(T->getReplacementType()); 416 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM; 417 } 418 419 void 420 ASTTypeWriter::VisitSubstTemplateTypeParmPackType( 421 const SubstTemplateTypeParmPackType *T) { 422 Record.AddTypeRef(QualType(T->getReplacedParameter(), 0)); 423 Record.AddTemplateArgument(T->getArgumentPack()); 424 Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK; 425 } 426 427 void 428 ASTTypeWriter::VisitTemplateSpecializationType( 429 const TemplateSpecializationType *T) { 430 Record.push_back(T->isDependentType()); 431 Record.AddTemplateName(T->getTemplateName()); 432 Record.push_back(T->getNumArgs()); 433 for (const auto &ArgI : *T) 434 Record.AddTemplateArgument(ArgI); 435 Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() 436 : T->isCanonicalUnqualified() 437 ? QualType() 438 : T->getCanonicalTypeInternal()); 439 Code = TYPE_TEMPLATE_SPECIALIZATION; 440 } 441 442 void 443 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) { 444 VisitArrayType(T); 445 Record.AddStmt(T->getSizeExpr()); 446 Record.AddSourceRange(T->getBracketsRange()); 447 Code = TYPE_DEPENDENT_SIZED_ARRAY; 448 } 449 450 void 451 ASTTypeWriter::VisitDependentSizedExtVectorType( 452 const DependentSizedExtVectorType *T) { 453 Record.AddTypeRef(T->getElementType()); 454 Record.AddStmt(T->getSizeExpr()); 455 Record.AddSourceLocation(T->getAttributeLoc()); 456 Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR; 457 } 458 459 void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) { 460 Record.AddTypeRef(T->getElementType()); 461 Record.AddStmt(const_cast<Expr*>(T->getSizeExpr())); 462 Record.AddSourceLocation(T->getAttributeLoc()); 463 Record.push_back(T->getVectorKind()); 464 Code = TYPE_DEPENDENT_SIZED_VECTOR; 465 } 466 467 void 468 ASTTypeWriter::VisitDependentAddressSpaceType( 469 const DependentAddressSpaceType *T) { 470 Record.AddTypeRef(T->getPointeeType()); 471 Record.AddStmt(T->getAddrSpaceExpr()); 472 Record.AddSourceLocation(T->getAttributeLoc()); 473 Code = TYPE_DEPENDENT_ADDRESS_SPACE; 474 } 475 476 void 477 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 478 Record.push_back(T->getDepth()); 479 Record.push_back(T->getIndex()); 480 Record.push_back(T->isParameterPack()); 481 Record.AddDeclRef(T->getDecl()); 482 Code = TYPE_TEMPLATE_TYPE_PARM; 483 } 484 485 void 486 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) { 487 Record.push_back(T->getKeyword()); 488 Record.AddNestedNameSpecifier(T->getQualifier()); 489 Record.AddIdentifierRef(T->getIdentifier()); 490 Record.AddTypeRef( 491 T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal()); 492 Code = TYPE_DEPENDENT_NAME; 493 } 494 495 void 496 ASTTypeWriter::VisitDependentTemplateSpecializationType( 497 const DependentTemplateSpecializationType *T) { 498 Record.push_back(T->getKeyword()); 499 Record.AddNestedNameSpecifier(T->getQualifier()); 500 Record.AddIdentifierRef(T->getIdentifier()); 501 Record.push_back(T->getNumArgs()); 502 for (const auto &I : *T) 503 Record.AddTemplateArgument(I); 504 Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION; 505 } 506 507 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) { 508 Record.AddTypeRef(T->getPattern()); 509 if (Optional<unsigned> NumExpansions = T->getNumExpansions()) 510 Record.push_back(*NumExpansions + 1); 511 else 512 Record.push_back(0); 513 Code = TYPE_PACK_EXPANSION; 514 } 515 516 void ASTTypeWriter::VisitParenType(const ParenType *T) { 517 Record.AddTypeRef(T->getInnerType()); 518 Code = TYPE_PAREN; 519 } 520 521 void ASTTypeWriter::VisitMacroQualifiedType(const MacroQualifiedType *T) { 522 Record.AddTypeRef(T->getUnderlyingType()); 523 Record.AddIdentifierRef(T->getMacroIdentifier()); 524 Code = TYPE_MACRO_QUALIFIED; 525 } 526 527 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) { 528 Record.push_back(T->getKeyword()); 529 Record.AddNestedNameSpecifier(T->getQualifier()); 530 Record.AddTypeRef(T->getNamedType()); 531 Record.AddDeclRef(T->getOwnedTagDecl()); 532 Code = TYPE_ELABORATED; 533 } 534 535 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) { 536 Record.AddDeclRef(T->getDecl()->getCanonicalDecl()); 537 Record.AddTypeRef(T->getInjectedSpecializationType()); 538 Code = TYPE_INJECTED_CLASS_NAME; 539 } 540 541 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 542 Record.AddDeclRef(T->getDecl()->getCanonicalDecl()); 543 Code = TYPE_OBJC_INTERFACE; 544 } 545 546 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) { 547 Record.AddDeclRef(T->getDecl()); 548 Record.push_back(T->getNumProtocols()); 549 for (const auto *I : T->quals()) 550 Record.AddDeclRef(I); 551 Code = TYPE_OBJC_TYPE_PARAM; 552 } 553 554 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) { 555 Record.AddTypeRef(T->getBaseType()); 556 Record.push_back(T->getTypeArgsAsWritten().size()); 557 for (auto TypeArg : T->getTypeArgsAsWritten()) 558 Record.AddTypeRef(TypeArg); 559 Record.push_back(T->getNumProtocols()); 560 for (const auto *I : T->quals()) 561 Record.AddDeclRef(I); 562 Record.push_back(T->isKindOfTypeAsWritten()); 563 Code = TYPE_OBJC_OBJECT; 564 } 565 566 void 567 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 568 Record.AddTypeRef(T->getPointeeType()); 569 Code = TYPE_OBJC_OBJECT_POINTER; 570 } 571 572 void 573 ASTTypeWriter::VisitAtomicType(const AtomicType *T) { 574 Record.AddTypeRef(T->getValueType()); 575 Code = TYPE_ATOMIC; 576 } 577 578 void 579 ASTTypeWriter::VisitPipeType(const PipeType *T) { 580 Record.AddTypeRef(T->getElementType()); 581 Record.push_back(T->isReadOnly()); 582 Code = TYPE_PIPE; 583 } 584 585 namespace { 586 587 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> { 588 ASTRecordWriter &Record; 589 590 public: 591 TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {} 592 593 #define ABSTRACT_TYPELOC(CLASS, PARENT) 594 #define TYPELOC(CLASS, PARENT) \ 595 void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc); 596 #include "clang/AST/TypeLocNodes.def" 597 598 void VisitArrayTypeLoc(ArrayTypeLoc TyLoc); 599 void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc); 600 }; 601 602 } // namespace 603 604 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 605 // nothing to do 606 } 607 608 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 609 Record.AddSourceLocation(TL.getBuiltinLoc()); 610 if (TL.needsExtraLocalData()) { 611 Record.push_back(TL.getWrittenTypeSpec()); 612 Record.push_back(TL.getWrittenSignSpec()); 613 Record.push_back(TL.getWrittenWidthSpec()); 614 Record.push_back(TL.hasModeAttr()); 615 } 616 } 617 618 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) { 619 Record.AddSourceLocation(TL.getNameLoc()); 620 } 621 622 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) { 623 Record.AddSourceLocation(TL.getStarLoc()); 624 } 625 626 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) { 627 // nothing to do 628 } 629 630 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) { 631 // nothing to do 632 } 633 634 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 635 Record.AddSourceLocation(TL.getCaretLoc()); 636 } 637 638 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 639 Record.AddSourceLocation(TL.getAmpLoc()); 640 } 641 642 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 643 Record.AddSourceLocation(TL.getAmpAmpLoc()); 644 } 645 646 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 647 Record.AddSourceLocation(TL.getStarLoc()); 648 Record.AddTypeSourceInfo(TL.getClassTInfo()); 649 } 650 651 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) { 652 Record.AddSourceLocation(TL.getLBracketLoc()); 653 Record.AddSourceLocation(TL.getRBracketLoc()); 654 Record.push_back(TL.getSizeExpr() ? 1 : 0); 655 if (TL.getSizeExpr()) 656 Record.AddStmt(TL.getSizeExpr()); 657 } 658 659 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) { 660 VisitArrayTypeLoc(TL); 661 } 662 663 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) { 664 VisitArrayTypeLoc(TL); 665 } 666 667 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) { 668 VisitArrayTypeLoc(TL); 669 } 670 671 void TypeLocWriter::VisitDependentSizedArrayTypeLoc( 672 DependentSizedArrayTypeLoc TL) { 673 VisitArrayTypeLoc(TL); 674 } 675 676 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc( 677 DependentAddressSpaceTypeLoc TL) { 678 Record.AddSourceLocation(TL.getAttrNameLoc()); 679 SourceRange range = TL.getAttrOperandParensRange(); 680 Record.AddSourceLocation(range.getBegin()); 681 Record.AddSourceLocation(range.getEnd()); 682 Record.AddStmt(TL.getAttrExprOperand()); 683 } 684 685 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc( 686 DependentSizedExtVectorTypeLoc TL) { 687 Record.AddSourceLocation(TL.getNameLoc()); 688 } 689 690 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) { 691 Record.AddSourceLocation(TL.getNameLoc()); 692 } 693 694 void TypeLocWriter::VisitDependentVectorTypeLoc( 695 DependentVectorTypeLoc TL) { 696 Record.AddSourceLocation(TL.getNameLoc()); 697 } 698 699 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) { 700 Record.AddSourceLocation(TL.getNameLoc()); 701 } 702 703 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) { 704 Record.AddSourceLocation(TL.getLocalRangeBegin()); 705 Record.AddSourceLocation(TL.getLParenLoc()); 706 Record.AddSourceLocation(TL.getRParenLoc()); 707 Record.AddSourceRange(TL.getExceptionSpecRange()); 708 Record.AddSourceLocation(TL.getLocalRangeEnd()); 709 for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) 710 Record.AddDeclRef(TL.getParam(i)); 711 } 712 713 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) { 714 VisitFunctionTypeLoc(TL); 715 } 716 717 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) { 718 VisitFunctionTypeLoc(TL); 719 } 720 721 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { 722 Record.AddSourceLocation(TL.getNameLoc()); 723 } 724 725 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) { 726 Record.AddSourceLocation(TL.getNameLoc()); 727 } 728 729 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) { 730 if (TL.getNumProtocols()) { 731 Record.AddSourceLocation(TL.getProtocolLAngleLoc()); 732 Record.AddSourceLocation(TL.getProtocolRAngleLoc()); 733 } 734 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 735 Record.AddSourceLocation(TL.getProtocolLoc(i)); 736 } 737 738 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 739 Record.AddSourceLocation(TL.getTypeofLoc()); 740 Record.AddSourceLocation(TL.getLParenLoc()); 741 Record.AddSourceLocation(TL.getRParenLoc()); 742 } 743 744 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 745 Record.AddSourceLocation(TL.getTypeofLoc()); 746 Record.AddSourceLocation(TL.getLParenLoc()); 747 Record.AddSourceLocation(TL.getRParenLoc()); 748 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo()); 749 } 750 751 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) { 752 Record.AddSourceLocation(TL.getNameLoc()); 753 } 754 755 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) { 756 Record.AddSourceLocation(TL.getKWLoc()); 757 Record.AddSourceLocation(TL.getLParenLoc()); 758 Record.AddSourceLocation(TL.getRParenLoc()); 759 Record.AddTypeSourceInfo(TL.getUnderlyingTInfo()); 760 } 761 762 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) { 763 Record.AddSourceLocation(TL.getNameLoc()); 764 } 765 766 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc( 767 DeducedTemplateSpecializationTypeLoc TL) { 768 Record.AddSourceLocation(TL.getTemplateNameLoc()); 769 } 770 771 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) { 772 Record.AddSourceLocation(TL.getNameLoc()); 773 } 774 775 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) { 776 Record.AddSourceLocation(TL.getNameLoc()); 777 } 778 779 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) { 780 Record.AddAttr(TL.getAttr()); 781 } 782 783 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 784 Record.AddSourceLocation(TL.getNameLoc()); 785 } 786 787 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc( 788 SubstTemplateTypeParmTypeLoc TL) { 789 Record.AddSourceLocation(TL.getNameLoc()); 790 } 791 792 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc( 793 SubstTemplateTypeParmPackTypeLoc TL) { 794 Record.AddSourceLocation(TL.getNameLoc()); 795 } 796 797 void TypeLocWriter::VisitTemplateSpecializationTypeLoc( 798 TemplateSpecializationTypeLoc TL) { 799 Record.AddSourceLocation(TL.getTemplateKeywordLoc()); 800 Record.AddSourceLocation(TL.getTemplateNameLoc()); 801 Record.AddSourceLocation(TL.getLAngleLoc()); 802 Record.AddSourceLocation(TL.getRAngleLoc()); 803 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 804 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(), 805 TL.getArgLoc(i).getLocInfo()); 806 } 807 808 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) { 809 Record.AddSourceLocation(TL.getLParenLoc()); 810 Record.AddSourceLocation(TL.getRParenLoc()); 811 } 812 813 void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) { 814 Record.AddSourceLocation(TL.getExpansionLoc()); 815 } 816 817 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 818 Record.AddSourceLocation(TL.getElaboratedKeywordLoc()); 819 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 820 } 821 822 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) { 823 Record.AddSourceLocation(TL.getNameLoc()); 824 } 825 826 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 827 Record.AddSourceLocation(TL.getElaboratedKeywordLoc()); 828 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 829 Record.AddSourceLocation(TL.getNameLoc()); 830 } 831 832 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc( 833 DependentTemplateSpecializationTypeLoc TL) { 834 Record.AddSourceLocation(TL.getElaboratedKeywordLoc()); 835 Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc()); 836 Record.AddSourceLocation(TL.getTemplateKeywordLoc()); 837 Record.AddSourceLocation(TL.getTemplateNameLoc()); 838 Record.AddSourceLocation(TL.getLAngleLoc()); 839 Record.AddSourceLocation(TL.getRAngleLoc()); 840 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) 841 Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(), 842 TL.getArgLoc(I).getLocInfo()); 843 } 844 845 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) { 846 Record.AddSourceLocation(TL.getEllipsisLoc()); 847 } 848 849 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 850 Record.AddSourceLocation(TL.getNameLoc()); 851 } 852 853 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 854 Record.push_back(TL.hasBaseTypeAsWritten()); 855 Record.AddSourceLocation(TL.getTypeArgsLAngleLoc()); 856 Record.AddSourceLocation(TL.getTypeArgsRAngleLoc()); 857 for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i) 858 Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i)); 859 Record.AddSourceLocation(TL.getProtocolLAngleLoc()); 860 Record.AddSourceLocation(TL.getProtocolRAngleLoc()); 861 for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i) 862 Record.AddSourceLocation(TL.getProtocolLoc(i)); 863 } 864 865 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 866 Record.AddSourceLocation(TL.getStarLoc()); 867 } 868 869 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) { 870 Record.AddSourceLocation(TL.getKWLoc()); 871 Record.AddSourceLocation(TL.getLParenLoc()); 872 Record.AddSourceLocation(TL.getRParenLoc()); 873 } 874 875 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) { 876 Record.AddSourceLocation(TL.getKWLoc()); 877 } 878 879 void ASTWriter::WriteTypeAbbrevs() { 880 using namespace llvm; 881 882 std::shared_ptr<BitCodeAbbrev> Abv; 883 884 // Abbreviation for TYPE_EXT_QUAL 885 Abv = std::make_shared<BitCodeAbbrev>(); 886 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL)); 887 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type 888 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals 889 TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv)); 890 891 // Abbreviation for TYPE_FUNCTION_PROTO 892 Abv = std::make_shared<BitCodeAbbrev>(); 893 Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO)); 894 // FunctionType 895 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType 896 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn 897 Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm 898 Abv->Add(BitCodeAbbrevOp(0)); // RegParm 899 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC 900 Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult 901 Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs 902 Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck 903 // FunctionProtoType 904 Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic 905 Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn 906 Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals 907 Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier 908 Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec 909 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams 910 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 911 Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params 912 TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv)); 913 } 914 915 //===----------------------------------------------------------------------===// 916 // ASTWriter Implementation 917 //===----------------------------------------------------------------------===// 918 919 static void EmitBlockID(unsigned ID, const char *Name, 920 llvm::BitstreamWriter &Stream, 921 ASTWriter::RecordDataImpl &Record) { 922 Record.clear(); 923 Record.push_back(ID); 924 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); 925 926 // Emit the block name if present. 927 if (!Name || Name[0] == 0) 928 return; 929 Record.clear(); 930 while (*Name) 931 Record.push_back(*Name++); 932 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); 933 } 934 935 static void EmitRecordID(unsigned ID, const char *Name, 936 llvm::BitstreamWriter &Stream, 937 ASTWriter::RecordDataImpl &Record) { 938 Record.clear(); 939 Record.push_back(ID); 940 while (*Name) 941 Record.push_back(*Name++); 942 Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); 943 } 944 945 static void AddStmtsExprs(llvm::BitstreamWriter &Stream, 946 ASTWriter::RecordDataImpl &Record) { 947 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 948 RECORD(STMT_STOP); 949 RECORD(STMT_NULL_PTR); 950 RECORD(STMT_REF_PTR); 951 RECORD(STMT_NULL); 952 RECORD(STMT_COMPOUND); 953 RECORD(STMT_CASE); 954 RECORD(STMT_DEFAULT); 955 RECORD(STMT_LABEL); 956 RECORD(STMT_ATTRIBUTED); 957 RECORD(STMT_IF); 958 RECORD(STMT_SWITCH); 959 RECORD(STMT_WHILE); 960 RECORD(STMT_DO); 961 RECORD(STMT_FOR); 962 RECORD(STMT_GOTO); 963 RECORD(STMT_INDIRECT_GOTO); 964 RECORD(STMT_CONTINUE); 965 RECORD(STMT_BREAK); 966 RECORD(STMT_RETURN); 967 RECORD(STMT_DECL); 968 RECORD(STMT_GCCASM); 969 RECORD(STMT_MSASM); 970 RECORD(EXPR_PREDEFINED); 971 RECORD(EXPR_DECL_REF); 972 RECORD(EXPR_INTEGER_LITERAL); 973 RECORD(EXPR_FLOATING_LITERAL); 974 RECORD(EXPR_IMAGINARY_LITERAL); 975 RECORD(EXPR_STRING_LITERAL); 976 RECORD(EXPR_CHARACTER_LITERAL); 977 RECORD(EXPR_PAREN); 978 RECORD(EXPR_PAREN_LIST); 979 RECORD(EXPR_UNARY_OPERATOR); 980 RECORD(EXPR_SIZEOF_ALIGN_OF); 981 RECORD(EXPR_ARRAY_SUBSCRIPT); 982 RECORD(EXPR_CALL); 983 RECORD(EXPR_MEMBER); 984 RECORD(EXPR_BINARY_OPERATOR); 985 RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR); 986 RECORD(EXPR_CONDITIONAL_OPERATOR); 987 RECORD(EXPR_IMPLICIT_CAST); 988 RECORD(EXPR_CSTYLE_CAST); 989 RECORD(EXPR_COMPOUND_LITERAL); 990 RECORD(EXPR_EXT_VECTOR_ELEMENT); 991 RECORD(EXPR_INIT_LIST); 992 RECORD(EXPR_DESIGNATED_INIT); 993 RECORD(EXPR_DESIGNATED_INIT_UPDATE); 994 RECORD(EXPR_IMPLICIT_VALUE_INIT); 995 RECORD(EXPR_NO_INIT); 996 RECORD(EXPR_VA_ARG); 997 RECORD(EXPR_ADDR_LABEL); 998 RECORD(EXPR_STMT); 999 RECORD(EXPR_CHOOSE); 1000 RECORD(EXPR_GNU_NULL); 1001 RECORD(EXPR_SHUFFLE_VECTOR); 1002 RECORD(EXPR_BLOCK); 1003 RECORD(EXPR_GENERIC_SELECTION); 1004 RECORD(EXPR_OBJC_STRING_LITERAL); 1005 RECORD(EXPR_OBJC_BOXED_EXPRESSION); 1006 RECORD(EXPR_OBJC_ARRAY_LITERAL); 1007 RECORD(EXPR_OBJC_DICTIONARY_LITERAL); 1008 RECORD(EXPR_OBJC_ENCODE); 1009 RECORD(EXPR_OBJC_SELECTOR_EXPR); 1010 RECORD(EXPR_OBJC_PROTOCOL_EXPR); 1011 RECORD(EXPR_OBJC_IVAR_REF_EXPR); 1012 RECORD(EXPR_OBJC_PROPERTY_REF_EXPR); 1013 RECORD(EXPR_OBJC_KVC_REF_EXPR); 1014 RECORD(EXPR_OBJC_MESSAGE_EXPR); 1015 RECORD(STMT_OBJC_FOR_COLLECTION); 1016 RECORD(STMT_OBJC_CATCH); 1017 RECORD(STMT_OBJC_FINALLY); 1018 RECORD(STMT_OBJC_AT_TRY); 1019 RECORD(STMT_OBJC_AT_SYNCHRONIZED); 1020 RECORD(STMT_OBJC_AT_THROW); 1021 RECORD(EXPR_OBJC_BOOL_LITERAL); 1022 RECORD(STMT_CXX_CATCH); 1023 RECORD(STMT_CXX_TRY); 1024 RECORD(STMT_CXX_FOR_RANGE); 1025 RECORD(EXPR_CXX_OPERATOR_CALL); 1026 RECORD(EXPR_CXX_MEMBER_CALL); 1027 RECORD(EXPR_CXX_REWRITTEN_BINARY_OPERATOR); 1028 RECORD(EXPR_CXX_CONSTRUCT); 1029 RECORD(EXPR_CXX_TEMPORARY_OBJECT); 1030 RECORD(EXPR_CXX_STATIC_CAST); 1031 RECORD(EXPR_CXX_DYNAMIC_CAST); 1032 RECORD(EXPR_CXX_REINTERPRET_CAST); 1033 RECORD(EXPR_CXX_CONST_CAST); 1034 RECORD(EXPR_CXX_FUNCTIONAL_CAST); 1035 RECORD(EXPR_USER_DEFINED_LITERAL); 1036 RECORD(EXPR_CXX_STD_INITIALIZER_LIST); 1037 RECORD(EXPR_CXX_BOOL_LITERAL); 1038 RECORD(EXPR_CXX_NULL_PTR_LITERAL); 1039 RECORD(EXPR_CXX_TYPEID_EXPR); 1040 RECORD(EXPR_CXX_TYPEID_TYPE); 1041 RECORD(EXPR_CXX_THIS); 1042 RECORD(EXPR_CXX_THROW); 1043 RECORD(EXPR_CXX_DEFAULT_ARG); 1044 RECORD(EXPR_CXX_DEFAULT_INIT); 1045 RECORD(EXPR_CXX_BIND_TEMPORARY); 1046 RECORD(EXPR_CXX_SCALAR_VALUE_INIT); 1047 RECORD(EXPR_CXX_NEW); 1048 RECORD(EXPR_CXX_DELETE); 1049 RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR); 1050 RECORD(EXPR_EXPR_WITH_CLEANUPS); 1051 RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER); 1052 RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF); 1053 RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT); 1054 RECORD(EXPR_CXX_UNRESOLVED_MEMBER); 1055 RECORD(EXPR_CXX_UNRESOLVED_LOOKUP); 1056 RECORD(EXPR_CXX_EXPRESSION_TRAIT); 1057 RECORD(EXPR_CXX_NOEXCEPT); 1058 RECORD(EXPR_OPAQUE_VALUE); 1059 RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR); 1060 RECORD(EXPR_TYPE_TRAIT); 1061 RECORD(EXPR_ARRAY_TYPE_TRAIT); 1062 RECORD(EXPR_PACK_EXPANSION); 1063 RECORD(EXPR_SIZEOF_PACK); 1064 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM); 1065 RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK); 1066 RECORD(EXPR_FUNCTION_PARM_PACK); 1067 RECORD(EXPR_MATERIALIZE_TEMPORARY); 1068 RECORD(EXPR_CUDA_KERNEL_CALL); 1069 RECORD(EXPR_CXX_UUIDOF_EXPR); 1070 RECORD(EXPR_CXX_UUIDOF_TYPE); 1071 RECORD(EXPR_LAMBDA); 1072 #undef RECORD 1073 } 1074 1075 void ASTWriter::WriteBlockInfoBlock() { 1076 RecordData Record; 1077 Stream.EnterBlockInfoBlock(); 1078 1079 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record) 1080 #define RECORD(X) EmitRecordID(X, #X, Stream, Record) 1081 1082 // Control Block. 1083 BLOCK(CONTROL_BLOCK); 1084 RECORD(METADATA); 1085 RECORD(MODULE_NAME); 1086 RECORD(MODULE_DIRECTORY); 1087 RECORD(MODULE_MAP_FILE); 1088 RECORD(IMPORTS); 1089 RECORD(ORIGINAL_FILE); 1090 RECORD(ORIGINAL_PCH_DIR); 1091 RECORD(ORIGINAL_FILE_ID); 1092 RECORD(INPUT_FILE_OFFSETS); 1093 1094 BLOCK(OPTIONS_BLOCK); 1095 RECORD(LANGUAGE_OPTIONS); 1096 RECORD(TARGET_OPTIONS); 1097 RECORD(FILE_SYSTEM_OPTIONS); 1098 RECORD(HEADER_SEARCH_OPTIONS); 1099 RECORD(PREPROCESSOR_OPTIONS); 1100 1101 BLOCK(INPUT_FILES_BLOCK); 1102 RECORD(INPUT_FILE); 1103 RECORD(INPUT_FILE_HASH); 1104 1105 // AST Top-Level Block. 1106 BLOCK(AST_BLOCK); 1107 RECORD(TYPE_OFFSET); 1108 RECORD(DECL_OFFSET); 1109 RECORD(IDENTIFIER_OFFSET); 1110 RECORD(IDENTIFIER_TABLE); 1111 RECORD(EAGERLY_DESERIALIZED_DECLS); 1112 RECORD(MODULAR_CODEGEN_DECLS); 1113 RECORD(SPECIAL_TYPES); 1114 RECORD(STATISTICS); 1115 RECORD(TENTATIVE_DEFINITIONS); 1116 RECORD(SELECTOR_OFFSETS); 1117 RECORD(METHOD_POOL); 1118 RECORD(PP_COUNTER_VALUE); 1119 RECORD(SOURCE_LOCATION_OFFSETS); 1120 RECORD(SOURCE_LOCATION_PRELOADS); 1121 RECORD(EXT_VECTOR_DECLS); 1122 RECORD(UNUSED_FILESCOPED_DECLS); 1123 RECORD(PPD_ENTITIES_OFFSETS); 1124 RECORD(VTABLE_USES); 1125 RECORD(PPD_SKIPPED_RANGES); 1126 RECORD(REFERENCED_SELECTOR_POOL); 1127 RECORD(TU_UPDATE_LEXICAL); 1128 RECORD(SEMA_DECL_REFS); 1129 RECORD(WEAK_UNDECLARED_IDENTIFIERS); 1130 RECORD(PENDING_IMPLICIT_INSTANTIATIONS); 1131 RECORD(UPDATE_VISIBLE); 1132 RECORD(DECL_UPDATE_OFFSETS); 1133 RECORD(DECL_UPDATES); 1134 RECORD(CUDA_SPECIAL_DECL_REFS); 1135 RECORD(HEADER_SEARCH_TABLE); 1136 RECORD(FP_PRAGMA_OPTIONS); 1137 RECORD(OPENCL_EXTENSIONS); 1138 RECORD(OPENCL_EXTENSION_TYPES); 1139 RECORD(OPENCL_EXTENSION_DECLS); 1140 RECORD(DELEGATING_CTORS); 1141 RECORD(KNOWN_NAMESPACES); 1142 RECORD(MODULE_OFFSET_MAP); 1143 RECORD(SOURCE_MANAGER_LINE_TABLE); 1144 RECORD(OBJC_CATEGORIES_MAP); 1145 RECORD(FILE_SORTED_DECLS); 1146 RECORD(IMPORTED_MODULES); 1147 RECORD(OBJC_CATEGORIES); 1148 RECORD(MACRO_OFFSET); 1149 RECORD(INTERESTING_IDENTIFIERS); 1150 RECORD(UNDEFINED_BUT_USED); 1151 RECORD(LATE_PARSED_TEMPLATE); 1152 RECORD(OPTIMIZE_PRAGMA_OPTIONS); 1153 RECORD(MSSTRUCT_PRAGMA_OPTIONS); 1154 RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS); 1155 RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES); 1156 RECORD(DELETE_EXPRS_TO_ANALYZE); 1157 RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH); 1158 RECORD(PP_CONDITIONAL_STACK); 1159 1160 // SourceManager Block. 1161 BLOCK(SOURCE_MANAGER_BLOCK); 1162 RECORD(SM_SLOC_FILE_ENTRY); 1163 RECORD(SM_SLOC_BUFFER_ENTRY); 1164 RECORD(SM_SLOC_BUFFER_BLOB); 1165 RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED); 1166 RECORD(SM_SLOC_EXPANSION_ENTRY); 1167 1168 // Preprocessor Block. 1169 BLOCK(PREPROCESSOR_BLOCK); 1170 RECORD(PP_MACRO_DIRECTIVE_HISTORY); 1171 RECORD(PP_MACRO_FUNCTION_LIKE); 1172 RECORD(PP_MACRO_OBJECT_LIKE); 1173 RECORD(PP_MODULE_MACRO); 1174 RECORD(PP_TOKEN); 1175 1176 // Submodule Block. 1177 BLOCK(SUBMODULE_BLOCK); 1178 RECORD(SUBMODULE_METADATA); 1179 RECORD(SUBMODULE_DEFINITION); 1180 RECORD(SUBMODULE_UMBRELLA_HEADER); 1181 RECORD(SUBMODULE_HEADER); 1182 RECORD(SUBMODULE_TOPHEADER); 1183 RECORD(SUBMODULE_UMBRELLA_DIR); 1184 RECORD(SUBMODULE_IMPORTS); 1185 RECORD(SUBMODULE_EXPORTS); 1186 RECORD(SUBMODULE_REQUIRES); 1187 RECORD(SUBMODULE_EXCLUDED_HEADER); 1188 RECORD(SUBMODULE_LINK_LIBRARY); 1189 RECORD(SUBMODULE_CONFIG_MACRO); 1190 RECORD(SUBMODULE_CONFLICT); 1191 RECORD(SUBMODULE_PRIVATE_HEADER); 1192 RECORD(SUBMODULE_TEXTUAL_HEADER); 1193 RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER); 1194 RECORD(SUBMODULE_INITIALIZERS); 1195 RECORD(SUBMODULE_EXPORT_AS); 1196 1197 // Comments Block. 1198 BLOCK(COMMENTS_BLOCK); 1199 RECORD(COMMENTS_RAW_COMMENT); 1200 1201 // Decls and Types block. 1202 BLOCK(DECLTYPES_BLOCK); 1203 RECORD(TYPE_EXT_QUAL); 1204 RECORD(TYPE_COMPLEX); 1205 RECORD(TYPE_POINTER); 1206 RECORD(TYPE_BLOCK_POINTER); 1207 RECORD(TYPE_LVALUE_REFERENCE); 1208 RECORD(TYPE_RVALUE_REFERENCE); 1209 RECORD(TYPE_MEMBER_POINTER); 1210 RECORD(TYPE_CONSTANT_ARRAY); 1211 RECORD(TYPE_INCOMPLETE_ARRAY); 1212 RECORD(TYPE_VARIABLE_ARRAY); 1213 RECORD(TYPE_VECTOR); 1214 RECORD(TYPE_EXT_VECTOR); 1215 RECORD(TYPE_FUNCTION_NO_PROTO); 1216 RECORD(TYPE_FUNCTION_PROTO); 1217 RECORD(TYPE_TYPEDEF); 1218 RECORD(TYPE_TYPEOF_EXPR); 1219 RECORD(TYPE_TYPEOF); 1220 RECORD(TYPE_RECORD); 1221 RECORD(TYPE_ENUM); 1222 RECORD(TYPE_OBJC_INTERFACE); 1223 RECORD(TYPE_OBJC_OBJECT_POINTER); 1224 RECORD(TYPE_DECLTYPE); 1225 RECORD(TYPE_ELABORATED); 1226 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM); 1227 RECORD(TYPE_UNRESOLVED_USING); 1228 RECORD(TYPE_INJECTED_CLASS_NAME); 1229 RECORD(TYPE_OBJC_OBJECT); 1230 RECORD(TYPE_TEMPLATE_TYPE_PARM); 1231 RECORD(TYPE_TEMPLATE_SPECIALIZATION); 1232 RECORD(TYPE_DEPENDENT_NAME); 1233 RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION); 1234 RECORD(TYPE_DEPENDENT_SIZED_ARRAY); 1235 RECORD(TYPE_PAREN); 1236 RECORD(TYPE_MACRO_QUALIFIED); 1237 RECORD(TYPE_PACK_EXPANSION); 1238 RECORD(TYPE_ATTRIBUTED); 1239 RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK); 1240 RECORD(TYPE_AUTO); 1241 RECORD(TYPE_UNARY_TRANSFORM); 1242 RECORD(TYPE_ATOMIC); 1243 RECORD(TYPE_DECAYED); 1244 RECORD(TYPE_ADJUSTED); 1245 RECORD(TYPE_OBJC_TYPE_PARAM); 1246 RECORD(LOCAL_REDECLARATIONS); 1247 RECORD(DECL_TYPEDEF); 1248 RECORD(DECL_TYPEALIAS); 1249 RECORD(DECL_ENUM); 1250 RECORD(DECL_RECORD); 1251 RECORD(DECL_ENUM_CONSTANT); 1252 RECORD(DECL_FUNCTION); 1253 RECORD(DECL_OBJC_METHOD); 1254 RECORD(DECL_OBJC_INTERFACE); 1255 RECORD(DECL_OBJC_PROTOCOL); 1256 RECORD(DECL_OBJC_IVAR); 1257 RECORD(DECL_OBJC_AT_DEFS_FIELD); 1258 RECORD(DECL_OBJC_CATEGORY); 1259 RECORD(DECL_OBJC_CATEGORY_IMPL); 1260 RECORD(DECL_OBJC_IMPLEMENTATION); 1261 RECORD(DECL_OBJC_COMPATIBLE_ALIAS); 1262 RECORD(DECL_OBJC_PROPERTY); 1263 RECORD(DECL_OBJC_PROPERTY_IMPL); 1264 RECORD(DECL_FIELD); 1265 RECORD(DECL_MS_PROPERTY); 1266 RECORD(DECL_VAR); 1267 RECORD(DECL_IMPLICIT_PARAM); 1268 RECORD(DECL_PARM_VAR); 1269 RECORD(DECL_FILE_SCOPE_ASM); 1270 RECORD(DECL_BLOCK); 1271 RECORD(DECL_CONTEXT_LEXICAL); 1272 RECORD(DECL_CONTEXT_VISIBLE); 1273 RECORD(DECL_NAMESPACE); 1274 RECORD(DECL_NAMESPACE_ALIAS); 1275 RECORD(DECL_USING); 1276 RECORD(DECL_USING_SHADOW); 1277 RECORD(DECL_USING_DIRECTIVE); 1278 RECORD(DECL_UNRESOLVED_USING_VALUE); 1279 RECORD(DECL_UNRESOLVED_USING_TYPENAME); 1280 RECORD(DECL_LINKAGE_SPEC); 1281 RECORD(DECL_CXX_RECORD); 1282 RECORD(DECL_CXX_METHOD); 1283 RECORD(DECL_CXX_CONSTRUCTOR); 1284 RECORD(DECL_CXX_DESTRUCTOR); 1285 RECORD(DECL_CXX_CONVERSION); 1286 RECORD(DECL_ACCESS_SPEC); 1287 RECORD(DECL_FRIEND); 1288 RECORD(DECL_FRIEND_TEMPLATE); 1289 RECORD(DECL_CLASS_TEMPLATE); 1290 RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION); 1291 RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION); 1292 RECORD(DECL_VAR_TEMPLATE); 1293 RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION); 1294 RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION); 1295 RECORD(DECL_FUNCTION_TEMPLATE); 1296 RECORD(DECL_TEMPLATE_TYPE_PARM); 1297 RECORD(DECL_NON_TYPE_TEMPLATE_PARM); 1298 RECORD(DECL_TEMPLATE_TEMPLATE_PARM); 1299 RECORD(DECL_CONCEPT); 1300 RECORD(DECL_TYPE_ALIAS_TEMPLATE); 1301 RECORD(DECL_STATIC_ASSERT); 1302 RECORD(DECL_CXX_BASE_SPECIFIERS); 1303 RECORD(DECL_CXX_CTOR_INITIALIZERS); 1304 RECORD(DECL_INDIRECTFIELD); 1305 RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK); 1306 RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK); 1307 RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION); 1308 RECORD(DECL_IMPORT); 1309 RECORD(DECL_OMP_THREADPRIVATE); 1310 RECORD(DECL_EMPTY); 1311 RECORD(DECL_OBJC_TYPE_PARAM); 1312 RECORD(DECL_OMP_CAPTUREDEXPR); 1313 RECORD(DECL_PRAGMA_COMMENT); 1314 RECORD(DECL_PRAGMA_DETECT_MISMATCH); 1315 RECORD(DECL_OMP_DECLARE_REDUCTION); 1316 RECORD(DECL_OMP_ALLOCATE); 1317 1318 // Statements and Exprs can occur in the Decls and Types block. 1319 AddStmtsExprs(Stream, Record); 1320 1321 BLOCK(PREPROCESSOR_DETAIL_BLOCK); 1322 RECORD(PPD_MACRO_EXPANSION); 1323 RECORD(PPD_MACRO_DEFINITION); 1324 RECORD(PPD_INCLUSION_DIRECTIVE); 1325 1326 // Decls and Types block. 1327 BLOCK(EXTENSION_BLOCK); 1328 RECORD(EXTENSION_METADATA); 1329 1330 BLOCK(UNHASHED_CONTROL_BLOCK); 1331 RECORD(SIGNATURE); 1332 RECORD(DIAGNOSTIC_OPTIONS); 1333 RECORD(DIAG_PRAGMA_MAPPINGS); 1334 1335 #undef RECORD 1336 #undef BLOCK 1337 Stream.ExitBlock(); 1338 } 1339 1340 /// Prepares a path for being written to an AST file by converting it 1341 /// to an absolute path and removing nested './'s. 1342 /// 1343 /// \return \c true if the path was changed. 1344 static bool cleanPathForOutput(FileManager &FileMgr, 1345 SmallVectorImpl<char> &Path) { 1346 bool Changed = FileMgr.makeAbsolutePath(Path); 1347 return Changed | llvm::sys::path::remove_dots(Path); 1348 } 1349 1350 /// Adjusts the given filename to only write out the portion of the 1351 /// filename that is not part of the system root directory. 1352 /// 1353 /// \param Filename the file name to adjust. 1354 /// 1355 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and 1356 /// the returned filename will be adjusted by this root directory. 1357 /// 1358 /// \returns either the original filename (if it needs no adjustment) or the 1359 /// adjusted filename (which points into the @p Filename parameter). 1360 static const char * 1361 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) { 1362 assert(Filename && "No file name to adjust?"); 1363 1364 if (BaseDir.empty()) 1365 return Filename; 1366 1367 // Verify that the filename and the system root have the same prefix. 1368 unsigned Pos = 0; 1369 for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos) 1370 if (Filename[Pos] != BaseDir[Pos]) 1371 return Filename; // Prefixes don't match. 1372 1373 // We hit the end of the filename before we hit the end of the system root. 1374 if (!Filename[Pos]) 1375 return Filename; 1376 1377 // If there's not a path separator at the end of the base directory nor 1378 // immediately after it, then this isn't within the base directory. 1379 if (!llvm::sys::path::is_separator(Filename[Pos])) { 1380 if (!llvm::sys::path::is_separator(BaseDir.back())) 1381 return Filename; 1382 } else { 1383 // If the file name has a '/' at the current position, skip over the '/'. 1384 // We distinguish relative paths from absolute paths by the 1385 // absence of '/' at the beginning of relative paths. 1386 // 1387 // FIXME: This is wrong. We distinguish them by asking if the path is 1388 // absolute, which isn't the same thing. And there might be multiple '/'s 1389 // in a row. Use a better mechanism to indicate whether we have emitted an 1390 // absolute or relative path. 1391 ++Pos; 1392 } 1393 1394 return Filename + Pos; 1395 } 1396 1397 ASTFileSignature ASTWriter::createSignature(StringRef Bytes) { 1398 // Calculate the hash till start of UNHASHED_CONTROL_BLOCK. 1399 llvm::SHA1 Hasher; 1400 Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size())); 1401 auto Hash = Hasher.result(); 1402 1403 // Convert to an array [5*i32]. 1404 ASTFileSignature Signature; 1405 auto LShift = [&](unsigned char Val, unsigned Shift) { 1406 return (uint32_t)Val << Shift; 1407 }; 1408 for (int I = 0; I != 5; ++I) 1409 Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) | 1410 LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0); 1411 1412 return Signature; 1413 } 1414 1415 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP, 1416 ASTContext &Context) { 1417 // Flush first to prepare the PCM hash (signature). 1418 Stream.FlushToWord(); 1419 auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3; 1420 1421 // Enter the block and prepare to write records. 1422 RecordData Record; 1423 Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5); 1424 1425 // For implicit modules, write the hash of the PCM as its signature. 1426 ASTFileSignature Signature; 1427 if (WritingModule && 1428 PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) { 1429 Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl)); 1430 Record.append(Signature.begin(), Signature.end()); 1431 Stream.EmitRecord(SIGNATURE, Record); 1432 Record.clear(); 1433 } 1434 1435 // Diagnostic options. 1436 const auto &Diags = Context.getDiagnostics(); 1437 const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions(); 1438 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name); 1439 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 1440 Record.push_back(static_cast<unsigned>(DiagOpts.get##Name())); 1441 #include "clang/Basic/DiagnosticOptions.def" 1442 Record.push_back(DiagOpts.Warnings.size()); 1443 for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I) 1444 AddString(DiagOpts.Warnings[I], Record); 1445 Record.push_back(DiagOpts.Remarks.size()); 1446 for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I) 1447 AddString(DiagOpts.Remarks[I], Record); 1448 // Note: we don't serialize the log or serialization file names, because they 1449 // are generally transient files and will almost always be overridden. 1450 Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record); 1451 1452 // Write out the diagnostic/pragma mappings. 1453 WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule); 1454 1455 // Leave the options block. 1456 Stream.ExitBlock(); 1457 return Signature; 1458 } 1459 1460 /// Write the control block. 1461 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context, 1462 StringRef isysroot, 1463 const std::string &OutputFile) { 1464 using namespace llvm; 1465 1466 Stream.EnterSubblock(CONTROL_BLOCK_ID, 5); 1467 RecordData Record; 1468 1469 // Metadata 1470 auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>(); 1471 MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA)); 1472 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major 1473 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor 1474 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj. 1475 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min. 1476 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable 1477 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps 1478 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile 1479 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors 1480 MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag 1481 unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev)); 1482 assert((!WritingModule || isysroot.empty()) && 1483 "writing module as a relocatable PCH?"); 1484 { 1485 RecordData::value_type Record[] = { 1486 METADATA, 1487 VERSION_MAJOR, 1488 VERSION_MINOR, 1489 CLANG_VERSION_MAJOR, 1490 CLANG_VERSION_MINOR, 1491 !isysroot.empty(), 1492 IncludeTimestamps, 1493 Context.getLangOpts().BuildingPCHWithObjectFile, 1494 ASTHasCompilerErrors}; 1495 Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record, 1496 getClangFullRepositoryVersion()); 1497 } 1498 1499 if (WritingModule) { 1500 // Module name 1501 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1502 Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME)); 1503 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 1504 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1505 RecordData::value_type Record[] = {MODULE_NAME}; 1506 Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name); 1507 } 1508 1509 if (WritingModule && WritingModule->Directory) { 1510 SmallString<128> BaseDir(WritingModule->Directory->getName()); 1511 cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir); 1512 1513 // If the home of the module is the current working directory, then we 1514 // want to pick up the cwd of the build process loading the module, not 1515 // our cwd, when we load this module. 1516 if (!PP.getHeaderSearchInfo() 1517 .getHeaderSearchOpts() 1518 .ModuleMapFileHomeIsCwd || 1519 WritingModule->Directory->getName() != StringRef(".")) { 1520 // Module directory. 1521 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1522 Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY)); 1523 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory 1524 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1525 1526 RecordData::value_type Record[] = {MODULE_DIRECTORY}; 1527 Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir); 1528 } 1529 1530 // Write out all other paths relative to the base directory if possible. 1531 BaseDirectory.assign(BaseDir.begin(), BaseDir.end()); 1532 } else if (!isysroot.empty()) { 1533 // Write out paths relative to the sysroot if possible. 1534 BaseDirectory = isysroot; 1535 } 1536 1537 // Module map file 1538 if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) { 1539 Record.clear(); 1540 1541 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 1542 AddPath(WritingModule->PresumedModuleMapFile.empty() 1543 ? Map.getModuleMapFileForUniquing(WritingModule)->getName() 1544 : StringRef(WritingModule->PresumedModuleMapFile), 1545 Record); 1546 1547 // Additional module map files. 1548 if (auto *AdditionalModMaps = 1549 Map.getAdditionalModuleMapFiles(WritingModule)) { 1550 Record.push_back(AdditionalModMaps->size()); 1551 for (const FileEntry *F : *AdditionalModMaps) 1552 AddPath(F->getName(), Record); 1553 } else { 1554 Record.push_back(0); 1555 } 1556 1557 Stream.EmitRecord(MODULE_MAP_FILE, Record); 1558 } 1559 1560 // Imports 1561 if (Chain) { 1562 serialization::ModuleManager &Mgr = Chain->getModuleManager(); 1563 Record.clear(); 1564 1565 for (ModuleFile &M : Mgr) { 1566 // Skip modules that weren't directly imported. 1567 if (!M.isDirectlyImported()) 1568 continue; 1569 1570 Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding 1571 AddSourceLocation(M.ImportLoc, Record); 1572 1573 // If we have calculated signature, there is no need to store 1574 // the size or timestamp. 1575 Record.push_back(M.Signature ? 0 : M.File->getSize()); 1576 Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File)); 1577 1578 for (auto I : M.Signature) 1579 Record.push_back(I); 1580 1581 AddString(M.ModuleName, Record); 1582 AddPath(M.FileName, Record); 1583 } 1584 Stream.EmitRecord(IMPORTS, Record); 1585 } 1586 1587 // Write the options block. 1588 Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4); 1589 1590 // Language options. 1591 Record.clear(); 1592 const LangOptions &LangOpts = Context.getLangOpts(); 1593 #define LANGOPT(Name, Bits, Default, Description) \ 1594 Record.push_back(LangOpts.Name); 1595 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 1596 Record.push_back(static_cast<unsigned>(LangOpts.get##Name())); 1597 #include "clang/Basic/LangOptions.def" 1598 #define SANITIZER(NAME, ID) \ 1599 Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID)); 1600 #include "clang/Basic/Sanitizers.def" 1601 1602 Record.push_back(LangOpts.ModuleFeatures.size()); 1603 for (StringRef Feature : LangOpts.ModuleFeatures) 1604 AddString(Feature, Record); 1605 1606 Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind()); 1607 AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record); 1608 1609 AddString(LangOpts.CurrentModule, Record); 1610 1611 // Comment options. 1612 Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size()); 1613 for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) { 1614 AddString(I, Record); 1615 } 1616 Record.push_back(LangOpts.CommentOpts.ParseAllComments); 1617 1618 // OpenMP offloading options. 1619 Record.push_back(LangOpts.OMPTargetTriples.size()); 1620 for (auto &T : LangOpts.OMPTargetTriples) 1621 AddString(T.getTriple(), Record); 1622 1623 AddString(LangOpts.OMPHostIRFile, Record); 1624 1625 Stream.EmitRecord(LANGUAGE_OPTIONS, Record); 1626 1627 // Target options. 1628 Record.clear(); 1629 const TargetInfo &Target = Context.getTargetInfo(); 1630 const TargetOptions &TargetOpts = Target.getTargetOpts(); 1631 AddString(TargetOpts.Triple, Record); 1632 AddString(TargetOpts.CPU, Record); 1633 AddString(TargetOpts.ABI, Record); 1634 Record.push_back(TargetOpts.FeaturesAsWritten.size()); 1635 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) { 1636 AddString(TargetOpts.FeaturesAsWritten[I], Record); 1637 } 1638 Record.push_back(TargetOpts.Features.size()); 1639 for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) { 1640 AddString(TargetOpts.Features[I], Record); 1641 } 1642 Stream.EmitRecord(TARGET_OPTIONS, Record); 1643 1644 // File system options. 1645 Record.clear(); 1646 const FileSystemOptions &FSOpts = 1647 Context.getSourceManager().getFileManager().getFileSystemOpts(); 1648 AddString(FSOpts.WorkingDir, Record); 1649 Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record); 1650 1651 // Header search options. 1652 Record.clear(); 1653 const HeaderSearchOptions &HSOpts 1654 = PP.getHeaderSearchInfo().getHeaderSearchOpts(); 1655 AddString(HSOpts.Sysroot, Record); 1656 1657 // Include entries. 1658 Record.push_back(HSOpts.UserEntries.size()); 1659 for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) { 1660 const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I]; 1661 AddString(Entry.Path, Record); 1662 Record.push_back(static_cast<unsigned>(Entry.Group)); 1663 Record.push_back(Entry.IsFramework); 1664 Record.push_back(Entry.IgnoreSysRoot); 1665 } 1666 1667 // System header prefixes. 1668 Record.push_back(HSOpts.SystemHeaderPrefixes.size()); 1669 for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) { 1670 AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record); 1671 Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader); 1672 } 1673 1674 AddString(HSOpts.ResourceDir, Record); 1675 AddString(HSOpts.ModuleCachePath, Record); 1676 AddString(HSOpts.ModuleUserBuildPath, Record); 1677 Record.push_back(HSOpts.DisableModuleHash); 1678 Record.push_back(HSOpts.ImplicitModuleMaps); 1679 Record.push_back(HSOpts.ModuleMapFileHomeIsCwd); 1680 Record.push_back(HSOpts.UseBuiltinIncludes); 1681 Record.push_back(HSOpts.UseStandardSystemIncludes); 1682 Record.push_back(HSOpts.UseStandardCXXIncludes); 1683 Record.push_back(HSOpts.UseLibcxx); 1684 // Write out the specific module cache path that contains the module files. 1685 AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record); 1686 Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record); 1687 1688 // Preprocessor options. 1689 Record.clear(); 1690 const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts(); 1691 1692 // Macro definitions. 1693 Record.push_back(PPOpts.Macros.size()); 1694 for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) { 1695 AddString(PPOpts.Macros[I].first, Record); 1696 Record.push_back(PPOpts.Macros[I].second); 1697 } 1698 1699 // Includes 1700 Record.push_back(PPOpts.Includes.size()); 1701 for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I) 1702 AddString(PPOpts.Includes[I], Record); 1703 1704 // Macro includes 1705 Record.push_back(PPOpts.MacroIncludes.size()); 1706 for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I) 1707 AddString(PPOpts.MacroIncludes[I], Record); 1708 1709 Record.push_back(PPOpts.UsePredefines); 1710 // Detailed record is important since it is used for the module cache hash. 1711 Record.push_back(PPOpts.DetailedRecord); 1712 AddString(PPOpts.ImplicitPCHInclude, Record); 1713 Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary)); 1714 Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record); 1715 1716 // Leave the options block. 1717 Stream.ExitBlock(); 1718 1719 // Original file name and file ID 1720 SourceManager &SM = Context.getSourceManager(); 1721 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 1722 auto FileAbbrev = std::make_shared<BitCodeAbbrev>(); 1723 FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE)); 1724 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID 1725 FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1726 unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev)); 1727 1728 Record.clear(); 1729 Record.push_back(ORIGINAL_FILE); 1730 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1731 EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName()); 1732 } 1733 1734 Record.clear(); 1735 Record.push_back(SM.getMainFileID().getOpaqueValue()); 1736 Stream.EmitRecord(ORIGINAL_FILE_ID, Record); 1737 1738 // Original PCH directory 1739 if (!OutputFile.empty() && OutputFile != "-") { 1740 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1741 Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR)); 1742 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1743 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 1744 1745 SmallString<128> OutputPath(OutputFile); 1746 1747 SM.getFileManager().makeAbsolutePath(OutputPath); 1748 StringRef origDir = llvm::sys::path::parent_path(OutputPath); 1749 1750 RecordData::value_type Record[] = {ORIGINAL_PCH_DIR}; 1751 Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir); 1752 } 1753 1754 WriteInputFiles(Context.SourceMgr, 1755 PP.getHeaderSearchInfo().getHeaderSearchOpts(), 1756 PP.getLangOpts().Modules); 1757 Stream.ExitBlock(); 1758 } 1759 1760 namespace { 1761 1762 /// An input file. 1763 struct InputFileEntry { 1764 const FileEntry *File; 1765 bool IsSystemFile; 1766 bool IsTransient; 1767 bool BufferOverridden; 1768 bool IsTopLevelModuleMap; 1769 uint32_t ContentHash[2]; 1770 }; 1771 1772 } // namespace 1773 1774 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr, 1775 HeaderSearchOptions &HSOpts, 1776 bool Modules) { 1777 using namespace llvm; 1778 1779 Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4); 1780 1781 // Create input-file abbreviation. 1782 auto IFAbbrev = std::make_shared<BitCodeAbbrev>(); 1783 IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE)); 1784 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 1785 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size 1786 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time 1787 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden 1788 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient 1789 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map 1790 IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name 1791 unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev)); 1792 1793 // Create input file hash abbreviation. 1794 auto IFHAbbrev = std::make_shared<BitCodeAbbrev>(); 1795 IFHAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_HASH)); 1796 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1797 IFHAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 1798 unsigned IFHAbbrevCode = Stream.EmitAbbrev(std::move(IFHAbbrev)); 1799 1800 // Get all ContentCache objects for files, sorted by whether the file is a 1801 // system one or not. System files go at the back, users files at the front. 1802 std::deque<InputFileEntry> SortedFiles; 1803 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) { 1804 // Get this source location entry. 1805 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 1806 assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc); 1807 1808 // We only care about file entries that were not overridden. 1809 if (!SLoc->isFile()) 1810 continue; 1811 const SrcMgr::FileInfo &File = SLoc->getFile(); 1812 const SrcMgr::ContentCache *Cache = File.getContentCache(); 1813 if (!Cache->OrigEntry) 1814 continue; 1815 1816 InputFileEntry Entry; 1817 Entry.File = Cache->OrigEntry; 1818 Entry.IsSystemFile = isSystem(File.getFileCharacteristic()); 1819 Entry.IsTransient = Cache->IsTransient; 1820 Entry.BufferOverridden = Cache->BufferOverridden; 1821 Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) && 1822 File.getIncludeLoc().isInvalid(); 1823 1824 auto ContentHash = hash_code(-1); 1825 if (PP->getHeaderSearchInfo() 1826 .getHeaderSearchOpts() 1827 .ValidateASTInputFilesContent) { 1828 auto *MemBuff = Cache->getRawBuffer(); 1829 if (MemBuff) 1830 ContentHash = hash_value(MemBuff->getBuffer()); 1831 else 1832 // FIXME: The path should be taken from the FileEntryRef. 1833 PP->Diag(SourceLocation(), diag::err_module_unable_to_hash_content) 1834 << Entry.File->getName(); 1835 } 1836 auto CH = llvm::APInt(64, ContentHash); 1837 Entry.ContentHash[0] = 1838 static_cast<uint32_t>(CH.getLoBits(32).getZExtValue()); 1839 Entry.ContentHash[1] = 1840 static_cast<uint32_t>(CH.getHiBits(32).getZExtValue()); 1841 1842 if (Entry.IsSystemFile) 1843 SortedFiles.push_back(Entry); 1844 else 1845 SortedFiles.push_front(Entry); 1846 } 1847 1848 unsigned UserFilesNum = 0; 1849 // Write out all of the input files. 1850 std::vector<uint64_t> InputFileOffsets; 1851 for (const auto &Entry : SortedFiles) { 1852 uint32_t &InputFileID = InputFileIDs[Entry.File]; 1853 if (InputFileID != 0) 1854 continue; // already recorded this file. 1855 1856 // Record this entry's offset. 1857 InputFileOffsets.push_back(Stream.GetCurrentBitNo()); 1858 1859 InputFileID = InputFileOffsets.size(); 1860 1861 if (!Entry.IsSystemFile) 1862 ++UserFilesNum; 1863 1864 // Emit size/modification time for this file. 1865 // And whether this file was overridden. 1866 { 1867 RecordData::value_type Record[] = { 1868 INPUT_FILE, 1869 InputFileOffsets.size(), 1870 (uint64_t)Entry.File->getSize(), 1871 (uint64_t)getTimestampForOutput(Entry.File), 1872 Entry.BufferOverridden, 1873 Entry.IsTransient, 1874 Entry.IsTopLevelModuleMap}; 1875 1876 // FIXME: The path should be taken from the FileEntryRef. 1877 EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName()); 1878 } 1879 1880 // Emit content hash for this file. 1881 { 1882 RecordData::value_type Record[] = {INPUT_FILE_HASH, Entry.ContentHash[0], 1883 Entry.ContentHash[1]}; 1884 Stream.EmitRecordWithAbbrev(IFHAbbrevCode, Record); 1885 } 1886 } 1887 1888 Stream.ExitBlock(); 1889 1890 // Create input file offsets abbreviation. 1891 auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>(); 1892 OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS)); 1893 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files 1894 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system 1895 // input files 1896 OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array 1897 unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev)); 1898 1899 // Write input file offsets. 1900 RecordData::value_type Record[] = {INPUT_FILE_OFFSETS, 1901 InputFileOffsets.size(), UserFilesNum}; 1902 Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets)); 1903 } 1904 1905 //===----------------------------------------------------------------------===// 1906 // Source Manager Serialization 1907 //===----------------------------------------------------------------------===// 1908 1909 /// Create an abbreviation for the SLocEntry that refers to a 1910 /// file. 1911 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) { 1912 using namespace llvm; 1913 1914 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1915 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY)); 1916 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1917 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1918 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic 1919 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1920 // FileEntry fields. 1921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID 1922 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs 1923 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex 1924 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls 1925 return Stream.EmitAbbrev(std::move(Abbrev)); 1926 } 1927 1928 /// Create an abbreviation for the SLocEntry that refers to a 1929 /// buffer. 1930 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) { 1931 using namespace llvm; 1932 1933 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1934 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY)); 1935 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1936 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location 1937 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic 1938 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives 1939 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob 1940 return Stream.EmitAbbrev(std::move(Abbrev)); 1941 } 1942 1943 /// Create an abbreviation for the SLocEntry that refers to a 1944 /// buffer's blob. 1945 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream, 1946 bool Compressed) { 1947 using namespace llvm; 1948 1949 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1950 Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED 1951 : SM_SLOC_BUFFER_BLOB)); 1952 if (Compressed) 1953 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size 1954 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob 1955 return Stream.EmitAbbrev(std::move(Abbrev)); 1956 } 1957 1958 /// Create an abbreviation for the SLocEntry that refers to a macro 1959 /// expansion. 1960 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) { 1961 using namespace llvm; 1962 1963 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 1964 Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY)); 1965 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset 1966 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location 1967 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location 1968 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location 1969 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range 1970 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length 1971 return Stream.EmitAbbrev(std::move(Abbrev)); 1972 } 1973 1974 namespace { 1975 1976 // Trait used for the on-disk hash table of header search information. 1977 class HeaderFileInfoTrait { 1978 ASTWriter &Writer; 1979 1980 // Keep track of the framework names we've used during serialization. 1981 SmallVector<char, 128> FrameworkStringData; 1982 llvm::StringMap<unsigned> FrameworkNameOffset; 1983 1984 public: 1985 HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {} 1986 1987 struct key_type { 1988 StringRef Filename; 1989 off_t Size; 1990 time_t ModTime; 1991 }; 1992 using key_type_ref = const key_type &; 1993 1994 using UnresolvedModule = 1995 llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>; 1996 1997 struct data_type { 1998 const HeaderFileInfo &HFI; 1999 ArrayRef<ModuleMap::KnownHeader> KnownHeaders; 2000 UnresolvedModule Unresolved; 2001 }; 2002 using data_type_ref = const data_type &; 2003 2004 using hash_value_type = unsigned; 2005 using offset_type = unsigned; 2006 2007 hash_value_type ComputeHash(key_type_ref key) { 2008 // The hash is based only on size/time of the file, so that the reader can 2009 // match even when symlinking or excess path elements ("foo/../", "../") 2010 // change the form of the name. However, complete path is still the key. 2011 return llvm::hash_combine(key.Size, key.ModTime); 2012 } 2013 2014 std::pair<unsigned, unsigned> 2015 EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) { 2016 using namespace llvm::support; 2017 2018 endian::Writer LE(Out, little); 2019 unsigned KeyLen = key.Filename.size() + 1 + 8 + 8; 2020 LE.write<uint16_t>(KeyLen); 2021 unsigned DataLen = 1 + 2 + 4 + 4; 2022 for (auto ModInfo : Data.KnownHeaders) 2023 if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule())) 2024 DataLen += 4; 2025 if (Data.Unresolved.getPointer()) 2026 DataLen += 4; 2027 LE.write<uint8_t>(DataLen); 2028 return std::make_pair(KeyLen, DataLen); 2029 } 2030 2031 void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) { 2032 using namespace llvm::support; 2033 2034 endian::Writer LE(Out, little); 2035 LE.write<uint64_t>(key.Size); 2036 KeyLen -= 8; 2037 LE.write<uint64_t>(key.ModTime); 2038 KeyLen -= 8; 2039 Out.write(key.Filename.data(), KeyLen); 2040 } 2041 2042 void EmitData(raw_ostream &Out, key_type_ref key, 2043 data_type_ref Data, unsigned DataLen) { 2044 using namespace llvm::support; 2045 2046 endian::Writer LE(Out, little); 2047 uint64_t Start = Out.tell(); (void)Start; 2048 2049 unsigned char Flags = (Data.HFI.isImport << 5) 2050 | (Data.HFI.isPragmaOnce << 4) 2051 | (Data.HFI.DirInfo << 1) 2052 | Data.HFI.IndexHeaderMapHeader; 2053 LE.write<uint8_t>(Flags); 2054 LE.write<uint16_t>(Data.HFI.NumIncludes); 2055 2056 if (!Data.HFI.ControllingMacro) 2057 LE.write<uint32_t>(Data.HFI.ControllingMacroID); 2058 else 2059 LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro)); 2060 2061 unsigned Offset = 0; 2062 if (!Data.HFI.Framework.empty()) { 2063 // If this header refers into a framework, save the framework name. 2064 llvm::StringMap<unsigned>::iterator Pos 2065 = FrameworkNameOffset.find(Data.HFI.Framework); 2066 if (Pos == FrameworkNameOffset.end()) { 2067 Offset = FrameworkStringData.size() + 1; 2068 FrameworkStringData.append(Data.HFI.Framework.begin(), 2069 Data.HFI.Framework.end()); 2070 FrameworkStringData.push_back(0); 2071 2072 FrameworkNameOffset[Data.HFI.Framework] = Offset; 2073 } else 2074 Offset = Pos->second; 2075 } 2076 LE.write<uint32_t>(Offset); 2077 2078 auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) { 2079 if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) { 2080 uint32_t Value = (ModID << 2) | (unsigned)Role; 2081 assert((Value >> 2) == ModID && "overflow in header module info"); 2082 LE.write<uint32_t>(Value); 2083 } 2084 }; 2085 2086 // FIXME: If the header is excluded, we should write out some 2087 // record of that fact. 2088 for (auto ModInfo : Data.KnownHeaders) 2089 EmitModule(ModInfo.getModule(), ModInfo.getRole()); 2090 if (Data.Unresolved.getPointer()) 2091 EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt()); 2092 2093 assert(Out.tell() - Start == DataLen && "Wrong data length"); 2094 } 2095 2096 const char *strings_begin() const { return FrameworkStringData.begin(); } 2097 const char *strings_end() const { return FrameworkStringData.end(); } 2098 }; 2099 2100 } // namespace 2101 2102 /// Write the header search block for the list of files that 2103 /// 2104 /// \param HS The header search structure to save. 2105 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) { 2106 HeaderFileInfoTrait GeneratorTrait(*this); 2107 llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator; 2108 SmallVector<const char *, 4> SavedStrings; 2109 unsigned NumHeaderSearchEntries = 0; 2110 2111 // Find all unresolved headers for the current module. We generally will 2112 // have resolved them before we get here, but not necessarily: we might be 2113 // compiling a preprocessed module, where there is no requirement for the 2114 // original files to exist any more. 2115 const HeaderFileInfo Empty; // So we can take a reference. 2116 if (WritingModule) { 2117 llvm::SmallVector<Module *, 16> Worklist(1, WritingModule); 2118 while (!Worklist.empty()) { 2119 Module *M = Worklist.pop_back_val(); 2120 if (!M->isAvailable()) 2121 continue; 2122 2123 // Map to disk files where possible, to pick up any missing stat 2124 // information. This also means we don't need to check the unresolved 2125 // headers list when emitting resolved headers in the first loop below. 2126 // FIXME: It'd be preferable to avoid doing this if we were given 2127 // sufficient stat information in the module map. 2128 HS.getModuleMap().resolveHeaderDirectives(M); 2129 2130 // If the file didn't exist, we can still create a module if we were given 2131 // enough information in the module map. 2132 for (auto U : M->MissingHeaders) { 2133 // Check that we were given enough information to build a module 2134 // without this file existing on disk. 2135 if (!U.Size || (!U.ModTime && IncludeTimestamps)) { 2136 PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header) 2137 << WritingModule->getFullModuleName() << U.Size.hasValue() 2138 << U.FileName; 2139 continue; 2140 } 2141 2142 // Form the effective relative pathname for the file. 2143 SmallString<128> Filename(M->Directory->getName()); 2144 llvm::sys::path::append(Filename, U.FileName); 2145 PreparePathForOutput(Filename); 2146 2147 StringRef FilenameDup = strdup(Filename.c_str()); 2148 SavedStrings.push_back(FilenameDup.data()); 2149 2150 HeaderFileInfoTrait::key_type Key = { 2151 FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0 2152 }; 2153 HeaderFileInfoTrait::data_type Data = { 2154 Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)} 2155 }; 2156 // FIXME: Deal with cases where there are multiple unresolved header 2157 // directives in different submodules for the same header. 2158 Generator.insert(Key, Data, GeneratorTrait); 2159 ++NumHeaderSearchEntries; 2160 } 2161 2162 Worklist.append(M->submodule_begin(), M->submodule_end()); 2163 } 2164 } 2165 2166 SmallVector<const FileEntry *, 16> FilesByUID; 2167 HS.getFileMgr().GetUniqueIDMapping(FilesByUID); 2168 2169 if (FilesByUID.size() > HS.header_file_size()) 2170 FilesByUID.resize(HS.header_file_size()); 2171 2172 for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) { 2173 const FileEntry *File = FilesByUID[UID]; 2174 if (!File) 2175 continue; 2176 2177 // Get the file info. This will load info from the external source if 2178 // necessary. Skip emitting this file if we have no information on it 2179 // as a header file (in which case HFI will be null) or if it hasn't 2180 // changed since it was loaded. Also skip it if it's for a modular header 2181 // from a different module; in that case, we rely on the module(s) 2182 // containing the header to provide this information. 2183 const HeaderFileInfo *HFI = 2184 HS.getExistingFileInfo(File, /*WantExternal*/!Chain); 2185 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader)) 2186 continue; 2187 2188 // Massage the file path into an appropriate form. 2189 StringRef Filename = File->getName(); 2190 SmallString<128> FilenameTmp(Filename); 2191 if (PreparePathForOutput(FilenameTmp)) { 2192 // If we performed any translation on the file name at all, we need to 2193 // save this string, since the generator will refer to it later. 2194 Filename = StringRef(strdup(FilenameTmp.c_str())); 2195 SavedStrings.push_back(Filename.data()); 2196 } 2197 2198 HeaderFileInfoTrait::key_type Key = { 2199 Filename, File->getSize(), getTimestampForOutput(File) 2200 }; 2201 HeaderFileInfoTrait::data_type Data = { 2202 *HFI, HS.getModuleMap().findAllModulesForHeader(File), {} 2203 }; 2204 Generator.insert(Key, Data, GeneratorTrait); 2205 ++NumHeaderSearchEntries; 2206 } 2207 2208 // Create the on-disk hash table in a buffer. 2209 SmallString<4096> TableData; 2210 uint32_t BucketOffset; 2211 { 2212 using namespace llvm::support; 2213 2214 llvm::raw_svector_ostream Out(TableData); 2215 // Make sure that no bucket is at offset 0 2216 endian::write<uint32_t>(Out, 0, little); 2217 BucketOffset = Generator.Emit(Out, GeneratorTrait); 2218 } 2219 2220 // Create a blob abbreviation 2221 using namespace llvm; 2222 2223 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2224 Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE)); 2225 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2226 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2227 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 2228 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2229 unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2230 2231 // Write the header search table 2232 RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset, 2233 NumHeaderSearchEntries, TableData.size()}; 2234 TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end()); 2235 Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData); 2236 2237 // Free all of the strings we had to duplicate. 2238 for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I) 2239 free(const_cast<char *>(SavedStrings[I])); 2240 } 2241 2242 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob, 2243 unsigned SLocBufferBlobCompressedAbbrv, 2244 unsigned SLocBufferBlobAbbrv) { 2245 using RecordDataType = ASTWriter::RecordData::value_type; 2246 2247 // Compress the buffer if possible. We expect that almost all PCM 2248 // consumers will not want its contents. 2249 SmallString<0> CompressedBuffer; 2250 if (llvm::zlib::isAvailable()) { 2251 llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer); 2252 if (!E) { 2253 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED, 2254 Blob.size() - 1}; 2255 Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record, 2256 CompressedBuffer); 2257 return; 2258 } 2259 llvm::consumeError(std::move(E)); 2260 } 2261 2262 RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB}; 2263 Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob); 2264 } 2265 2266 /// Writes the block containing the serialized form of the 2267 /// source manager. 2268 /// 2269 /// TODO: We should probably use an on-disk hash table (stored in a 2270 /// blob), indexed based on the file name, so that we only create 2271 /// entries for files that we actually need. In the common case (no 2272 /// errors), we probably won't have to create file entries for any of 2273 /// the files in the AST. 2274 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr, 2275 const Preprocessor &PP) { 2276 RecordData Record; 2277 2278 // Enter the source manager block. 2279 Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4); 2280 2281 // Abbreviations for the various kinds of source-location entries. 2282 unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream); 2283 unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream); 2284 unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false); 2285 unsigned SLocBufferBlobCompressedAbbrv = 2286 CreateSLocBufferBlobAbbrev(Stream, true); 2287 unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream); 2288 2289 // Write out the source location entry table. We skip the first 2290 // entry, which is always the same dummy entry. 2291 std::vector<uint32_t> SLocEntryOffsets; 2292 RecordData PreloadSLocs; 2293 SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1); 2294 for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); 2295 I != N; ++I) { 2296 // Get this source location entry. 2297 const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I); 2298 FileID FID = FileID::get(I); 2299 assert(&SourceMgr.getSLocEntry(FID) == SLoc); 2300 2301 // Record the offset of this source-location entry. 2302 SLocEntryOffsets.push_back(Stream.GetCurrentBitNo()); 2303 2304 // Figure out which record code to use. 2305 unsigned Code; 2306 if (SLoc->isFile()) { 2307 const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache(); 2308 if (Cache->OrigEntry) { 2309 Code = SM_SLOC_FILE_ENTRY; 2310 } else 2311 Code = SM_SLOC_BUFFER_ENTRY; 2312 } else 2313 Code = SM_SLOC_EXPANSION_ENTRY; 2314 Record.clear(); 2315 Record.push_back(Code); 2316 2317 // Starting offset of this entry within this module, so skip the dummy. 2318 Record.push_back(SLoc->getOffset() - 2); 2319 if (SLoc->isFile()) { 2320 const SrcMgr::FileInfo &File = SLoc->getFile(); 2321 AddSourceLocation(File.getIncludeLoc(), Record); 2322 Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding 2323 Record.push_back(File.hasLineDirectives()); 2324 2325 const SrcMgr::ContentCache *Content = File.getContentCache(); 2326 bool EmitBlob = false; 2327 if (Content->OrigEntry) { 2328 assert(Content->OrigEntry == Content->ContentsEntry && 2329 "Writing to AST an overridden file is not supported"); 2330 2331 // The source location entry is a file. Emit input file ID. 2332 assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry"); 2333 Record.push_back(InputFileIDs[Content->OrigEntry]); 2334 2335 Record.push_back(File.NumCreatedFIDs); 2336 2337 FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID); 2338 if (FDI != FileDeclIDs.end()) { 2339 Record.push_back(FDI->second->FirstDeclIndex); 2340 Record.push_back(FDI->second->DeclIDs.size()); 2341 } else { 2342 Record.push_back(0); 2343 Record.push_back(0); 2344 } 2345 2346 Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record); 2347 2348 if (Content->BufferOverridden || Content->IsTransient) 2349 EmitBlob = true; 2350 } else { 2351 // The source location entry is a buffer. The blob associated 2352 // with this entry contains the contents of the buffer. 2353 2354 // We add one to the size so that we capture the trailing NULL 2355 // that is required by llvm::MemoryBuffer::getMemBuffer (on 2356 // the reader side). 2357 const llvm::MemoryBuffer *Buffer = 2358 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager()); 2359 StringRef Name = Buffer->getBufferIdentifier(); 2360 Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record, 2361 StringRef(Name.data(), Name.size() + 1)); 2362 EmitBlob = true; 2363 2364 if (Name == "<built-in>") 2365 PreloadSLocs.push_back(SLocEntryOffsets.size()); 2366 } 2367 2368 if (EmitBlob) { 2369 // Include the implicit terminating null character in the on-disk buffer 2370 // if we're writing it uncompressed. 2371 const llvm::MemoryBuffer *Buffer = 2372 Content->getBuffer(PP.getDiagnostics(), PP.getFileManager()); 2373 StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1); 2374 emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv, 2375 SLocBufferBlobAbbrv); 2376 } 2377 } else { 2378 // The source location entry is a macro expansion. 2379 const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion(); 2380 AddSourceLocation(Expansion.getSpellingLoc(), Record); 2381 AddSourceLocation(Expansion.getExpansionLocStart(), Record); 2382 AddSourceLocation(Expansion.isMacroArgExpansion() 2383 ? SourceLocation() 2384 : Expansion.getExpansionLocEnd(), 2385 Record); 2386 Record.push_back(Expansion.isExpansionTokenRange()); 2387 2388 // Compute the token length for this macro expansion. 2389 unsigned NextOffset = SourceMgr.getNextLocalOffset(); 2390 if (I + 1 != N) 2391 NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset(); 2392 Record.push_back(NextOffset - SLoc->getOffset() - 1); 2393 Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record); 2394 } 2395 } 2396 2397 Stream.ExitBlock(); 2398 2399 if (SLocEntryOffsets.empty()) 2400 return; 2401 2402 // Write the source-location offsets table into the AST block. This 2403 // table is used for lazily loading source-location information. 2404 using namespace llvm; 2405 2406 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2407 Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS)); 2408 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs 2409 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size 2410 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets 2411 unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2412 { 2413 RecordData::value_type Record[] = { 2414 SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(), 2415 SourceMgr.getNextLocalOffset() - 1 /* skip dummy */}; 2416 Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, 2417 bytes(SLocEntryOffsets)); 2418 } 2419 // Write the source location entry preloads array, telling the AST 2420 // reader which source locations entries it should load eagerly. 2421 Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs); 2422 2423 // Write the line table. It depends on remapping working, so it must come 2424 // after the source location offsets. 2425 if (SourceMgr.hasLineTable()) { 2426 LineTableInfo &LineTable = SourceMgr.getLineTable(); 2427 2428 Record.clear(); 2429 2430 // Emit the needed file names. 2431 llvm::DenseMap<int, int> FilenameMap; 2432 FilenameMap[-1] = -1; // For unspecified filenames. 2433 for (const auto &L : LineTable) { 2434 if (L.first.ID < 0) 2435 continue; 2436 for (auto &LE : L.second) { 2437 if (FilenameMap.insert(std::make_pair(LE.FilenameID, 2438 FilenameMap.size() - 1)).second) 2439 AddPath(LineTable.getFilename(LE.FilenameID), Record); 2440 } 2441 } 2442 Record.push_back(0); 2443 2444 // Emit the line entries 2445 for (const auto &L : LineTable) { 2446 // Only emit entries for local files. 2447 if (L.first.ID < 0) 2448 continue; 2449 2450 // Emit the file ID 2451 Record.push_back(L.first.ID); 2452 2453 // Emit the line entries 2454 Record.push_back(L.second.size()); 2455 for (const auto &LE : L.second) { 2456 Record.push_back(LE.FileOffset); 2457 Record.push_back(LE.LineNo); 2458 Record.push_back(FilenameMap[LE.FilenameID]); 2459 Record.push_back((unsigned)LE.FileKind); 2460 Record.push_back(LE.IncludeOffset); 2461 } 2462 } 2463 2464 Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record); 2465 } 2466 } 2467 2468 //===----------------------------------------------------------------------===// 2469 // Preprocessor Serialization 2470 //===----------------------------------------------------------------------===// 2471 2472 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule, 2473 const Preprocessor &PP) { 2474 if (MacroInfo *MI = MD->getMacroInfo()) 2475 if (MI->isBuiltinMacro()) 2476 return true; 2477 2478 if (IsModule) { 2479 SourceLocation Loc = MD->getLocation(); 2480 if (Loc.isInvalid()) 2481 return true; 2482 if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID()) 2483 return true; 2484 } 2485 2486 return false; 2487 } 2488 2489 /// Writes the block containing the serialized form of the 2490 /// preprocessor. 2491 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) { 2492 PreprocessingRecord *PPRec = PP.getPreprocessingRecord(); 2493 if (PPRec) 2494 WritePreprocessorDetail(*PPRec); 2495 2496 RecordData Record; 2497 RecordData ModuleMacroRecord; 2498 2499 // If the preprocessor __COUNTER__ value has been bumped, remember it. 2500 if (PP.getCounterValue() != 0) { 2501 RecordData::value_type Record[] = {PP.getCounterValue()}; 2502 Stream.EmitRecord(PP_COUNTER_VALUE, Record); 2503 } 2504 2505 if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) { 2506 assert(!IsModule); 2507 auto SkipInfo = PP.getPreambleSkipInfo(); 2508 if (SkipInfo.hasValue()) { 2509 Record.push_back(true); 2510 AddSourceLocation(SkipInfo->HashTokenLoc, Record); 2511 AddSourceLocation(SkipInfo->IfTokenLoc, Record); 2512 Record.push_back(SkipInfo->FoundNonSkipPortion); 2513 Record.push_back(SkipInfo->FoundElse); 2514 AddSourceLocation(SkipInfo->ElseLoc, Record); 2515 } else { 2516 Record.push_back(false); 2517 } 2518 for (const auto &Cond : PP.getPreambleConditionalStack()) { 2519 AddSourceLocation(Cond.IfLoc, Record); 2520 Record.push_back(Cond.WasSkipping); 2521 Record.push_back(Cond.FoundNonSkip); 2522 Record.push_back(Cond.FoundElse); 2523 } 2524 Stream.EmitRecord(PP_CONDITIONAL_STACK, Record); 2525 Record.clear(); 2526 } 2527 2528 // Enter the preprocessor block. 2529 Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3); 2530 2531 // If the AST file contains __DATE__ or __TIME__ emit a warning about this. 2532 // FIXME: Include a location for the use, and say which one was used. 2533 if (PP.SawDateOrTime()) 2534 PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule; 2535 2536 // Loop over all the macro directives that are live at the end of the file, 2537 // emitting each to the PP section. 2538 2539 // Construct the list of identifiers with macro directives that need to be 2540 // serialized. 2541 SmallVector<const IdentifierInfo *, 128> MacroIdentifiers; 2542 for (auto &Id : PP.getIdentifierTable()) 2543 if (Id.second->hadMacroDefinition() && 2544 (!Id.second->isFromAST() || 2545 Id.second->hasChangedSinceDeserialization())) 2546 MacroIdentifiers.push_back(Id.second); 2547 // Sort the set of macro definitions that need to be serialized by the 2548 // name of the macro, to provide a stable ordering. 2549 llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>()); 2550 2551 // Emit the macro directives as a list and associate the offset with the 2552 // identifier they belong to. 2553 for (const IdentifierInfo *Name : MacroIdentifiers) { 2554 MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name); 2555 auto StartOffset = Stream.GetCurrentBitNo(); 2556 2557 // Emit the macro directives in reverse source order. 2558 for (; MD; MD = MD->getPrevious()) { 2559 // Once we hit an ignored macro, we're done: the rest of the chain 2560 // will all be ignored macros. 2561 if (shouldIgnoreMacro(MD, IsModule, PP)) 2562 break; 2563 2564 AddSourceLocation(MD->getLocation(), Record); 2565 Record.push_back(MD->getKind()); 2566 if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) { 2567 Record.push_back(getMacroRef(DefMD->getInfo(), Name)); 2568 } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 2569 Record.push_back(VisMD->isPublic()); 2570 } 2571 } 2572 2573 // Write out any exported module macros. 2574 bool EmittedModuleMacros = false; 2575 // We write out exported module macros for PCH as well. 2576 auto Leafs = PP.getLeafModuleMacros(Name); 2577 SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end()); 2578 llvm::DenseMap<ModuleMacro*, unsigned> Visits; 2579 while (!Worklist.empty()) { 2580 auto *Macro = Worklist.pop_back_val(); 2581 2582 // Emit a record indicating this submodule exports this macro. 2583 ModuleMacroRecord.push_back( 2584 getSubmoduleID(Macro->getOwningModule())); 2585 ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name)); 2586 for (auto *M : Macro->overrides()) 2587 ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule())); 2588 2589 Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord); 2590 ModuleMacroRecord.clear(); 2591 2592 // Enqueue overridden macros once we've visited all their ancestors. 2593 for (auto *M : Macro->overrides()) 2594 if (++Visits[M] == M->getNumOverridingMacros()) 2595 Worklist.push_back(M); 2596 2597 EmittedModuleMacros = true; 2598 } 2599 2600 if (Record.empty() && !EmittedModuleMacros) 2601 continue; 2602 2603 IdentMacroDirectivesOffsetMap[Name] = StartOffset; 2604 Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record); 2605 Record.clear(); 2606 } 2607 2608 /// Offsets of each of the macros into the bitstream, indexed by 2609 /// the local macro ID 2610 /// 2611 /// For each identifier that is associated with a macro, this map 2612 /// provides the offset into the bitstream where that macro is 2613 /// defined. 2614 std::vector<uint32_t> MacroOffsets; 2615 2616 for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) { 2617 const IdentifierInfo *Name = MacroInfosToEmit[I].Name; 2618 MacroInfo *MI = MacroInfosToEmit[I].MI; 2619 MacroID ID = MacroInfosToEmit[I].ID; 2620 2621 if (ID < FirstMacroID) { 2622 assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?"); 2623 continue; 2624 } 2625 2626 // Record the local offset of this macro. 2627 unsigned Index = ID - FirstMacroID; 2628 if (Index == MacroOffsets.size()) 2629 MacroOffsets.push_back(Stream.GetCurrentBitNo()); 2630 else { 2631 if (Index > MacroOffsets.size()) 2632 MacroOffsets.resize(Index + 1); 2633 2634 MacroOffsets[Index] = Stream.GetCurrentBitNo(); 2635 } 2636 2637 AddIdentifierRef(Name, Record); 2638 AddSourceLocation(MI->getDefinitionLoc(), Record); 2639 AddSourceLocation(MI->getDefinitionEndLoc(), Record); 2640 Record.push_back(MI->isUsed()); 2641 Record.push_back(MI->isUsedForHeaderGuard()); 2642 unsigned Code; 2643 if (MI->isObjectLike()) { 2644 Code = PP_MACRO_OBJECT_LIKE; 2645 } else { 2646 Code = PP_MACRO_FUNCTION_LIKE; 2647 2648 Record.push_back(MI->isC99Varargs()); 2649 Record.push_back(MI->isGNUVarargs()); 2650 Record.push_back(MI->hasCommaPasting()); 2651 Record.push_back(MI->getNumParams()); 2652 for (const IdentifierInfo *Param : MI->params()) 2653 AddIdentifierRef(Param, Record); 2654 } 2655 2656 // If we have a detailed preprocessing record, record the macro definition 2657 // ID that corresponds to this macro. 2658 if (PPRec) 2659 Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]); 2660 2661 Stream.EmitRecord(Code, Record); 2662 Record.clear(); 2663 2664 // Emit the tokens array. 2665 for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) { 2666 // Note that we know that the preprocessor does not have any annotation 2667 // tokens in it because they are created by the parser, and thus can't 2668 // be in a macro definition. 2669 const Token &Tok = MI->getReplacementToken(TokNo); 2670 AddToken(Tok, Record); 2671 Stream.EmitRecord(PP_TOKEN, Record); 2672 Record.clear(); 2673 } 2674 ++NumMacros; 2675 } 2676 2677 Stream.ExitBlock(); 2678 2679 // Write the offsets table for macro IDs. 2680 using namespace llvm; 2681 2682 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2683 Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET)); 2684 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros 2685 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 2686 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2687 2688 unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2689 { 2690 RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(), 2691 FirstMacroID - NUM_PREDEF_MACRO_IDS}; 2692 Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets)); 2693 } 2694 } 2695 2696 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) { 2697 if (PPRec.local_begin() == PPRec.local_end()) 2698 return; 2699 2700 SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets; 2701 2702 // Enter the preprocessor block. 2703 Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3); 2704 2705 // If the preprocessor has a preprocessing record, emit it. 2706 unsigned NumPreprocessingRecords = 0; 2707 using namespace llvm; 2708 2709 // Set up the abbreviation for 2710 unsigned InclusionAbbrev = 0; 2711 { 2712 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2713 Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE)); 2714 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length 2715 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes 2716 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind 2717 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module 2718 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2719 InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2720 } 2721 2722 unsigned FirstPreprocessorEntityID 2723 = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0) 2724 + NUM_PREDEF_PP_ENTITY_IDS; 2725 unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID; 2726 RecordData Record; 2727 for (PreprocessingRecord::iterator E = PPRec.local_begin(), 2728 EEnd = PPRec.local_end(); 2729 E != EEnd; 2730 (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) { 2731 Record.clear(); 2732 2733 PreprocessedEntityOffsets.push_back( 2734 PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo())); 2735 2736 if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) { 2737 // Record this macro definition's ID. 2738 MacroDefinitions[MD] = NextPreprocessorEntityID; 2739 2740 AddIdentifierRef(MD->getName(), Record); 2741 Stream.EmitRecord(PPD_MACRO_DEFINITION, Record); 2742 continue; 2743 } 2744 2745 if (auto *ME = dyn_cast<MacroExpansion>(*E)) { 2746 Record.push_back(ME->isBuiltinMacro()); 2747 if (ME->isBuiltinMacro()) 2748 AddIdentifierRef(ME->getName(), Record); 2749 else 2750 Record.push_back(MacroDefinitions[ME->getDefinition()]); 2751 Stream.EmitRecord(PPD_MACRO_EXPANSION, Record); 2752 continue; 2753 } 2754 2755 if (auto *ID = dyn_cast<InclusionDirective>(*E)) { 2756 Record.push_back(PPD_INCLUSION_DIRECTIVE); 2757 Record.push_back(ID->getFileName().size()); 2758 Record.push_back(ID->wasInQuotes()); 2759 Record.push_back(static_cast<unsigned>(ID->getKind())); 2760 Record.push_back(ID->importedModule()); 2761 SmallString<64> Buffer; 2762 Buffer += ID->getFileName(); 2763 // Check that the FileEntry is not null because it was not resolved and 2764 // we create a PCH even with compiler errors. 2765 if (ID->getFile()) 2766 Buffer += ID->getFile()->getName(); 2767 Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer); 2768 continue; 2769 } 2770 2771 llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter"); 2772 } 2773 Stream.ExitBlock(); 2774 2775 // Write the offsets table for the preprocessing record. 2776 if (NumPreprocessingRecords > 0) { 2777 assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords); 2778 2779 // Write the offsets table for identifier IDs. 2780 using namespace llvm; 2781 2782 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2783 Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS)); 2784 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity 2785 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2786 unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2787 2788 RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS, 2789 FirstPreprocessorEntityID - 2790 NUM_PREDEF_PP_ENTITY_IDS}; 2791 Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record, 2792 bytes(PreprocessedEntityOffsets)); 2793 } 2794 2795 // Write the skipped region table for the preprocessing record. 2796 ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges(); 2797 if (SkippedRanges.size() > 0) { 2798 std::vector<PPSkippedRange> SerializedSkippedRanges; 2799 SerializedSkippedRanges.reserve(SkippedRanges.size()); 2800 for (auto const& Range : SkippedRanges) 2801 SerializedSkippedRanges.emplace_back(Range); 2802 2803 using namespace llvm; 2804 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2805 Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES)); 2806 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 2807 unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2808 2809 Record.clear(); 2810 Record.push_back(PPD_SKIPPED_RANGES); 2811 Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record, 2812 bytes(SerializedSkippedRanges)); 2813 } 2814 } 2815 2816 unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) { 2817 if (!Mod) 2818 return 0; 2819 2820 llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod); 2821 if (Known != SubmoduleIDs.end()) 2822 return Known->second; 2823 2824 auto *Top = Mod->getTopLevelModule(); 2825 if (Top != WritingModule && 2826 (getLangOpts().CompilingPCH || 2827 !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule)))) 2828 return 0; 2829 2830 return SubmoduleIDs[Mod] = NextSubmoduleID++; 2831 } 2832 2833 unsigned ASTWriter::getSubmoduleID(Module *Mod) { 2834 // FIXME: This can easily happen, if we have a reference to a submodule that 2835 // did not result in us loading a module file for that submodule. For 2836 // instance, a cross-top-level-module 'conflict' declaration will hit this. 2837 unsigned ID = getLocalOrImportedSubmoduleID(Mod); 2838 assert((ID || !Mod) && 2839 "asked for module ID for non-local, non-imported module"); 2840 return ID; 2841 } 2842 2843 /// Compute the number of modules within the given tree (including the 2844 /// given module). 2845 static unsigned getNumberOfModules(Module *Mod) { 2846 unsigned ChildModules = 0; 2847 for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end(); 2848 Sub != SubEnd; ++Sub) 2849 ChildModules += getNumberOfModules(*Sub); 2850 2851 return ChildModules + 1; 2852 } 2853 2854 void ASTWriter::WriteSubmodules(Module *WritingModule) { 2855 // Enter the submodule description block. 2856 Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5); 2857 2858 // Write the abbreviations needed for the submodules block. 2859 using namespace llvm; 2860 2861 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 2862 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION)); 2863 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID 2864 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent 2865 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind 2866 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 2867 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit 2868 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem 2869 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC 2870 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules... 2871 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit... 2872 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild... 2873 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh... 2874 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv... 2875 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2876 unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2877 2878 Abbrev = std::make_shared<BitCodeAbbrev>(); 2879 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER)); 2880 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2881 unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2882 2883 Abbrev = std::make_shared<BitCodeAbbrev>(); 2884 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER)); 2885 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2886 unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2887 2888 Abbrev = std::make_shared<BitCodeAbbrev>(); 2889 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER)); 2890 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2891 unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2892 2893 Abbrev = std::make_shared<BitCodeAbbrev>(); 2894 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR)); 2895 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2896 unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2897 2898 Abbrev = std::make_shared<BitCodeAbbrev>(); 2899 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES)); 2900 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State 2901 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature 2902 unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2903 2904 Abbrev = std::make_shared<BitCodeAbbrev>(); 2905 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER)); 2906 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2907 unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2908 2909 Abbrev = std::make_shared<BitCodeAbbrev>(); 2910 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER)); 2911 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2912 unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2913 2914 Abbrev = std::make_shared<BitCodeAbbrev>(); 2915 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER)); 2916 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2917 unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2918 2919 Abbrev = std::make_shared<BitCodeAbbrev>(); 2920 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER)); 2921 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2922 unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2923 2924 Abbrev = std::make_shared<BitCodeAbbrev>(); 2925 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY)); 2926 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework 2927 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name 2928 unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2929 2930 Abbrev = std::make_shared<BitCodeAbbrev>(); 2931 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO)); 2932 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name 2933 unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2934 2935 Abbrev = std::make_shared<BitCodeAbbrev>(); 2936 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT)); 2937 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module 2938 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message 2939 unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2940 2941 Abbrev = std::make_shared<BitCodeAbbrev>(); 2942 Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS)); 2943 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name 2944 unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 2945 2946 // Write the submodule metadata block. 2947 RecordData::value_type Record[] = { 2948 getNumberOfModules(WritingModule), 2949 FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS}; 2950 Stream.EmitRecord(SUBMODULE_METADATA, Record); 2951 2952 // Write all of the submodules. 2953 std::queue<Module *> Q; 2954 Q.push(WritingModule); 2955 while (!Q.empty()) { 2956 Module *Mod = Q.front(); 2957 Q.pop(); 2958 unsigned ID = getSubmoduleID(Mod); 2959 2960 uint64_t ParentID = 0; 2961 if (Mod->Parent) { 2962 assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?"); 2963 ParentID = SubmoduleIDs[Mod->Parent]; 2964 } 2965 2966 // Emit the definition of the block. 2967 { 2968 RecordData::value_type Record[] = {SUBMODULE_DEFINITION, 2969 ID, 2970 ParentID, 2971 (RecordData::value_type)Mod->Kind, 2972 Mod->IsFramework, 2973 Mod->IsExplicit, 2974 Mod->IsSystem, 2975 Mod->IsExternC, 2976 Mod->InferSubmodules, 2977 Mod->InferExplicitSubmodules, 2978 Mod->InferExportWildcard, 2979 Mod->ConfigMacrosExhaustive, 2980 Mod->ModuleMapIsPrivate}; 2981 Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name); 2982 } 2983 2984 // Emit the requirements. 2985 for (const auto &R : Mod->Requirements) { 2986 RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second}; 2987 Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first); 2988 } 2989 2990 // Emit the umbrella header, if there is one. 2991 if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) { 2992 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER}; 2993 Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record, 2994 UmbrellaHeader.NameAsWritten); 2995 } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) { 2996 RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR}; 2997 Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record, 2998 UmbrellaDir.NameAsWritten); 2999 } 3000 3001 // Emit the headers. 3002 struct { 3003 unsigned RecordKind; 3004 unsigned Abbrev; 3005 Module::HeaderKind HeaderKind; 3006 } HeaderLists[] = { 3007 {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal}, 3008 {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual}, 3009 {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private}, 3010 {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev, 3011 Module::HK_PrivateTextual}, 3012 {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded} 3013 }; 3014 for (auto &HL : HeaderLists) { 3015 RecordData::value_type Record[] = {HL.RecordKind}; 3016 for (auto &H : Mod->Headers[HL.HeaderKind]) 3017 Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten); 3018 } 3019 3020 // Emit the top headers. 3021 { 3022 auto TopHeaders = Mod->getTopHeaders(PP->getFileManager()); 3023 RecordData::value_type Record[] = {SUBMODULE_TOPHEADER}; 3024 for (auto *H : TopHeaders) 3025 Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName()); 3026 } 3027 3028 // Emit the imports. 3029 if (!Mod->Imports.empty()) { 3030 RecordData Record; 3031 for (auto *I : Mod->Imports) 3032 Record.push_back(getSubmoduleID(I)); 3033 Stream.EmitRecord(SUBMODULE_IMPORTS, Record); 3034 } 3035 3036 // Emit the exports. 3037 if (!Mod->Exports.empty()) { 3038 RecordData Record; 3039 for (const auto &E : Mod->Exports) { 3040 // FIXME: This may fail; we don't require that all exported modules 3041 // are local or imported. 3042 Record.push_back(getSubmoduleID(E.getPointer())); 3043 Record.push_back(E.getInt()); 3044 } 3045 Stream.EmitRecord(SUBMODULE_EXPORTS, Record); 3046 } 3047 3048 //FIXME: How do we emit the 'use'd modules? They may not be submodules. 3049 // Might be unnecessary as use declarations are only used to build the 3050 // module itself. 3051 3052 // Emit the link libraries. 3053 for (const auto &LL : Mod->LinkLibraries) { 3054 RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY, 3055 LL.IsFramework}; 3056 Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library); 3057 } 3058 3059 // Emit the conflicts. 3060 for (const auto &C : Mod->Conflicts) { 3061 // FIXME: This may fail; we don't require that all conflicting modules 3062 // are local or imported. 3063 RecordData::value_type Record[] = {SUBMODULE_CONFLICT, 3064 getSubmoduleID(C.Other)}; 3065 Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message); 3066 } 3067 3068 // Emit the configuration macros. 3069 for (const auto &CM : Mod->ConfigMacros) { 3070 RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO}; 3071 Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM); 3072 } 3073 3074 // Emit the initializers, if any. 3075 RecordData Inits; 3076 for (Decl *D : Context->getModuleInitializers(Mod)) 3077 Inits.push_back(GetDeclRef(D)); 3078 if (!Inits.empty()) 3079 Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits); 3080 3081 // Emit the name of the re-exported module, if any. 3082 if (!Mod->ExportAsModule.empty()) { 3083 RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS}; 3084 Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule); 3085 } 3086 3087 // Queue up the submodules of this module. 3088 for (auto *M : Mod->submodules()) 3089 Q.push(M); 3090 } 3091 3092 Stream.ExitBlock(); 3093 3094 assert((NextSubmoduleID - FirstSubmoduleID == 3095 getNumberOfModules(WritingModule)) && 3096 "Wrong # of submodules; found a reference to a non-local, " 3097 "non-imported submodule?"); 3098 } 3099 3100 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag, 3101 bool isModule) { 3102 llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64> 3103 DiagStateIDMap; 3104 unsigned CurrID = 0; 3105 RecordData Record; 3106 3107 auto EncodeDiagStateFlags = 3108 [](const DiagnosticsEngine::DiagState *DS) -> unsigned { 3109 unsigned Result = (unsigned)DS->ExtBehavior; 3110 for (unsigned Val : 3111 {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings, 3112 (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal, 3113 (unsigned)DS->SuppressSystemWarnings}) 3114 Result = (Result << 1) | Val; 3115 return Result; 3116 }; 3117 3118 unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState); 3119 Record.push_back(Flags); 3120 3121 auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State, 3122 bool IncludeNonPragmaStates) { 3123 // Ensure that the diagnostic state wasn't modified since it was created. 3124 // We will not correctly round-trip this information otherwise. 3125 assert(Flags == EncodeDiagStateFlags(State) && 3126 "diag state flags vary in single AST file"); 3127 3128 unsigned &DiagStateID = DiagStateIDMap[State]; 3129 Record.push_back(DiagStateID); 3130 3131 if (DiagStateID == 0) { 3132 DiagStateID = ++CurrID; 3133 3134 // Add a placeholder for the number of mappings. 3135 auto SizeIdx = Record.size(); 3136 Record.emplace_back(); 3137 for (const auto &I : *State) { 3138 if (I.second.isPragma() || IncludeNonPragmaStates) { 3139 Record.push_back(I.first); 3140 Record.push_back(I.second.serialize()); 3141 } 3142 } 3143 // Update the placeholder. 3144 Record[SizeIdx] = (Record.size() - SizeIdx) / 2; 3145 } 3146 }; 3147 3148 AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule); 3149 3150 // Reserve a spot for the number of locations with state transitions. 3151 auto NumLocationsIdx = Record.size(); 3152 Record.emplace_back(); 3153 3154 // Emit the state transitions. 3155 unsigned NumLocations = 0; 3156 for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) { 3157 if (!FileIDAndFile.first.isValid() || 3158 !FileIDAndFile.second.HasLocalTransitions) 3159 continue; 3160 ++NumLocations; 3161 3162 SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0); 3163 assert(!Loc.isInvalid() && "start loc for valid FileID is invalid"); 3164 AddSourceLocation(Loc, Record); 3165 3166 Record.push_back(FileIDAndFile.second.StateTransitions.size()); 3167 for (auto &StatePoint : FileIDAndFile.second.StateTransitions) { 3168 Record.push_back(StatePoint.Offset); 3169 AddDiagState(StatePoint.State, false); 3170 } 3171 } 3172 3173 // Backpatch the number of locations. 3174 Record[NumLocationsIdx] = NumLocations; 3175 3176 // Emit CurDiagStateLoc. Do it last in order to match source order. 3177 // 3178 // This also protects against a hypothetical corner case with simulating 3179 // -Werror settings for implicit modules in the ASTReader, where reading 3180 // CurDiagState out of context could change whether warning pragmas are 3181 // treated as errors. 3182 AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record); 3183 AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false); 3184 3185 Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record); 3186 } 3187 3188 //===----------------------------------------------------------------------===// 3189 // Type Serialization 3190 //===----------------------------------------------------------------------===// 3191 3192 /// Write the representation of a type to the AST stream. 3193 void ASTWriter::WriteType(QualType T) { 3194 TypeIdx &IdxRef = TypeIdxs[T]; 3195 if (IdxRef.getIndex() == 0) // we haven't seen this type before. 3196 IdxRef = TypeIdx(NextTypeID++); 3197 TypeIdx Idx = IdxRef; 3198 3199 assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST"); 3200 3201 RecordData Record; 3202 3203 // Emit the type's representation. 3204 ASTTypeWriter W(*this, Record); 3205 W.Visit(T); 3206 uint64_t Offset = W.Emit(); 3207 3208 // Record the offset for this type. 3209 unsigned Index = Idx.getIndex() - FirstTypeID; 3210 if (TypeOffsets.size() == Index) 3211 TypeOffsets.push_back(Offset); 3212 else if (TypeOffsets.size() < Index) { 3213 TypeOffsets.resize(Index + 1); 3214 TypeOffsets[Index] = Offset; 3215 } else { 3216 llvm_unreachable("Types emitted in wrong order"); 3217 } 3218 } 3219 3220 //===----------------------------------------------------------------------===// 3221 // Declaration Serialization 3222 //===----------------------------------------------------------------------===// 3223 3224 /// Write the block containing all of the declaration IDs 3225 /// lexically declared within the given DeclContext. 3226 /// 3227 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the 3228 /// bitstream, or 0 if no block was written. 3229 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context, 3230 DeclContext *DC) { 3231 if (DC->decls_empty()) 3232 return 0; 3233 3234 uint64_t Offset = Stream.GetCurrentBitNo(); 3235 SmallVector<uint32_t, 128> KindDeclPairs; 3236 for (const auto *D : DC->decls()) { 3237 KindDeclPairs.push_back(D->getKind()); 3238 KindDeclPairs.push_back(GetDeclRef(D)); 3239 } 3240 3241 ++NumLexicalDeclContexts; 3242 RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL}; 3243 Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, 3244 bytes(KindDeclPairs)); 3245 return Offset; 3246 } 3247 3248 void ASTWriter::WriteTypeDeclOffsets() { 3249 using namespace llvm; 3250 3251 // Write the type offsets array 3252 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3253 Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET)); 3254 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types 3255 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index 3256 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block 3257 unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3258 { 3259 RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(), 3260 FirstTypeID - NUM_PREDEF_TYPE_IDS}; 3261 Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets)); 3262 } 3263 3264 // Write the declaration offsets array 3265 Abbrev = std::make_shared<BitCodeAbbrev>(); 3266 Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET)); 3267 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations 3268 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID 3269 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block 3270 unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3271 { 3272 RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(), 3273 FirstDeclID - NUM_PREDEF_DECL_IDS}; 3274 Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets)); 3275 } 3276 } 3277 3278 void ASTWriter::WriteFileDeclIDsMap() { 3279 using namespace llvm; 3280 3281 SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs( 3282 FileDeclIDs.begin(), FileDeclIDs.end()); 3283 llvm::sort(SortedFileDeclIDs, llvm::less_first()); 3284 3285 // Join the vectors of DeclIDs from all files. 3286 SmallVector<DeclID, 256> FileGroupedDeclIDs; 3287 for (auto &FileDeclEntry : SortedFileDeclIDs) { 3288 DeclIDInFileInfo &Info = *FileDeclEntry.second; 3289 Info.FirstDeclIndex = FileGroupedDeclIDs.size(); 3290 for (auto &LocDeclEntry : Info.DeclIDs) 3291 FileGroupedDeclIDs.push_back(LocDeclEntry.second); 3292 } 3293 3294 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3295 Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS)); 3296 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3297 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3298 unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev)); 3299 RecordData::value_type Record[] = {FILE_SORTED_DECLS, 3300 FileGroupedDeclIDs.size()}; 3301 Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs)); 3302 } 3303 3304 void ASTWriter::WriteComments() { 3305 Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3); 3306 auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); }); 3307 if (!PP->getPreprocessorOpts().WriteCommentListToPCH) 3308 return; 3309 RecordData Record; 3310 for (const auto &FO : Context->Comments.OrderedComments) { 3311 for (const auto &OC : FO.second) { 3312 const RawComment *I = OC.second; 3313 Record.clear(); 3314 AddSourceRange(I->getSourceRange(), Record); 3315 Record.push_back(I->getKind()); 3316 Record.push_back(I->isTrailingComment()); 3317 Record.push_back(I->isAlmostTrailingComment()); 3318 Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record); 3319 } 3320 } 3321 } 3322 3323 //===----------------------------------------------------------------------===// 3324 // Global Method Pool and Selector Serialization 3325 //===----------------------------------------------------------------------===// 3326 3327 namespace { 3328 3329 // Trait used for the on-disk hash table used in the method pool. 3330 class ASTMethodPoolTrait { 3331 ASTWriter &Writer; 3332 3333 public: 3334 using key_type = Selector; 3335 using key_type_ref = key_type; 3336 3337 struct data_type { 3338 SelectorID ID; 3339 ObjCMethodList Instance, Factory; 3340 }; 3341 using data_type_ref = const data_type &; 3342 3343 using hash_value_type = unsigned; 3344 using offset_type = unsigned; 3345 3346 explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {} 3347 3348 static hash_value_type ComputeHash(Selector Sel) { 3349 return serialization::ComputeHash(Sel); 3350 } 3351 3352 std::pair<unsigned, unsigned> 3353 EmitKeyDataLength(raw_ostream& Out, Selector Sel, 3354 data_type_ref Methods) { 3355 using namespace llvm::support; 3356 3357 endian::Writer LE(Out, little); 3358 unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4); 3359 LE.write<uint16_t>(KeyLen); 3360 unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts 3361 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3362 Method = Method->getNext()) 3363 if (Method->getMethod()) 3364 DataLen += 4; 3365 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3366 Method = Method->getNext()) 3367 if (Method->getMethod()) 3368 DataLen += 4; 3369 LE.write<uint16_t>(DataLen); 3370 return std::make_pair(KeyLen, DataLen); 3371 } 3372 3373 void EmitKey(raw_ostream& Out, Selector Sel, unsigned) { 3374 using namespace llvm::support; 3375 3376 endian::Writer LE(Out, little); 3377 uint64_t Start = Out.tell(); 3378 assert((Start >> 32) == 0 && "Selector key offset too large"); 3379 Writer.SetSelectorOffset(Sel, Start); 3380 unsigned N = Sel.getNumArgs(); 3381 LE.write<uint16_t>(N); 3382 if (N == 0) 3383 N = 1; 3384 for (unsigned I = 0; I != N; ++I) 3385 LE.write<uint32_t>( 3386 Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I))); 3387 } 3388 3389 void EmitData(raw_ostream& Out, key_type_ref, 3390 data_type_ref Methods, unsigned DataLen) { 3391 using namespace llvm::support; 3392 3393 endian::Writer LE(Out, little); 3394 uint64_t Start = Out.tell(); (void)Start; 3395 LE.write<uint32_t>(Methods.ID); 3396 unsigned NumInstanceMethods = 0; 3397 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3398 Method = Method->getNext()) 3399 if (Method->getMethod()) 3400 ++NumInstanceMethods; 3401 3402 unsigned NumFactoryMethods = 0; 3403 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3404 Method = Method->getNext()) 3405 if (Method->getMethod()) 3406 ++NumFactoryMethods; 3407 3408 unsigned InstanceBits = Methods.Instance.getBits(); 3409 assert(InstanceBits < 4); 3410 unsigned InstanceHasMoreThanOneDeclBit = 3411 Methods.Instance.hasMoreThanOneDecl(); 3412 unsigned FullInstanceBits = (NumInstanceMethods << 3) | 3413 (InstanceHasMoreThanOneDeclBit << 2) | 3414 InstanceBits; 3415 unsigned FactoryBits = Methods.Factory.getBits(); 3416 assert(FactoryBits < 4); 3417 unsigned FactoryHasMoreThanOneDeclBit = 3418 Methods.Factory.hasMoreThanOneDecl(); 3419 unsigned FullFactoryBits = (NumFactoryMethods << 3) | 3420 (FactoryHasMoreThanOneDeclBit << 2) | 3421 FactoryBits; 3422 LE.write<uint16_t>(FullInstanceBits); 3423 LE.write<uint16_t>(FullFactoryBits); 3424 for (const ObjCMethodList *Method = &Methods.Instance; Method; 3425 Method = Method->getNext()) 3426 if (Method->getMethod()) 3427 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3428 for (const ObjCMethodList *Method = &Methods.Factory; Method; 3429 Method = Method->getNext()) 3430 if (Method->getMethod()) 3431 LE.write<uint32_t>(Writer.getDeclID(Method->getMethod())); 3432 3433 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3434 } 3435 }; 3436 3437 } // namespace 3438 3439 /// Write ObjC data: selectors and the method pool. 3440 /// 3441 /// The method pool contains both instance and factory methods, stored 3442 /// in an on-disk hash table indexed by the selector. The hash table also 3443 /// contains an empty entry for every other selector known to Sema. 3444 void ASTWriter::WriteSelectors(Sema &SemaRef) { 3445 using namespace llvm; 3446 3447 // Do we have to do anything at all? 3448 if (SemaRef.MethodPool.empty() && SelectorIDs.empty()) 3449 return; 3450 unsigned NumTableEntries = 0; 3451 // Create and write out the blob that contains selectors and the method pool. 3452 { 3453 llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator; 3454 ASTMethodPoolTrait Trait(*this); 3455 3456 // Create the on-disk hash table representation. We walk through every 3457 // selector we've seen and look it up in the method pool. 3458 SelectorOffsets.resize(NextSelectorID - FirstSelectorID); 3459 for (auto &SelectorAndID : SelectorIDs) { 3460 Selector S = SelectorAndID.first; 3461 SelectorID ID = SelectorAndID.second; 3462 Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S); 3463 ASTMethodPoolTrait::data_type Data = { 3464 ID, 3465 ObjCMethodList(), 3466 ObjCMethodList() 3467 }; 3468 if (F != SemaRef.MethodPool.end()) { 3469 Data.Instance = F->second.first; 3470 Data.Factory = F->second.second; 3471 } 3472 // Only write this selector if it's not in an existing AST or something 3473 // changed. 3474 if (Chain && ID < FirstSelectorID) { 3475 // Selector already exists. Did it change? 3476 bool changed = false; 3477 for (ObjCMethodList *M = &Data.Instance; 3478 !changed && M && M->getMethod(); M = M->getNext()) { 3479 if (!M->getMethod()->isFromASTFile()) 3480 changed = true; 3481 } 3482 for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod(); 3483 M = M->getNext()) { 3484 if (!M->getMethod()->isFromASTFile()) 3485 changed = true; 3486 } 3487 if (!changed) 3488 continue; 3489 } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) { 3490 // A new method pool entry. 3491 ++NumTableEntries; 3492 } 3493 Generator.insert(S, Data, Trait); 3494 } 3495 3496 // Create the on-disk hash table in a buffer. 3497 SmallString<4096> MethodPool; 3498 uint32_t BucketOffset; 3499 { 3500 using namespace llvm::support; 3501 3502 ASTMethodPoolTrait Trait(*this); 3503 llvm::raw_svector_ostream Out(MethodPool); 3504 // Make sure that no bucket is at offset 0 3505 endian::write<uint32_t>(Out, 0, little); 3506 BucketOffset = Generator.Emit(Out, Trait); 3507 } 3508 3509 // Create a blob abbreviation 3510 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3511 Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL)); 3512 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3513 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3514 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3515 unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3516 3517 // Write the method pool 3518 { 3519 RecordData::value_type Record[] = {METHOD_POOL, BucketOffset, 3520 NumTableEntries}; 3521 Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool); 3522 } 3523 3524 // Create a blob abbreviation for the selector table offsets. 3525 Abbrev = std::make_shared<BitCodeAbbrev>(); 3526 Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS)); 3527 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size 3528 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3529 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3530 unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3531 3532 // Write the selector offsets table. 3533 { 3534 RecordData::value_type Record[] = { 3535 SELECTOR_OFFSETS, SelectorOffsets.size(), 3536 FirstSelectorID - NUM_PREDEF_SELECTOR_IDS}; 3537 Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record, 3538 bytes(SelectorOffsets)); 3539 } 3540 } 3541 } 3542 3543 /// Write the selectors referenced in @selector expression into AST file. 3544 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) { 3545 using namespace llvm; 3546 3547 if (SemaRef.ReferencedSelectors.empty()) 3548 return; 3549 3550 RecordData Record; 3551 ASTRecordWriter Writer(*this, Record); 3552 3553 // Note: this writes out all references even for a dependent AST. But it is 3554 // very tricky to fix, and given that @selector shouldn't really appear in 3555 // headers, probably not worth it. It's not a correctness issue. 3556 for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) { 3557 Selector Sel = SelectorAndLocation.first; 3558 SourceLocation Loc = SelectorAndLocation.second; 3559 Writer.AddSelectorRef(Sel); 3560 Writer.AddSourceLocation(Loc); 3561 } 3562 Writer.Emit(REFERENCED_SELECTOR_POOL); 3563 } 3564 3565 //===----------------------------------------------------------------------===// 3566 // Identifier Table Serialization 3567 //===----------------------------------------------------------------------===// 3568 3569 /// Determine the declaration that should be put into the name lookup table to 3570 /// represent the given declaration in this module. This is usually D itself, 3571 /// but if D was imported and merged into a local declaration, we want the most 3572 /// recent local declaration instead. The chosen declaration will be the most 3573 /// recent declaration in any module that imports this one. 3574 static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts, 3575 NamedDecl *D) { 3576 if (!LangOpts.Modules || !D->isFromASTFile()) 3577 return D; 3578 3579 if (Decl *Redecl = D->getPreviousDecl()) { 3580 // For Redeclarable decls, a prior declaration might be local. 3581 for (; Redecl; Redecl = Redecl->getPreviousDecl()) { 3582 // If we find a local decl, we're done. 3583 if (!Redecl->isFromASTFile()) { 3584 // Exception: in very rare cases (for injected-class-names), not all 3585 // redeclarations are in the same semantic context. Skip ones in a 3586 // different context. They don't go in this lookup table at all. 3587 if (!Redecl->getDeclContext()->getRedeclContext()->Equals( 3588 D->getDeclContext()->getRedeclContext())) 3589 continue; 3590 return cast<NamedDecl>(Redecl); 3591 } 3592 3593 // If we find a decl from a (chained-)PCH stop since we won't find a 3594 // local one. 3595 if (Redecl->getOwningModuleID() == 0) 3596 break; 3597 } 3598 } else if (Decl *First = D->getCanonicalDecl()) { 3599 // For Mergeable decls, the first decl might be local. 3600 if (!First->isFromASTFile()) 3601 return cast<NamedDecl>(First); 3602 } 3603 3604 // All declarations are imported. Our most recent declaration will also be 3605 // the most recent one in anyone who imports us. 3606 return D; 3607 } 3608 3609 namespace { 3610 3611 class ASTIdentifierTableTrait { 3612 ASTWriter &Writer; 3613 Preprocessor &PP; 3614 IdentifierResolver &IdResolver; 3615 bool IsModule; 3616 bool NeedDecls; 3617 ASTWriter::RecordData *InterestingIdentifierOffsets; 3618 3619 /// Determines whether this is an "interesting" identifier that needs a 3620 /// full IdentifierInfo structure written into the hash table. Notably, this 3621 /// doesn't check whether the name has macros defined; use PublicMacroIterator 3622 /// to check that. 3623 bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) { 3624 if (MacroOffset || 3625 II->isPoisoned() || 3626 (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) || 3627 II->hasRevertedTokenIDToIdentifier() || 3628 (NeedDecls && II->getFETokenInfo())) 3629 return true; 3630 3631 return false; 3632 } 3633 3634 public: 3635 using key_type = IdentifierInfo *; 3636 using key_type_ref = key_type; 3637 3638 using data_type = IdentID; 3639 using data_type_ref = data_type; 3640 3641 using hash_value_type = unsigned; 3642 using offset_type = unsigned; 3643 3644 ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP, 3645 IdentifierResolver &IdResolver, bool IsModule, 3646 ASTWriter::RecordData *InterestingIdentifierOffsets) 3647 : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule), 3648 NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus), 3649 InterestingIdentifierOffsets(InterestingIdentifierOffsets) {} 3650 3651 bool needDecls() const { return NeedDecls; } 3652 3653 static hash_value_type ComputeHash(const IdentifierInfo* II) { 3654 return llvm::djbHash(II->getName()); 3655 } 3656 3657 bool isInterestingIdentifier(const IdentifierInfo *II) { 3658 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3659 return isInterestingIdentifier(II, MacroOffset); 3660 } 3661 3662 bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) { 3663 return isInterestingIdentifier(II, 0); 3664 } 3665 3666 std::pair<unsigned, unsigned> 3667 EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) { 3668 unsigned KeyLen = II->getLength() + 1; 3669 unsigned DataLen = 4; // 4 bytes for the persistent ID << 1 3670 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3671 if (isInterestingIdentifier(II, MacroOffset)) { 3672 DataLen += 2; // 2 bytes for builtin ID 3673 DataLen += 2; // 2 bytes for flags 3674 if (MacroOffset) 3675 DataLen += 4; // MacroDirectives offset. 3676 3677 if (NeedDecls) { 3678 for (IdentifierResolver::iterator D = IdResolver.begin(II), 3679 DEnd = IdResolver.end(); 3680 D != DEnd; ++D) 3681 DataLen += 4; 3682 } 3683 } 3684 3685 using namespace llvm::support; 3686 3687 endian::Writer LE(Out, little); 3688 3689 assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen); 3690 LE.write<uint16_t>(DataLen); 3691 // We emit the key length after the data length so that every 3692 // string is preceded by a 16-bit length. This matches the PTH 3693 // format for storing identifiers. 3694 LE.write<uint16_t>(KeyLen); 3695 return std::make_pair(KeyLen, DataLen); 3696 } 3697 3698 void EmitKey(raw_ostream& Out, const IdentifierInfo* II, 3699 unsigned KeyLen) { 3700 // Record the location of the key data. This is used when generating 3701 // the mapping from persistent IDs to strings. 3702 Writer.SetIdentifierOffset(II, Out.tell()); 3703 3704 // Emit the offset of the key/data length information to the interesting 3705 // identifiers table if necessary. 3706 if (InterestingIdentifierOffsets && isInterestingIdentifier(II)) 3707 InterestingIdentifierOffsets->push_back(Out.tell() - 4); 3708 3709 Out.write(II->getNameStart(), KeyLen); 3710 } 3711 3712 void EmitData(raw_ostream& Out, IdentifierInfo* II, 3713 IdentID ID, unsigned) { 3714 using namespace llvm::support; 3715 3716 endian::Writer LE(Out, little); 3717 3718 auto MacroOffset = Writer.getMacroDirectivesOffset(II); 3719 if (!isInterestingIdentifier(II, MacroOffset)) { 3720 LE.write<uint32_t>(ID << 1); 3721 return; 3722 } 3723 3724 LE.write<uint32_t>((ID << 1) | 0x01); 3725 uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID(); 3726 assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader."); 3727 LE.write<uint16_t>(Bits); 3728 Bits = 0; 3729 bool HadMacroDefinition = MacroOffset != 0; 3730 Bits = (Bits << 1) | unsigned(HadMacroDefinition); 3731 Bits = (Bits << 1) | unsigned(II->isExtensionToken()); 3732 Bits = (Bits << 1) | unsigned(II->isPoisoned()); 3733 Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin()); 3734 Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier()); 3735 Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword()); 3736 LE.write<uint16_t>(Bits); 3737 3738 if (HadMacroDefinition) 3739 LE.write<uint32_t>(MacroOffset); 3740 3741 if (NeedDecls) { 3742 // Emit the declaration IDs in reverse order, because the 3743 // IdentifierResolver provides the declarations as they would be 3744 // visible (e.g., the function "stat" would come before the struct 3745 // "stat"), but the ASTReader adds declarations to the end of the list 3746 // (so we need to see the struct "stat" before the function "stat"). 3747 // Only emit declarations that aren't from a chained PCH, though. 3748 SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), 3749 IdResolver.end()); 3750 for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(), 3751 DEnd = Decls.rend(); 3752 D != DEnd; ++D) 3753 LE.write<uint32_t>( 3754 Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D))); 3755 } 3756 } 3757 }; 3758 3759 } // namespace 3760 3761 /// Write the identifier table into the AST file. 3762 /// 3763 /// The identifier table consists of a blob containing string data 3764 /// (the actual identifiers themselves) and a separate "offsets" index 3765 /// that maps identifier IDs to locations within the blob. 3766 void ASTWriter::WriteIdentifierTable(Preprocessor &PP, 3767 IdentifierResolver &IdResolver, 3768 bool IsModule) { 3769 using namespace llvm; 3770 3771 RecordData InterestingIdents; 3772 3773 // Create and write out the blob that contains the identifier 3774 // strings. 3775 { 3776 llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator; 3777 ASTIdentifierTableTrait Trait( 3778 *this, PP, IdResolver, IsModule, 3779 (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr); 3780 3781 // Look for any identifiers that were named while processing the 3782 // headers, but are otherwise not needed. We add these to the hash 3783 // table to enable checking of the predefines buffer in the case 3784 // where the user adds new macro definitions when building the AST 3785 // file. 3786 SmallVector<const IdentifierInfo *, 128> IIs; 3787 for (const auto &ID : PP.getIdentifierTable()) 3788 IIs.push_back(ID.second); 3789 // Sort the identifiers lexicographically before getting them references so 3790 // that their order is stable. 3791 llvm::sort(IIs, llvm::deref<std::less<>>()); 3792 for (const IdentifierInfo *II : IIs) 3793 if (Trait.isInterestingNonMacroIdentifier(II)) 3794 getIdentifierRef(II); 3795 3796 // Create the on-disk hash table representation. We only store offsets 3797 // for identifiers that appear here for the first time. 3798 IdentifierOffsets.resize(NextIdentID - FirstIdentID); 3799 for (auto IdentIDPair : IdentifierIDs) { 3800 auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first); 3801 IdentID ID = IdentIDPair.second; 3802 assert(II && "NULL identifier in identifier table"); 3803 // Write out identifiers if either the ID is local or the identifier has 3804 // changed since it was loaded. 3805 if (ID >= FirstIdentID || !Chain || !II->isFromAST() 3806 || II->hasChangedSinceDeserialization() || 3807 (Trait.needDecls() && 3808 II->hasFETokenInfoChangedSinceDeserialization())) 3809 Generator.insert(II, ID, Trait); 3810 } 3811 3812 // Create the on-disk hash table in a buffer. 3813 SmallString<4096> IdentifierTable; 3814 uint32_t BucketOffset; 3815 { 3816 using namespace llvm::support; 3817 3818 llvm::raw_svector_ostream Out(IdentifierTable); 3819 // Make sure that no bucket is at offset 0 3820 endian::write<uint32_t>(Out, 0, little); 3821 BucketOffset = Generator.Emit(Out, Trait); 3822 } 3823 3824 // Create a blob abbreviation 3825 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3826 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE)); 3827 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); 3828 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3829 unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3830 3831 // Write the identifier table 3832 RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset}; 3833 Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable); 3834 } 3835 3836 // Write the offsets table for identifier IDs. 3837 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 3838 Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET)); 3839 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers 3840 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID 3841 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 3842 unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 3843 3844 #ifndef NDEBUG 3845 for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I) 3846 assert(IdentifierOffsets[I] && "Missing identifier offset?"); 3847 #endif 3848 3849 RecordData::value_type Record[] = {IDENTIFIER_OFFSET, 3850 IdentifierOffsets.size(), 3851 FirstIdentID - NUM_PREDEF_IDENT_IDS}; 3852 Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record, 3853 bytes(IdentifierOffsets)); 3854 3855 // In C++, write the list of interesting identifiers (those that are 3856 // defined as macros, poisoned, or similar unusual things). 3857 if (!InterestingIdents.empty()) 3858 Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents); 3859 } 3860 3861 //===----------------------------------------------------------------------===// 3862 // DeclContext's Name Lookup Table Serialization 3863 //===----------------------------------------------------------------------===// 3864 3865 namespace { 3866 3867 // Trait used for the on-disk hash table used in the method pool. 3868 class ASTDeclContextNameLookupTrait { 3869 ASTWriter &Writer; 3870 llvm::SmallVector<DeclID, 64> DeclIDs; 3871 3872 public: 3873 using key_type = DeclarationNameKey; 3874 using key_type_ref = key_type; 3875 3876 /// A start and end index into DeclIDs, representing a sequence of decls. 3877 using data_type = std::pair<unsigned, unsigned>; 3878 using data_type_ref = const data_type &; 3879 3880 using hash_value_type = unsigned; 3881 using offset_type = unsigned; 3882 3883 explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {} 3884 3885 template<typename Coll> 3886 data_type getData(const Coll &Decls) { 3887 unsigned Start = DeclIDs.size(); 3888 for (NamedDecl *D : Decls) { 3889 DeclIDs.push_back( 3890 Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D))); 3891 } 3892 return std::make_pair(Start, DeclIDs.size()); 3893 } 3894 3895 data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) { 3896 unsigned Start = DeclIDs.size(); 3897 for (auto ID : FromReader) 3898 DeclIDs.push_back(ID); 3899 return std::make_pair(Start, DeclIDs.size()); 3900 } 3901 3902 static bool EqualKey(key_type_ref a, key_type_ref b) { 3903 return a == b; 3904 } 3905 3906 hash_value_type ComputeHash(DeclarationNameKey Name) { 3907 return Name.getHash(); 3908 } 3909 3910 void EmitFileRef(raw_ostream &Out, ModuleFile *F) const { 3911 assert(Writer.hasChain() && 3912 "have reference to loaded module file but no chain?"); 3913 3914 using namespace llvm::support; 3915 3916 endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little); 3917 } 3918 3919 std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out, 3920 DeclarationNameKey Name, 3921 data_type_ref Lookup) { 3922 using namespace llvm::support; 3923 3924 endian::Writer LE(Out, little); 3925 unsigned KeyLen = 1; 3926 switch (Name.getKind()) { 3927 case DeclarationName::Identifier: 3928 case DeclarationName::ObjCZeroArgSelector: 3929 case DeclarationName::ObjCOneArgSelector: 3930 case DeclarationName::ObjCMultiArgSelector: 3931 case DeclarationName::CXXLiteralOperatorName: 3932 case DeclarationName::CXXDeductionGuideName: 3933 KeyLen += 4; 3934 break; 3935 case DeclarationName::CXXOperatorName: 3936 KeyLen += 1; 3937 break; 3938 case DeclarationName::CXXConstructorName: 3939 case DeclarationName::CXXDestructorName: 3940 case DeclarationName::CXXConversionFunctionName: 3941 case DeclarationName::CXXUsingDirective: 3942 break; 3943 } 3944 LE.write<uint16_t>(KeyLen); 3945 3946 // 4 bytes for each DeclID. 3947 unsigned DataLen = 4 * (Lookup.second - Lookup.first); 3948 assert(uint16_t(DataLen) == DataLen && 3949 "too many decls for serialized lookup result"); 3950 LE.write<uint16_t>(DataLen); 3951 3952 return std::make_pair(KeyLen, DataLen); 3953 } 3954 3955 void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) { 3956 using namespace llvm::support; 3957 3958 endian::Writer LE(Out, little); 3959 LE.write<uint8_t>(Name.getKind()); 3960 switch (Name.getKind()) { 3961 case DeclarationName::Identifier: 3962 case DeclarationName::CXXLiteralOperatorName: 3963 case DeclarationName::CXXDeductionGuideName: 3964 LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier())); 3965 return; 3966 case DeclarationName::ObjCZeroArgSelector: 3967 case DeclarationName::ObjCOneArgSelector: 3968 case DeclarationName::ObjCMultiArgSelector: 3969 LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector())); 3970 return; 3971 case DeclarationName::CXXOperatorName: 3972 assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS && 3973 "Invalid operator?"); 3974 LE.write<uint8_t>(Name.getOperatorKind()); 3975 return; 3976 case DeclarationName::CXXConstructorName: 3977 case DeclarationName::CXXDestructorName: 3978 case DeclarationName::CXXConversionFunctionName: 3979 case DeclarationName::CXXUsingDirective: 3980 return; 3981 } 3982 3983 llvm_unreachable("Invalid name kind?"); 3984 } 3985 3986 void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup, 3987 unsigned DataLen) { 3988 using namespace llvm::support; 3989 3990 endian::Writer LE(Out, little); 3991 uint64_t Start = Out.tell(); (void)Start; 3992 for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I) 3993 LE.write<uint32_t>(DeclIDs[I]); 3994 assert(Out.tell() - Start == DataLen && "Data length is wrong"); 3995 } 3996 }; 3997 3998 } // namespace 3999 4000 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result, 4001 DeclContext *DC) { 4002 return Result.hasExternalDecls() && 4003 DC->hasNeedToReconcileExternalVisibleStorage(); 4004 } 4005 4006 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result, 4007 DeclContext *DC) { 4008 for (auto *D : Result.getLookupResult()) 4009 if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile()) 4010 return false; 4011 4012 return true; 4013 } 4014 4015 void 4016 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC, 4017 llvm::SmallVectorImpl<char> &LookupTable) { 4018 assert(!ConstDC->hasLazyLocalLexicalLookups() && 4019 !ConstDC->hasLazyExternalLexicalLookups() && 4020 "must call buildLookups first"); 4021 4022 // FIXME: We need to build the lookups table, which is logically const. 4023 auto *DC = const_cast<DeclContext*>(ConstDC); 4024 assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table"); 4025 4026 // Create the on-disk hash table representation. 4027 MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait, 4028 ASTDeclContextNameLookupTrait> Generator; 4029 ASTDeclContextNameLookupTrait Trait(*this); 4030 4031 // The first step is to collect the declaration names which we need to 4032 // serialize into the name lookup table, and to collect them in a stable 4033 // order. 4034 SmallVector<DeclarationName, 16> Names; 4035 4036 // We also build up small sets of the constructor and conversion function 4037 // names which are visible. 4038 llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet; 4039 4040 for (auto &Lookup : *DC->buildLookup()) { 4041 auto &Name = Lookup.first; 4042 auto &Result = Lookup.second; 4043 4044 // If there are no local declarations in our lookup result, we 4045 // don't need to write an entry for the name at all. If we can't 4046 // write out a lookup set without performing more deserialization, 4047 // just skip this entry. 4048 if (isLookupResultExternal(Result, DC) && 4049 isLookupResultEntirelyExternal(Result, DC)) 4050 continue; 4051 4052 // We also skip empty results. If any of the results could be external and 4053 // the currently available results are empty, then all of the results are 4054 // external and we skip it above. So the only way we get here with an empty 4055 // results is when no results could have been external *and* we have 4056 // external results. 4057 // 4058 // FIXME: While we might want to start emitting on-disk entries for negative 4059 // lookups into a decl context as an optimization, today we *have* to skip 4060 // them because there are names with empty lookup results in decl contexts 4061 // which we can't emit in any stable ordering: we lookup constructors and 4062 // conversion functions in the enclosing namespace scope creating empty 4063 // results for them. This in almost certainly a bug in Clang's name lookup, 4064 // but that is likely to be hard or impossible to fix and so we tolerate it 4065 // here by omitting lookups with empty results. 4066 if (Lookup.second.getLookupResult().empty()) 4067 continue; 4068 4069 switch (Lookup.first.getNameKind()) { 4070 default: 4071 Names.push_back(Lookup.first); 4072 break; 4073 4074 case DeclarationName::CXXConstructorName: 4075 assert(isa<CXXRecordDecl>(DC) && 4076 "Cannot have a constructor name outside of a class!"); 4077 ConstructorNameSet.insert(Name); 4078 break; 4079 4080 case DeclarationName::CXXConversionFunctionName: 4081 assert(isa<CXXRecordDecl>(DC) && 4082 "Cannot have a conversion function name outside of a class!"); 4083 ConversionNameSet.insert(Name); 4084 break; 4085 } 4086 } 4087 4088 // Sort the names into a stable order. 4089 llvm::sort(Names); 4090 4091 if (auto *D = dyn_cast<CXXRecordDecl>(DC)) { 4092 // We need to establish an ordering of constructor and conversion function 4093 // names, and they don't have an intrinsic ordering. 4094 4095 // First we try the easy case by forming the current context's constructor 4096 // name and adding that name first. This is a very useful optimization to 4097 // avoid walking the lexical declarations in many cases, and it also 4098 // handles the only case where a constructor name can come from some other 4099 // lexical context -- when that name is an implicit constructor merged from 4100 // another declaration in the redecl chain. Any non-implicit constructor or 4101 // conversion function which doesn't occur in all the lexical contexts 4102 // would be an ODR violation. 4103 auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName( 4104 Context->getCanonicalType(Context->getRecordType(D))); 4105 if (ConstructorNameSet.erase(ImplicitCtorName)) 4106 Names.push_back(ImplicitCtorName); 4107 4108 // If we still have constructors or conversion functions, we walk all the 4109 // names in the decl and add the constructors and conversion functions 4110 // which are visible in the order they lexically occur within the context. 4111 if (!ConstructorNameSet.empty() || !ConversionNameSet.empty()) 4112 for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls()) 4113 if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) { 4114 auto Name = ChildND->getDeclName(); 4115 switch (Name.getNameKind()) { 4116 default: 4117 continue; 4118 4119 case DeclarationName::CXXConstructorName: 4120 if (ConstructorNameSet.erase(Name)) 4121 Names.push_back(Name); 4122 break; 4123 4124 case DeclarationName::CXXConversionFunctionName: 4125 if (ConversionNameSet.erase(Name)) 4126 Names.push_back(Name); 4127 break; 4128 } 4129 4130 if (ConstructorNameSet.empty() && ConversionNameSet.empty()) 4131 break; 4132 } 4133 4134 assert(ConstructorNameSet.empty() && "Failed to find all of the visible " 4135 "constructors by walking all the " 4136 "lexical members of the context."); 4137 assert(ConversionNameSet.empty() && "Failed to find all of the visible " 4138 "conversion functions by walking all " 4139 "the lexical members of the context."); 4140 } 4141 4142 // Next we need to do a lookup with each name into this decl context to fully 4143 // populate any results from external sources. We don't actually use the 4144 // results of these lookups because we only want to use the results after all 4145 // results have been loaded and the pointers into them will be stable. 4146 for (auto &Name : Names) 4147 DC->lookup(Name); 4148 4149 // Now we need to insert the results for each name into the hash table. For 4150 // constructor names and conversion function names, we actually need to merge 4151 // all of the results for them into one list of results each and insert 4152 // those. 4153 SmallVector<NamedDecl *, 8> ConstructorDecls; 4154 SmallVector<NamedDecl *, 8> ConversionDecls; 4155 4156 // Now loop over the names, either inserting them or appending for the two 4157 // special cases. 4158 for (auto &Name : Names) { 4159 DeclContext::lookup_result Result = DC->noload_lookup(Name); 4160 4161 switch (Name.getNameKind()) { 4162 default: 4163 Generator.insert(Name, Trait.getData(Result), Trait); 4164 break; 4165 4166 case DeclarationName::CXXConstructorName: 4167 ConstructorDecls.append(Result.begin(), Result.end()); 4168 break; 4169 4170 case DeclarationName::CXXConversionFunctionName: 4171 ConversionDecls.append(Result.begin(), Result.end()); 4172 break; 4173 } 4174 } 4175 4176 // Handle our two special cases if we ended up having any. We arbitrarily use 4177 // the first declaration's name here because the name itself isn't part of 4178 // the key, only the kind of name is used. 4179 if (!ConstructorDecls.empty()) 4180 Generator.insert(ConstructorDecls.front()->getDeclName(), 4181 Trait.getData(ConstructorDecls), Trait); 4182 if (!ConversionDecls.empty()) 4183 Generator.insert(ConversionDecls.front()->getDeclName(), 4184 Trait.getData(ConversionDecls), Trait); 4185 4186 // Create the on-disk hash table. Also emit the existing imported and 4187 // merged table if there is one. 4188 auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr; 4189 Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr); 4190 } 4191 4192 /// Write the block containing all of the declaration IDs 4193 /// visible from the given DeclContext. 4194 /// 4195 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the 4196 /// bitstream, or 0 if no block was written. 4197 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context, 4198 DeclContext *DC) { 4199 // If we imported a key declaration of this namespace, write the visible 4200 // lookup results as an update record for it rather than including them 4201 // on this declaration. We will only look at key declarations on reload. 4202 if (isa<NamespaceDecl>(DC) && Chain && 4203 Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) { 4204 // Only do this once, for the first local declaration of the namespace. 4205 for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev; 4206 Prev = Prev->getPreviousDecl()) 4207 if (!Prev->isFromASTFile()) 4208 return 0; 4209 4210 // Note that we need to emit an update record for the primary context. 4211 UpdatedDeclContexts.insert(DC->getPrimaryContext()); 4212 4213 // Make sure all visible decls are written. They will be recorded later. We 4214 // do this using a side data structure so we can sort the names into 4215 // a deterministic order. 4216 StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup(); 4217 SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16> 4218 LookupResults; 4219 if (Map) { 4220 LookupResults.reserve(Map->size()); 4221 for (auto &Entry : *Map) 4222 LookupResults.push_back( 4223 std::make_pair(Entry.first, Entry.second.getLookupResult())); 4224 } 4225 4226 llvm::sort(LookupResults, llvm::less_first()); 4227 for (auto &NameAndResult : LookupResults) { 4228 DeclarationName Name = NameAndResult.first; 4229 DeclContext::lookup_result Result = NameAndResult.second; 4230 if (Name.getNameKind() == DeclarationName::CXXConstructorName || 4231 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 4232 // We have to work around a name lookup bug here where negative lookup 4233 // results for these names get cached in namespace lookup tables (these 4234 // names should never be looked up in a namespace). 4235 assert(Result.empty() && "Cannot have a constructor or conversion " 4236 "function name in a namespace!"); 4237 continue; 4238 } 4239 4240 for (NamedDecl *ND : Result) 4241 if (!ND->isFromASTFile()) 4242 GetDeclRef(ND); 4243 } 4244 4245 return 0; 4246 } 4247 4248 if (DC->getPrimaryContext() != DC) 4249 return 0; 4250 4251 // Skip contexts which don't support name lookup. 4252 if (!DC->isLookupContext()) 4253 return 0; 4254 4255 // If not in C++, we perform name lookup for the translation unit via the 4256 // IdentifierInfo chains, don't bother to build a visible-declarations table. 4257 if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus) 4258 return 0; 4259 4260 // Serialize the contents of the mapping used for lookup. Note that, 4261 // although we have two very different code paths, the serialized 4262 // representation is the same for both cases: a declaration name, 4263 // followed by a size, followed by references to the visible 4264 // declarations that have that name. 4265 uint64_t Offset = Stream.GetCurrentBitNo(); 4266 StoredDeclsMap *Map = DC->buildLookup(); 4267 if (!Map || Map->empty()) 4268 return 0; 4269 4270 // Create the on-disk hash table in a buffer. 4271 SmallString<4096> LookupTable; 4272 GenerateNameLookupTable(DC, LookupTable); 4273 4274 // Write the lookup table 4275 RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE}; 4276 Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record, 4277 LookupTable); 4278 ++NumVisibleDeclContexts; 4279 return Offset; 4280 } 4281 4282 /// Write an UPDATE_VISIBLE block for the given context. 4283 /// 4284 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing 4285 /// DeclContext in a dependent AST file. As such, they only exist for the TU 4286 /// (in C++), for namespaces, and for classes with forward-declared unscoped 4287 /// enumeration members (in C++11). 4288 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) { 4289 StoredDeclsMap *Map = DC->getLookupPtr(); 4290 if (!Map || Map->empty()) 4291 return; 4292 4293 // Create the on-disk hash table in a buffer. 4294 SmallString<4096> LookupTable; 4295 GenerateNameLookupTable(DC, LookupTable); 4296 4297 // If we're updating a namespace, select a key declaration as the key for the 4298 // update record; those are the only ones that will be checked on reload. 4299 if (isa<NamespaceDecl>(DC)) 4300 DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC))); 4301 4302 // Write the lookup table 4303 RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))}; 4304 Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable); 4305 } 4306 4307 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions. 4308 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) { 4309 RecordData::value_type Record[] = {Opts.getInt()}; 4310 Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record); 4311 } 4312 4313 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions. 4314 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) { 4315 if (!SemaRef.Context.getLangOpts().OpenCL) 4316 return; 4317 4318 const OpenCLOptions &Opts = SemaRef.getOpenCLOptions(); 4319 RecordData Record; 4320 for (const auto &I:Opts.OptMap) { 4321 AddString(I.getKey(), Record); 4322 auto V = I.getValue(); 4323 Record.push_back(V.Supported ? 1 : 0); 4324 Record.push_back(V.Enabled ? 1 : 0); 4325 Record.push_back(V.Avail); 4326 Record.push_back(V.Core); 4327 } 4328 Stream.EmitRecord(OPENCL_EXTENSIONS, Record); 4329 } 4330 4331 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) { 4332 if (!SemaRef.Context.getLangOpts().OpenCL) 4333 return; 4334 4335 // Sort the elements of the map OpenCLTypeExtMap by TypeIDs, 4336 // without copying them. 4337 const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap = 4338 SemaRef.OpenCLTypeExtMap; 4339 using ElementTy = std::pair<TypeID, const std::set<std::string> *>; 4340 llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap; 4341 StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size()); 4342 4343 for (const auto &I : OpenCLTypeExtMap) 4344 StableOpenCLTypeExtMap.emplace_back( 4345 getTypeID(I.first->getCanonicalTypeInternal()), &I.second); 4346 4347 auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool { 4348 return E1.first < E2.first; 4349 }; 4350 llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID); 4351 4352 RecordData Record; 4353 for (const ElementTy &E : StableOpenCLTypeExtMap) { 4354 Record.push_back(E.first); // TypeID 4355 const std::set<std::string> *ExtSet = E.second; 4356 Record.push_back(static_cast<unsigned>(ExtSet->size())); 4357 for (const std::string &Ext : *ExtSet) 4358 AddString(Ext, Record); 4359 } 4360 4361 Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record); 4362 } 4363 4364 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) { 4365 if (!SemaRef.Context.getLangOpts().OpenCL) 4366 return; 4367 4368 // Sort the elements of the map OpenCLDeclExtMap by DeclIDs, 4369 // without copying them. 4370 const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap = 4371 SemaRef.OpenCLDeclExtMap; 4372 using ElementTy = std::pair<DeclID, const std::set<std::string> *>; 4373 llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap; 4374 StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size()); 4375 4376 for (const auto &I : OpenCLDeclExtMap) 4377 StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second); 4378 4379 auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool { 4380 return E1.first < E2.first; 4381 }; 4382 llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID); 4383 4384 RecordData Record; 4385 for (const ElementTy &E : StableOpenCLDeclExtMap) { 4386 Record.push_back(E.first); // DeclID 4387 const std::set<std::string> *ExtSet = E.second; 4388 Record.push_back(static_cast<unsigned>(ExtSet->size())); 4389 for (const std::string &Ext : *ExtSet) 4390 AddString(Ext, Record); 4391 } 4392 4393 Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record); 4394 } 4395 4396 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) { 4397 if (SemaRef.ForceCUDAHostDeviceDepth > 0) { 4398 RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth}; 4399 Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record); 4400 } 4401 } 4402 4403 void ASTWriter::WriteObjCCategories() { 4404 SmallVector<ObjCCategoriesInfo, 2> CategoriesMap; 4405 RecordData Categories; 4406 4407 for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) { 4408 unsigned Size = 0; 4409 unsigned StartIndex = Categories.size(); 4410 4411 ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I]; 4412 4413 // Allocate space for the size. 4414 Categories.push_back(0); 4415 4416 // Add the categories. 4417 for (ObjCInterfaceDecl::known_categories_iterator 4418 Cat = Class->known_categories_begin(), 4419 CatEnd = Class->known_categories_end(); 4420 Cat != CatEnd; ++Cat, ++Size) { 4421 assert(getDeclID(*Cat) != 0 && "Bogus category"); 4422 AddDeclRef(*Cat, Categories); 4423 } 4424 4425 // Update the size. 4426 Categories[StartIndex] = Size; 4427 4428 // Record this interface -> category map. 4429 ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex }; 4430 CategoriesMap.push_back(CatInfo); 4431 } 4432 4433 // Sort the categories map by the definition ID, since the reader will be 4434 // performing binary searches on this information. 4435 llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end()); 4436 4437 // Emit the categories map. 4438 using namespace llvm; 4439 4440 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 4441 Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP)); 4442 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries 4443 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 4444 unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev)); 4445 4446 RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()}; 4447 Stream.EmitRecordWithBlob(AbbrevID, Record, 4448 reinterpret_cast<char *>(CategoriesMap.data()), 4449 CategoriesMap.size() * sizeof(ObjCCategoriesInfo)); 4450 4451 // Emit the category lists. 4452 Stream.EmitRecord(OBJC_CATEGORIES, Categories); 4453 } 4454 4455 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) { 4456 Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap; 4457 4458 if (LPTMap.empty()) 4459 return; 4460 4461 RecordData Record; 4462 for (auto &LPTMapEntry : LPTMap) { 4463 const FunctionDecl *FD = LPTMapEntry.first; 4464 LateParsedTemplate &LPT = *LPTMapEntry.second; 4465 AddDeclRef(FD, Record); 4466 AddDeclRef(LPT.D, Record); 4467 Record.push_back(LPT.Toks.size()); 4468 4469 for (const auto &Tok : LPT.Toks) { 4470 AddToken(Tok, Record); 4471 } 4472 } 4473 Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record); 4474 } 4475 4476 /// Write the state of 'pragma clang optimize' at the end of the module. 4477 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) { 4478 RecordData Record; 4479 SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation(); 4480 AddSourceLocation(PragmaLoc, Record); 4481 Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record); 4482 } 4483 4484 /// Write the state of 'pragma ms_struct' at the end of the module. 4485 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) { 4486 RecordData Record; 4487 Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF); 4488 Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record); 4489 } 4490 4491 /// Write the state of 'pragma pointers_to_members' at the end of the 4492 //module. 4493 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) { 4494 RecordData Record; 4495 Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod); 4496 AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record); 4497 Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record); 4498 } 4499 4500 /// Write the state of 'pragma pack' at the end of the module. 4501 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) { 4502 // Don't serialize pragma pack state for modules, since it should only take 4503 // effect on a per-submodule basis. 4504 if (WritingModule) 4505 return; 4506 4507 RecordData Record; 4508 Record.push_back(SemaRef.PackStack.CurrentValue); 4509 AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record); 4510 Record.push_back(SemaRef.PackStack.Stack.size()); 4511 for (const auto &StackEntry : SemaRef.PackStack.Stack) { 4512 Record.push_back(StackEntry.Value); 4513 AddSourceLocation(StackEntry.PragmaLocation, Record); 4514 AddSourceLocation(StackEntry.PragmaPushLocation, Record); 4515 AddString(StackEntry.StackSlotLabel, Record); 4516 } 4517 Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record); 4518 } 4519 4520 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef, 4521 ModuleFileExtensionWriter &Writer) { 4522 // Enter the extension block. 4523 Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4); 4524 4525 // Emit the metadata record abbreviation. 4526 auto Abv = std::make_shared<llvm::BitCodeAbbrev>(); 4527 Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA)); 4528 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4529 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4530 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4531 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4532 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4533 unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv)); 4534 4535 // Emit the metadata record. 4536 RecordData Record; 4537 auto Metadata = Writer.getExtension()->getExtensionMetadata(); 4538 Record.push_back(EXTENSION_METADATA); 4539 Record.push_back(Metadata.MajorVersion); 4540 Record.push_back(Metadata.MinorVersion); 4541 Record.push_back(Metadata.BlockName.size()); 4542 Record.push_back(Metadata.UserInfo.size()); 4543 SmallString<64> Buffer; 4544 Buffer += Metadata.BlockName; 4545 Buffer += Metadata.UserInfo; 4546 Stream.EmitRecordWithBlob(Abbrev, Record, Buffer); 4547 4548 // Emit the contents of the extension block. 4549 Writer.writeExtensionContents(SemaRef, Stream); 4550 4551 // Exit the extension block. 4552 Stream.ExitBlock(); 4553 } 4554 4555 //===----------------------------------------------------------------------===// 4556 // General Serialization Routines 4557 //===----------------------------------------------------------------------===// 4558 4559 void ASTRecordWriter::AddAttr(const Attr *A) { 4560 auto &Record = *this; 4561 if (!A) 4562 return Record.push_back(0); 4563 Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs 4564 4565 Record.AddIdentifierRef(A->getAttrName()); 4566 Record.AddIdentifierRef(A->getScopeName()); 4567 Record.AddSourceRange(A->getRange()); 4568 Record.AddSourceLocation(A->getScopeLoc()); 4569 Record.push_back(A->getParsedKind()); 4570 Record.push_back(A->getSyntax()); 4571 Record.push_back(A->getAttributeSpellingListIndexRaw()); 4572 4573 #include "clang/Serialization/AttrPCHWrite.inc" 4574 } 4575 4576 /// Emit the list of attributes to the specified record. 4577 void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) { 4578 push_back(Attrs.size()); 4579 for (const auto *A : Attrs) 4580 AddAttr(A); 4581 } 4582 4583 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) { 4584 AddSourceLocation(Tok.getLocation(), Record); 4585 Record.push_back(Tok.getLength()); 4586 4587 // FIXME: When reading literal tokens, reconstruct the literal pointer 4588 // if it is needed. 4589 AddIdentifierRef(Tok.getIdentifierInfo(), Record); 4590 // FIXME: Should translate token kind to a stable encoding. 4591 Record.push_back(Tok.getKind()); 4592 // FIXME: Should translate token flags to a stable encoding. 4593 Record.push_back(Tok.getFlags()); 4594 } 4595 4596 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) { 4597 Record.push_back(Str.size()); 4598 Record.insert(Record.end(), Str.begin(), Str.end()); 4599 } 4600 4601 bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) { 4602 assert(Context && "should have context when outputting path"); 4603 4604 bool Changed = 4605 cleanPathForOutput(Context->getSourceManager().getFileManager(), Path); 4606 4607 // Remove a prefix to make the path relative, if relevant. 4608 const char *PathBegin = Path.data(); 4609 const char *PathPtr = 4610 adjustFilenameForRelocatableAST(PathBegin, BaseDirectory); 4611 if (PathPtr != PathBegin) { 4612 Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin)); 4613 Changed = true; 4614 } 4615 4616 return Changed; 4617 } 4618 4619 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) { 4620 SmallString<128> FilePath(Path); 4621 PreparePathForOutput(FilePath); 4622 AddString(FilePath, Record); 4623 } 4624 4625 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record, 4626 StringRef Path) { 4627 SmallString<128> FilePath(Path); 4628 PreparePathForOutput(FilePath); 4629 Stream.EmitRecordWithBlob(Abbrev, Record, FilePath); 4630 } 4631 4632 void ASTWriter::AddVersionTuple(const VersionTuple &Version, 4633 RecordDataImpl &Record) { 4634 Record.push_back(Version.getMajor()); 4635 if (Optional<unsigned> Minor = Version.getMinor()) 4636 Record.push_back(*Minor + 1); 4637 else 4638 Record.push_back(0); 4639 if (Optional<unsigned> Subminor = Version.getSubminor()) 4640 Record.push_back(*Subminor + 1); 4641 else 4642 Record.push_back(0); 4643 } 4644 4645 /// Note that the identifier II occurs at the given offset 4646 /// within the identifier table. 4647 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) { 4648 IdentID ID = IdentifierIDs[II]; 4649 // Only store offsets new to this AST file. Other identifier names are looked 4650 // up earlier in the chain and thus don't need an offset. 4651 if (ID >= FirstIdentID) 4652 IdentifierOffsets[ID - FirstIdentID] = Offset; 4653 } 4654 4655 /// Note that the selector Sel occurs at the given offset 4656 /// within the method pool/selector table. 4657 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) { 4658 unsigned ID = SelectorIDs[Sel]; 4659 assert(ID && "Unknown selector"); 4660 // Don't record offsets for selectors that are also available in a different 4661 // file. 4662 if (ID < FirstSelectorID) 4663 return; 4664 SelectorOffsets[ID - FirstSelectorID] = Offset; 4665 } 4666 4667 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream, 4668 SmallVectorImpl<char> &Buffer, 4669 InMemoryModuleCache &ModuleCache, 4670 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions, 4671 bool IncludeTimestamps) 4672 : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache), 4673 IncludeTimestamps(IncludeTimestamps) { 4674 for (const auto &Ext : Extensions) { 4675 if (auto Writer = Ext->createExtensionWriter(*this)) 4676 ModuleFileExtensionWriters.push_back(std::move(Writer)); 4677 } 4678 } 4679 4680 ASTWriter::~ASTWriter() { 4681 llvm::DeleteContainerSeconds(FileDeclIDs); 4682 } 4683 4684 const LangOptions &ASTWriter::getLangOpts() const { 4685 assert(WritingAST && "can't determine lang opts when not writing AST"); 4686 return Context->getLangOpts(); 4687 } 4688 4689 time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const { 4690 return IncludeTimestamps ? E->getModificationTime() : 0; 4691 } 4692 4693 ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef, 4694 const std::string &OutputFile, 4695 Module *WritingModule, StringRef isysroot, 4696 bool hasErrors, 4697 bool ShouldCacheASTInMemory) { 4698 WritingAST = true; 4699 4700 ASTHasCompilerErrors = hasErrors; 4701 4702 // Emit the file header. 4703 Stream.Emit((unsigned)'C', 8); 4704 Stream.Emit((unsigned)'P', 8); 4705 Stream.Emit((unsigned)'C', 8); 4706 Stream.Emit((unsigned)'H', 8); 4707 4708 WriteBlockInfoBlock(); 4709 4710 Context = &SemaRef.Context; 4711 PP = &SemaRef.PP; 4712 this->WritingModule = WritingModule; 4713 ASTFileSignature Signature = 4714 WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule); 4715 Context = nullptr; 4716 PP = nullptr; 4717 this->WritingModule = nullptr; 4718 this->BaseDirectory.clear(); 4719 4720 WritingAST = false; 4721 if (ShouldCacheASTInMemory) { 4722 // Construct MemoryBuffer and update buffer manager. 4723 ModuleCache.addBuiltPCM(OutputFile, 4724 llvm::MemoryBuffer::getMemBufferCopy( 4725 StringRef(Buffer.begin(), Buffer.size()))); 4726 } 4727 return Signature; 4728 } 4729 4730 template<typename Vector> 4731 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec, 4732 ASTWriter::RecordData &Record) { 4733 for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end(); 4734 I != E; ++I) { 4735 Writer.AddDeclRef(*I, Record); 4736 } 4737 } 4738 4739 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot, 4740 const std::string &OutputFile, 4741 Module *WritingModule) { 4742 using namespace llvm; 4743 4744 bool isModule = WritingModule != nullptr; 4745 4746 // Make sure that the AST reader knows to finalize itself. 4747 if (Chain) 4748 Chain->finalizeForWriting(); 4749 4750 ASTContext &Context = SemaRef.Context; 4751 Preprocessor &PP = SemaRef.PP; 4752 4753 // Set up predefined declaration IDs. 4754 auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) { 4755 if (D) { 4756 assert(D->isCanonicalDecl() && "predefined decl is not canonical"); 4757 DeclIDs[D] = ID; 4758 } 4759 }; 4760 RegisterPredefDecl(Context.getTranslationUnitDecl(), 4761 PREDEF_DECL_TRANSLATION_UNIT_ID); 4762 RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID); 4763 RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID); 4764 RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID); 4765 RegisterPredefDecl(Context.ObjCProtocolClassDecl, 4766 PREDEF_DECL_OBJC_PROTOCOL_ID); 4767 RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID); 4768 RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID); 4769 RegisterPredefDecl(Context.ObjCInstanceTypeDecl, 4770 PREDEF_DECL_OBJC_INSTANCETYPE_ID); 4771 RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID); 4772 RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG); 4773 RegisterPredefDecl(Context.BuiltinMSVaListDecl, 4774 PREDEF_DECL_BUILTIN_MS_VA_LIST_ID); 4775 RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID); 4776 RegisterPredefDecl(Context.MakeIntegerSeqDecl, 4777 PREDEF_DECL_MAKE_INTEGER_SEQ_ID); 4778 RegisterPredefDecl(Context.CFConstantStringTypeDecl, 4779 PREDEF_DECL_CF_CONSTANT_STRING_ID); 4780 RegisterPredefDecl(Context.CFConstantStringTagDecl, 4781 PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID); 4782 RegisterPredefDecl(Context.TypePackElementDecl, 4783 PREDEF_DECL_TYPE_PACK_ELEMENT_ID); 4784 4785 // Build a record containing all of the tentative definitions in this file, in 4786 // TentativeDefinitions order. Generally, this record will be empty for 4787 // headers. 4788 RecordData TentativeDefinitions; 4789 AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions); 4790 4791 // Build a record containing all of the file scoped decls in this file. 4792 RecordData UnusedFileScopedDecls; 4793 if (!isModule) 4794 AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls, 4795 UnusedFileScopedDecls); 4796 4797 // Build a record containing all of the delegating constructors we still need 4798 // to resolve. 4799 RecordData DelegatingCtorDecls; 4800 if (!isModule) 4801 AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls); 4802 4803 // Write the set of weak, undeclared identifiers. We always write the 4804 // entire table, since later PCH files in a PCH chain are only interested in 4805 // the results at the end of the chain. 4806 RecordData WeakUndeclaredIdentifiers; 4807 for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) { 4808 IdentifierInfo *II = WeakUndeclaredIdentifier.first; 4809 WeakInfo &WI = WeakUndeclaredIdentifier.second; 4810 AddIdentifierRef(II, WeakUndeclaredIdentifiers); 4811 AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers); 4812 AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers); 4813 WeakUndeclaredIdentifiers.push_back(WI.getUsed()); 4814 } 4815 4816 // Build a record containing all of the ext_vector declarations. 4817 RecordData ExtVectorDecls; 4818 AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls); 4819 4820 // Build a record containing all of the VTable uses information. 4821 RecordData VTableUses; 4822 if (!SemaRef.VTableUses.empty()) { 4823 for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) { 4824 AddDeclRef(SemaRef.VTableUses[I].first, VTableUses); 4825 AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses); 4826 VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]); 4827 } 4828 } 4829 4830 // Build a record containing all of the UnusedLocalTypedefNameCandidates. 4831 RecordData UnusedLocalTypedefNameCandidates; 4832 for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates) 4833 AddDeclRef(TD, UnusedLocalTypedefNameCandidates); 4834 4835 // Build a record containing all of pending implicit instantiations. 4836 RecordData PendingInstantiations; 4837 for (const auto &I : SemaRef.PendingInstantiations) { 4838 AddDeclRef(I.first, PendingInstantiations); 4839 AddSourceLocation(I.second, PendingInstantiations); 4840 } 4841 assert(SemaRef.PendingLocalImplicitInstantiations.empty() && 4842 "There are local ones at end of translation unit!"); 4843 4844 // Build a record containing some declaration references. 4845 RecordData SemaDeclRefs; 4846 if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) { 4847 AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs); 4848 AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs); 4849 AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs); 4850 } 4851 4852 RecordData CUDASpecialDeclRefs; 4853 if (Context.getcudaConfigureCallDecl()) { 4854 AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs); 4855 } 4856 4857 // Build a record containing all of the known namespaces. 4858 RecordData KnownNamespaces; 4859 for (const auto &I : SemaRef.KnownNamespaces) { 4860 if (!I.second) 4861 AddDeclRef(I.first, KnownNamespaces); 4862 } 4863 4864 // Build a record of all used, undefined objects that require definitions. 4865 RecordData UndefinedButUsed; 4866 4867 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 4868 SemaRef.getUndefinedButUsed(Undefined); 4869 for (const auto &I : Undefined) { 4870 AddDeclRef(I.first, UndefinedButUsed); 4871 AddSourceLocation(I.second, UndefinedButUsed); 4872 } 4873 4874 // Build a record containing all delete-expressions that we would like to 4875 // analyze later in AST. 4876 RecordData DeleteExprsToAnalyze; 4877 4878 if (!isModule) { 4879 for (const auto &DeleteExprsInfo : 4880 SemaRef.getMismatchingDeleteExpressions()) { 4881 AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze); 4882 DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size()); 4883 for (const auto &DeleteLoc : DeleteExprsInfo.second) { 4884 AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze); 4885 DeleteExprsToAnalyze.push_back(DeleteLoc.second); 4886 } 4887 } 4888 } 4889 4890 // Write the control block 4891 WriteControlBlock(PP, Context, isysroot, OutputFile); 4892 4893 // Write the remaining AST contents. 4894 Stream.EnterSubblock(AST_BLOCK_ID, 5); 4895 4896 // This is so that older clang versions, before the introduction 4897 // of the control block, can read and reject the newer PCH format. 4898 { 4899 RecordData Record = {VERSION_MAJOR}; 4900 Stream.EmitRecord(METADATA_OLD_FORMAT, Record); 4901 } 4902 4903 // Create a lexical update block containing all of the declarations in the 4904 // translation unit that do not come from other AST files. 4905 const TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 4906 SmallVector<uint32_t, 128> NewGlobalKindDeclPairs; 4907 for (const auto *D : TU->noload_decls()) { 4908 if (!D->isFromASTFile()) { 4909 NewGlobalKindDeclPairs.push_back(D->getKind()); 4910 NewGlobalKindDeclPairs.push_back(GetDeclRef(D)); 4911 } 4912 } 4913 4914 auto Abv = std::make_shared<BitCodeAbbrev>(); 4915 Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL)); 4916 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4917 unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4918 { 4919 RecordData::value_type Record[] = {TU_UPDATE_LEXICAL}; 4920 Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record, 4921 bytes(NewGlobalKindDeclPairs)); 4922 } 4923 4924 // And a visible updates block for the translation unit. 4925 Abv = std::make_shared<BitCodeAbbrev>(); 4926 Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE)); 4927 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6)); 4928 Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob)); 4929 UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv)); 4930 WriteDeclContextVisibleUpdate(TU); 4931 4932 // If we have any extern "C" names, write out a visible update for them. 4933 if (Context.ExternCContext) 4934 WriteDeclContextVisibleUpdate(Context.ExternCContext); 4935 4936 // If the translation unit has an anonymous namespace, and we don't already 4937 // have an update block for it, write it as an update block. 4938 // FIXME: Why do we not do this if there's already an update block? 4939 if (NamespaceDecl *NS = TU->getAnonymousNamespace()) { 4940 ASTWriter::UpdateRecord &Record = DeclUpdates[TU]; 4941 if (Record.empty()) 4942 Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS)); 4943 } 4944 4945 // Add update records for all mangling numbers and static local numbers. 4946 // These aren't really update records, but this is a convenient way of 4947 // tagging this rare extra data onto the declarations. 4948 for (const auto &Number : Context.MangleNumbers) 4949 if (!Number.first->isFromASTFile()) 4950 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER, 4951 Number.second)); 4952 for (const auto &Number : Context.StaticLocalNumbers) 4953 if (!Number.first->isFromASTFile()) 4954 DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER, 4955 Number.second)); 4956 4957 // Make sure visible decls, added to DeclContexts previously loaded from 4958 // an AST file, are registered for serialization. Likewise for template 4959 // specializations added to imported templates. 4960 for (const auto *I : DeclsToEmitEvenIfUnreferenced) { 4961 GetDeclRef(I); 4962 } 4963 4964 // Make sure all decls associated with an identifier are registered for 4965 // serialization, if we're storing decls with identifiers. 4966 if (!WritingModule || !getLangOpts().CPlusPlus) { 4967 llvm::SmallVector<const IdentifierInfo*, 256> IIs; 4968 for (const auto &ID : PP.getIdentifierTable()) { 4969 const IdentifierInfo *II = ID.second; 4970 if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) 4971 IIs.push_back(II); 4972 } 4973 // Sort the identifiers to visit based on their name. 4974 llvm::sort(IIs, llvm::deref<std::less<>>()); 4975 for (const IdentifierInfo *II : IIs) { 4976 for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II), 4977 DEnd = SemaRef.IdResolver.end(); 4978 D != DEnd; ++D) { 4979 GetDeclRef(*D); 4980 } 4981 } 4982 } 4983 4984 // For method pool in the module, if it contains an entry for a selector, 4985 // the entry should be complete, containing everything introduced by that 4986 // module and all modules it imports. It's possible that the entry is out of 4987 // date, so we need to pull in the new content here. 4988 4989 // It's possible that updateOutOfDateSelector can update SelectorIDs. To be 4990 // safe, we copy all selectors out. 4991 llvm::SmallVector<Selector, 256> AllSelectors; 4992 for (auto &SelectorAndID : SelectorIDs) 4993 AllSelectors.push_back(SelectorAndID.first); 4994 for (auto &Selector : AllSelectors) 4995 SemaRef.updateOutOfDateSelector(Selector); 4996 4997 // Form the record of special types. 4998 RecordData SpecialTypes; 4999 AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes); 5000 AddTypeRef(Context.getFILEType(), SpecialTypes); 5001 AddTypeRef(Context.getjmp_bufType(), SpecialTypes); 5002 AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes); 5003 AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes); 5004 AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes); 5005 AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes); 5006 AddTypeRef(Context.getucontext_tType(), SpecialTypes); 5007 5008 if (Chain) { 5009 // Write the mapping information describing our module dependencies and how 5010 // each of those modules were mapped into our own offset/ID space, so that 5011 // the reader can build the appropriate mapping to its own offset/ID space. 5012 // The map consists solely of a blob with the following format: 5013 // *(module-kind:i8 5014 // module-name-len:i16 module-name:len*i8 5015 // source-location-offset:i32 5016 // identifier-id:i32 5017 // preprocessed-entity-id:i32 5018 // macro-definition-id:i32 5019 // submodule-id:i32 5020 // selector-id:i32 5021 // declaration-id:i32 5022 // c++-base-specifiers-id:i32 5023 // type-id:i32) 5024 // 5025 // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or 5026 // MK_ExplicitModule, then the module-name is the module name. Otherwise, 5027 // it is the module file name. 5028 auto Abbrev = std::make_shared<BitCodeAbbrev>(); 5029 Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP)); 5030 Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); 5031 unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev)); 5032 SmallString<2048> Buffer; 5033 { 5034 llvm::raw_svector_ostream Out(Buffer); 5035 for (ModuleFile &M : Chain->ModuleMgr) { 5036 using namespace llvm::support; 5037 5038 endian::Writer LE(Out, little); 5039 LE.write<uint8_t>(static_cast<uint8_t>(M.Kind)); 5040 StringRef Name = 5041 M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule 5042 ? M.ModuleName 5043 : M.FileName; 5044 LE.write<uint16_t>(Name.size()); 5045 Out.write(Name.data(), Name.size()); 5046 5047 // Note: if a base ID was uint max, it would not be possible to load 5048 // another module after it or have more than one entity inside it. 5049 uint32_t None = std::numeric_limits<uint32_t>::max(); 5050 5051 auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) { 5052 assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high"); 5053 if (ShouldWrite) 5054 LE.write<uint32_t>(BaseID); 5055 else 5056 LE.write<uint32_t>(None); 5057 }; 5058 5059 // These values should be unique within a chain, since they will be read 5060 // as keys into ContinuousRangeMaps. 5061 writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries); 5062 writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers); 5063 writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros); 5064 writeBaseIDOrNone(M.BasePreprocessedEntityID, 5065 M.NumPreprocessedEntities); 5066 writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules); 5067 writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors); 5068 writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls); 5069 writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes); 5070 } 5071 } 5072 RecordData::value_type Record[] = {MODULE_OFFSET_MAP}; 5073 Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record, 5074 Buffer.data(), Buffer.size()); 5075 } 5076 5077 RecordData DeclUpdatesOffsetsRecord; 5078 5079 // Keep writing types, declarations, and declaration update records 5080 // until we've emitted all of them. 5081 Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5); 5082 WriteTypeAbbrevs(); 5083 WriteDeclAbbrevs(); 5084 do { 5085 WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord); 5086 while (!DeclTypesToEmit.empty()) { 5087 DeclOrType DOT = DeclTypesToEmit.front(); 5088 DeclTypesToEmit.pop(); 5089 if (DOT.isType()) 5090 WriteType(DOT.getType()); 5091 else 5092 WriteDecl(Context, DOT.getDecl()); 5093 } 5094 } while (!DeclUpdates.empty()); 5095 Stream.ExitBlock(); 5096 5097 DoneWritingDeclsAndTypes = true; 5098 5099 // These things can only be done once we've written out decls and types. 5100 WriteTypeDeclOffsets(); 5101 if (!DeclUpdatesOffsetsRecord.empty()) 5102 Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord); 5103 WriteFileDeclIDsMap(); 5104 WriteSourceManagerBlock(Context.getSourceManager(), PP); 5105 WriteComments(); 5106 WritePreprocessor(PP, isModule); 5107 WriteHeaderSearch(PP.getHeaderSearchInfo()); 5108 WriteSelectors(SemaRef); 5109 WriteReferencedSelectorsPool(SemaRef); 5110 WriteLateParsedTemplates(SemaRef); 5111 WriteIdentifierTable(PP, SemaRef.IdResolver, isModule); 5112 WriteFPPragmaOptions(SemaRef.getFPOptions()); 5113 WriteOpenCLExtensions(SemaRef); 5114 WriteOpenCLExtensionTypes(SemaRef); 5115 WriteCUDAPragmas(SemaRef); 5116 5117 // If we're emitting a module, write out the submodule information. 5118 if (WritingModule) 5119 WriteSubmodules(WritingModule); 5120 5121 // We need to have information about submodules to correctly deserialize 5122 // decls from OpenCLExtensionDecls block 5123 WriteOpenCLExtensionDecls(SemaRef); 5124 5125 Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes); 5126 5127 // Write the record containing external, unnamed definitions. 5128 if (!EagerlyDeserializedDecls.empty()) 5129 Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls); 5130 5131 if (!ModularCodegenDecls.empty()) 5132 Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls); 5133 5134 // Write the record containing tentative definitions. 5135 if (!TentativeDefinitions.empty()) 5136 Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions); 5137 5138 // Write the record containing unused file scoped decls. 5139 if (!UnusedFileScopedDecls.empty()) 5140 Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls); 5141 5142 // Write the record containing weak undeclared identifiers. 5143 if (!WeakUndeclaredIdentifiers.empty()) 5144 Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS, 5145 WeakUndeclaredIdentifiers); 5146 5147 // Write the record containing ext_vector type names. 5148 if (!ExtVectorDecls.empty()) 5149 Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls); 5150 5151 // Write the record containing VTable uses information. 5152 if (!VTableUses.empty()) 5153 Stream.EmitRecord(VTABLE_USES, VTableUses); 5154 5155 // Write the record containing potentially unused local typedefs. 5156 if (!UnusedLocalTypedefNameCandidates.empty()) 5157 Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES, 5158 UnusedLocalTypedefNameCandidates); 5159 5160 // Write the record containing pending implicit instantiations. 5161 if (!PendingInstantiations.empty()) 5162 Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations); 5163 5164 // Write the record containing declaration references of Sema. 5165 if (!SemaDeclRefs.empty()) 5166 Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs); 5167 5168 // Write the record containing CUDA-specific declaration references. 5169 if (!CUDASpecialDeclRefs.empty()) 5170 Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs); 5171 5172 // Write the delegating constructors. 5173 if (!DelegatingCtorDecls.empty()) 5174 Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls); 5175 5176 // Write the known namespaces. 5177 if (!KnownNamespaces.empty()) 5178 Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces); 5179 5180 // Write the undefined internal functions and variables, and inline functions. 5181 if (!UndefinedButUsed.empty()) 5182 Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed); 5183 5184 if (!DeleteExprsToAnalyze.empty()) 5185 Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze); 5186 5187 // Write the visible updates to DeclContexts. 5188 for (auto *DC : UpdatedDeclContexts) 5189 WriteDeclContextVisibleUpdate(DC); 5190 5191 if (!WritingModule) { 5192 // Write the submodules that were imported, if any. 5193 struct ModuleInfo { 5194 uint64_t ID; 5195 Module *M; 5196 ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {} 5197 }; 5198 llvm::SmallVector<ModuleInfo, 64> Imports; 5199 for (const auto *I : Context.local_imports()) { 5200 assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end()); 5201 Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()], 5202 I->getImportedModule())); 5203 } 5204 5205 if (!Imports.empty()) { 5206 auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) { 5207 return A.ID < B.ID; 5208 }; 5209 auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) { 5210 return A.ID == B.ID; 5211 }; 5212 5213 // Sort and deduplicate module IDs. 5214 llvm::sort(Imports, Cmp); 5215 Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq), 5216 Imports.end()); 5217 5218 RecordData ImportedModules; 5219 for (const auto &Import : Imports) { 5220 ImportedModules.push_back(Import.ID); 5221 // FIXME: If the module has macros imported then later has declarations 5222 // imported, this location won't be the right one as a location for the 5223 // declaration imports. 5224 AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules); 5225 } 5226 5227 Stream.EmitRecord(IMPORTED_MODULES, ImportedModules); 5228 } 5229 } 5230 5231 WriteObjCCategories(); 5232 if(!WritingModule) { 5233 WriteOptimizePragmaOptions(SemaRef); 5234 WriteMSStructPragmaOptions(SemaRef); 5235 WriteMSPointersToMembersPragmaOptions(SemaRef); 5236 } 5237 WritePackPragmaOptions(SemaRef); 5238 5239 // Some simple statistics 5240 RecordData::value_type Record[] = { 5241 NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts}; 5242 Stream.EmitRecord(STATISTICS, Record); 5243 Stream.ExitBlock(); 5244 5245 // Write the module file extension blocks. 5246 for (const auto &ExtWriter : ModuleFileExtensionWriters) 5247 WriteModuleFileExtension(SemaRef, *ExtWriter); 5248 5249 return writeUnhashedControlBlock(PP, Context); 5250 } 5251 5252 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) { 5253 if (DeclUpdates.empty()) 5254 return; 5255 5256 DeclUpdateMap LocalUpdates; 5257 LocalUpdates.swap(DeclUpdates); 5258 5259 for (auto &DeclUpdate : LocalUpdates) { 5260 const Decl *D = DeclUpdate.first; 5261 5262 bool HasUpdatedBody = false; 5263 RecordData RecordData; 5264 ASTRecordWriter Record(*this, RecordData); 5265 for (auto &Update : DeclUpdate.second) { 5266 DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind(); 5267 5268 // An updated body is emitted last, so that the reader doesn't need 5269 // to skip over the lazy body to reach statements for other records. 5270 if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION) 5271 HasUpdatedBody = true; 5272 else 5273 Record.push_back(Kind); 5274 5275 switch (Kind) { 5276 case UPD_CXX_ADDED_IMPLICIT_MEMBER: 5277 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION: 5278 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: 5279 assert(Update.getDecl() && "no decl to add?"); 5280 Record.push_back(GetDeclRef(Update.getDecl())); 5281 break; 5282 5283 case UPD_CXX_ADDED_FUNCTION_DEFINITION: 5284 break; 5285 5286 case UPD_CXX_POINT_OF_INSTANTIATION: 5287 // FIXME: Do we need to also save the template specialization kind here? 5288 Record.AddSourceLocation(Update.getLoc()); 5289 break; 5290 5291 case UPD_CXX_ADDED_VAR_DEFINITION: { 5292 const VarDecl *VD = cast<VarDecl>(D); 5293 Record.push_back(VD->isInline()); 5294 Record.push_back(VD->isInlineSpecified()); 5295 if (VD->getInit()) { 5296 Record.push_back(!VD->isInitKnownICE() ? 1 5297 : (VD->isInitICE() ? 3 : 2)); 5298 Record.AddStmt(const_cast<Expr*>(VD->getInit())); 5299 } else { 5300 Record.push_back(0); 5301 } 5302 break; 5303 } 5304 5305 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: 5306 Record.AddStmt(const_cast<Expr *>( 5307 cast<ParmVarDecl>(Update.getDecl())->getDefaultArg())); 5308 break; 5309 5310 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: 5311 Record.AddStmt( 5312 cast<FieldDecl>(Update.getDecl())->getInClassInitializer()); 5313 break; 5314 5315 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: { 5316 auto *RD = cast<CXXRecordDecl>(D); 5317 UpdatedDeclContexts.insert(RD->getPrimaryContext()); 5318 Record.push_back(RD->isParamDestroyedInCallee()); 5319 Record.push_back(RD->getArgPassingRestrictions()); 5320 Record.AddCXXDefinitionData(RD); 5321 Record.AddOffset(WriteDeclContextLexicalBlock( 5322 *Context, const_cast<CXXRecordDecl *>(RD))); 5323 5324 // This state is sometimes updated by template instantiation, when we 5325 // switch from the specialization referring to the template declaration 5326 // to it referring to the template definition. 5327 if (auto *MSInfo = RD->getMemberSpecializationInfo()) { 5328 Record.push_back(MSInfo->getTemplateSpecializationKind()); 5329 Record.AddSourceLocation(MSInfo->getPointOfInstantiation()); 5330 } else { 5331 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD); 5332 Record.push_back(Spec->getTemplateSpecializationKind()); 5333 Record.AddSourceLocation(Spec->getPointOfInstantiation()); 5334 5335 // The instantiation might have been resolved to a partial 5336 // specialization. If so, record which one. 5337 auto From = Spec->getInstantiatedFrom(); 5338 if (auto PartialSpec = 5339 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) { 5340 Record.push_back(true); 5341 Record.AddDeclRef(PartialSpec); 5342 Record.AddTemplateArgumentList( 5343 &Spec->getTemplateInstantiationArgs()); 5344 } else { 5345 Record.push_back(false); 5346 } 5347 } 5348 Record.push_back(RD->getTagKind()); 5349 Record.AddSourceLocation(RD->getLocation()); 5350 Record.AddSourceLocation(RD->getBeginLoc()); 5351 Record.AddSourceRange(RD->getBraceRange()); 5352 5353 // Instantiation may change attributes; write them all out afresh. 5354 Record.push_back(D->hasAttrs()); 5355 if (D->hasAttrs()) 5356 Record.AddAttributes(D->getAttrs()); 5357 5358 // FIXME: Ensure we don't get here for explicit instantiations. 5359 break; 5360 } 5361 5362 case UPD_CXX_RESOLVED_DTOR_DELETE: 5363 Record.AddDeclRef(Update.getDecl()); 5364 Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg()); 5365 break; 5366 5367 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: 5368 addExceptionSpec( 5369 cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(), 5370 Record); 5371 break; 5372 5373 case UPD_CXX_DEDUCED_RETURN_TYPE: 5374 Record.push_back(GetOrCreateTypeID(Update.getType())); 5375 break; 5376 5377 case UPD_DECL_MARKED_USED: 5378 break; 5379 5380 case UPD_MANGLING_NUMBER: 5381 case UPD_STATIC_LOCAL_NUMBER: 5382 Record.push_back(Update.getNumber()); 5383 break; 5384 5385 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE: 5386 Record.AddSourceRange( 5387 D->getAttr<OMPThreadPrivateDeclAttr>()->getRange()); 5388 break; 5389 5390 case UPD_DECL_MARKED_OPENMP_ALLOCATE: { 5391 auto *A = D->getAttr<OMPAllocateDeclAttr>(); 5392 Record.push_back(A->getAllocatorType()); 5393 Record.AddStmt(A->getAllocator()); 5394 Record.AddSourceRange(A->getRange()); 5395 break; 5396 } 5397 5398 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: 5399 Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType()); 5400 Record.AddSourceRange( 5401 D->getAttr<OMPDeclareTargetDeclAttr>()->getRange()); 5402 break; 5403 5404 case UPD_DECL_EXPORTED: 5405 Record.push_back(getSubmoduleID(Update.getModule())); 5406 break; 5407 5408 case UPD_ADDED_ATTR_TO_RECORD: 5409 Record.AddAttributes(llvm::makeArrayRef(Update.getAttr())); 5410 break; 5411 } 5412 } 5413 5414 if (HasUpdatedBody) { 5415 const auto *Def = cast<FunctionDecl>(D); 5416 Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION); 5417 Record.push_back(Def->isInlined()); 5418 Record.AddSourceLocation(Def->getInnerLocStart()); 5419 Record.AddFunctionDefinition(Def); 5420 } 5421 5422 OffsetsRecord.push_back(GetDeclRef(D)); 5423 OffsetsRecord.push_back(Record.Emit(DECL_UPDATES)); 5424 } 5425 } 5426 5427 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) { 5428 uint32_t Raw = Loc.getRawEncoding(); 5429 Record.push_back((Raw << 1) | (Raw >> 31)); 5430 } 5431 5432 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) { 5433 AddSourceLocation(Range.getBegin(), Record); 5434 AddSourceLocation(Range.getEnd(), Record); 5435 } 5436 5437 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) { 5438 Record->push_back(Value.getBitWidth()); 5439 const uint64_t *Words = Value.getRawData(); 5440 Record->append(Words, Words + Value.getNumWords()); 5441 } 5442 5443 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) { 5444 Record->push_back(Value.isUnsigned()); 5445 AddAPInt(Value); 5446 } 5447 5448 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) { 5449 AddAPInt(Value.bitcastToAPInt()); 5450 } 5451 5452 static void WriteFixedPointSemantics(ASTRecordWriter &Record, 5453 FixedPointSemantics FPSema) { 5454 Record.push_back(FPSema.getWidth()); 5455 Record.push_back(FPSema.getScale()); 5456 Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 | 5457 FPSema.hasUnsignedPadding() << 2); 5458 } 5459 5460 void ASTRecordWriter::AddAPValue(const APValue &Value) { 5461 APValue::ValueKind Kind = Value.getKind(); 5462 push_back(static_cast<uint64_t>(Kind)); 5463 switch (Kind) { 5464 case APValue::None: 5465 case APValue::Indeterminate: 5466 return; 5467 case APValue::Int: 5468 AddAPSInt(Value.getInt()); 5469 return; 5470 case APValue::Float: 5471 push_back(static_cast<uint64_t>( 5472 llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics()))); 5473 AddAPFloat(Value.getFloat()); 5474 return; 5475 case APValue::FixedPoint: { 5476 WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics()); 5477 AddAPSInt(Value.getFixedPoint().getValue()); 5478 return; 5479 } 5480 case APValue::ComplexInt: { 5481 AddAPSInt(Value.getComplexIntReal()); 5482 AddAPSInt(Value.getComplexIntImag()); 5483 return; 5484 } 5485 case APValue::ComplexFloat: { 5486 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum( 5487 Value.getComplexFloatReal().getSemantics()))); 5488 AddAPFloat(Value.getComplexFloatReal()); 5489 push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum( 5490 Value.getComplexFloatImag().getSemantics()))); 5491 AddAPFloat(Value.getComplexFloatImag()); 5492 return; 5493 } 5494 case APValue::LValue: 5495 case APValue::Vector: 5496 case APValue::Array: 5497 case APValue::Struct: 5498 case APValue::Union: 5499 case APValue::MemberPointer: 5500 case APValue::AddrLabelDiff: 5501 // TODO : Handle all these APValue::ValueKind. 5502 return; 5503 } 5504 llvm_unreachable("Invalid APValue::ValueKind"); 5505 } 5506 5507 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) { 5508 Record.push_back(getIdentifierRef(II)); 5509 } 5510 5511 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) { 5512 if (!II) 5513 return 0; 5514 5515 IdentID &ID = IdentifierIDs[II]; 5516 if (ID == 0) 5517 ID = NextIdentID++; 5518 return ID; 5519 } 5520 5521 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) { 5522 // Don't emit builtin macros like __LINE__ to the AST file unless they 5523 // have been redefined by the header (in which case they are not 5524 // isBuiltinMacro). 5525 if (!MI || MI->isBuiltinMacro()) 5526 return 0; 5527 5528 MacroID &ID = MacroIDs[MI]; 5529 if (ID == 0) { 5530 ID = NextMacroID++; 5531 MacroInfoToEmitData Info = { Name, MI, ID }; 5532 MacroInfosToEmit.push_back(Info); 5533 } 5534 return ID; 5535 } 5536 5537 MacroID ASTWriter::getMacroID(MacroInfo *MI) { 5538 if (!MI || MI->isBuiltinMacro()) 5539 return 0; 5540 5541 assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!"); 5542 return MacroIDs[MI]; 5543 } 5544 5545 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) { 5546 return IdentMacroDirectivesOffsetMap.lookup(Name); 5547 } 5548 5549 void ASTRecordWriter::AddSelectorRef(const Selector SelRef) { 5550 Record->push_back(Writer->getSelectorRef(SelRef)); 5551 } 5552 5553 SelectorID ASTWriter::getSelectorRef(Selector Sel) { 5554 if (Sel.getAsOpaquePtr() == nullptr) { 5555 return 0; 5556 } 5557 5558 SelectorID SID = SelectorIDs[Sel]; 5559 if (SID == 0 && Chain) { 5560 // This might trigger a ReadSelector callback, which will set the ID for 5561 // this selector. 5562 Chain->LoadSelector(Sel); 5563 SID = SelectorIDs[Sel]; 5564 } 5565 if (SID == 0) { 5566 SID = NextSelectorID++; 5567 SelectorIDs[Sel] = SID; 5568 } 5569 return SID; 5570 } 5571 5572 void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) { 5573 AddDeclRef(Temp->getDestructor()); 5574 } 5575 5576 void ASTRecordWriter::AddTemplateArgumentLocInfo( 5577 TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) { 5578 switch (Kind) { 5579 case TemplateArgument::Expression: 5580 AddStmt(Arg.getAsExpr()); 5581 break; 5582 case TemplateArgument::Type: 5583 AddTypeSourceInfo(Arg.getAsTypeSourceInfo()); 5584 break; 5585 case TemplateArgument::Template: 5586 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5587 AddSourceLocation(Arg.getTemplateNameLoc()); 5588 break; 5589 case TemplateArgument::TemplateExpansion: 5590 AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc()); 5591 AddSourceLocation(Arg.getTemplateNameLoc()); 5592 AddSourceLocation(Arg.getTemplateEllipsisLoc()); 5593 break; 5594 case TemplateArgument::Null: 5595 case TemplateArgument::Integral: 5596 case TemplateArgument::Declaration: 5597 case TemplateArgument::NullPtr: 5598 case TemplateArgument::Pack: 5599 // FIXME: Is this right? 5600 break; 5601 } 5602 } 5603 5604 void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) { 5605 AddTemplateArgument(Arg.getArgument()); 5606 5607 if (Arg.getArgument().getKind() == TemplateArgument::Expression) { 5608 bool InfoHasSameExpr 5609 = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr(); 5610 Record->push_back(InfoHasSameExpr); 5611 if (InfoHasSameExpr) 5612 return; // Avoid storing the same expr twice. 5613 } 5614 AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo()); 5615 } 5616 5617 void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) { 5618 if (!TInfo) { 5619 AddTypeRef(QualType()); 5620 return; 5621 } 5622 5623 AddTypeRef(TInfo->getType()); 5624 AddTypeLoc(TInfo->getTypeLoc()); 5625 } 5626 5627 void ASTRecordWriter::AddTypeLoc(TypeLoc TL) { 5628 TypeLocWriter TLW(*this); 5629 for (; !TL.isNull(); TL = TL.getNextTypeLoc()) 5630 TLW.Visit(TL); 5631 } 5632 5633 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) { 5634 Record.push_back(GetOrCreateTypeID(T)); 5635 } 5636 5637 TypeID ASTWriter::GetOrCreateTypeID(QualType T) { 5638 assert(Context); 5639 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5640 if (T.isNull()) 5641 return TypeIdx(); 5642 assert(!T.getLocalFastQualifiers()); 5643 5644 TypeIdx &Idx = TypeIdxs[T]; 5645 if (Idx.getIndex() == 0) { 5646 if (DoneWritingDeclsAndTypes) { 5647 assert(0 && "New type seen after serializing all the types to emit!"); 5648 return TypeIdx(); 5649 } 5650 5651 // We haven't seen this type before. Assign it a new ID and put it 5652 // into the queue of types to emit. 5653 Idx = TypeIdx(NextTypeID++); 5654 DeclTypesToEmit.push(T); 5655 } 5656 return Idx; 5657 }); 5658 } 5659 5660 TypeID ASTWriter::getTypeID(QualType T) const { 5661 assert(Context); 5662 return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx { 5663 if (T.isNull()) 5664 return TypeIdx(); 5665 assert(!T.getLocalFastQualifiers()); 5666 5667 TypeIdxMap::const_iterator I = TypeIdxs.find(T); 5668 assert(I != TypeIdxs.end() && "Type not emitted!"); 5669 return I->second; 5670 }); 5671 } 5672 5673 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) { 5674 Record.push_back(GetDeclRef(D)); 5675 } 5676 5677 DeclID ASTWriter::GetDeclRef(const Decl *D) { 5678 assert(WritingAST && "Cannot request a declaration ID before AST writing"); 5679 5680 if (!D) { 5681 return 0; 5682 } 5683 5684 // If D comes from an AST file, its declaration ID is already known and 5685 // fixed. 5686 if (D->isFromASTFile()) 5687 return D->getGlobalID(); 5688 5689 assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer"); 5690 DeclID &ID = DeclIDs[D]; 5691 if (ID == 0) { 5692 if (DoneWritingDeclsAndTypes) { 5693 assert(0 && "New decl seen after serializing all the decls to emit!"); 5694 return 0; 5695 } 5696 5697 // We haven't seen this declaration before. Give it a new ID and 5698 // enqueue it in the list of declarations to emit. 5699 ID = NextDeclID++; 5700 DeclTypesToEmit.push(const_cast<Decl *>(D)); 5701 } 5702 5703 return ID; 5704 } 5705 5706 DeclID ASTWriter::getDeclID(const Decl *D) { 5707 if (!D) 5708 return 0; 5709 5710 // If D comes from an AST file, its declaration ID is already known and 5711 // fixed. 5712 if (D->isFromASTFile()) 5713 return D->getGlobalID(); 5714 5715 assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!"); 5716 return DeclIDs[D]; 5717 } 5718 5719 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) { 5720 assert(ID); 5721 assert(D); 5722 5723 SourceLocation Loc = D->getLocation(); 5724 if (Loc.isInvalid()) 5725 return; 5726 5727 // We only keep track of the file-level declarations of each file. 5728 if (!D->getLexicalDeclContext()->isFileContext()) 5729 return; 5730 // FIXME: ParmVarDecls that are part of a function type of a parameter of 5731 // a function/objc method, should not have TU as lexical context. 5732 // TemplateTemplateParmDecls that are part of an alias template, should not 5733 // have TU as lexical context. 5734 if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D)) 5735 return; 5736 5737 SourceManager &SM = Context->getSourceManager(); 5738 SourceLocation FileLoc = SM.getFileLoc(Loc); 5739 assert(SM.isLocalSourceLocation(FileLoc)); 5740 FileID FID; 5741 unsigned Offset; 5742 std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc); 5743 if (FID.isInvalid()) 5744 return; 5745 assert(SM.getSLocEntry(FID).isFile()); 5746 5747 DeclIDInFileInfo *&Info = FileDeclIDs[FID]; 5748 if (!Info) 5749 Info = new DeclIDInFileInfo(); 5750 5751 std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID); 5752 LocDeclIDsTy &Decls = Info->DeclIDs; 5753 5754 if (Decls.empty() || Decls.back().first <= Offset) { 5755 Decls.push_back(LocDecl); 5756 return; 5757 } 5758 5759 LocDeclIDsTy::iterator I = 5760 llvm::upper_bound(Decls, LocDecl, llvm::less_first()); 5761 5762 Decls.insert(I, LocDecl); 5763 } 5764 5765 void ASTRecordWriter::AddDeclarationName(DeclarationName Name) { 5766 // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc. 5767 Record->push_back(Name.getNameKind()); 5768 switch (Name.getNameKind()) { 5769 case DeclarationName::Identifier: 5770 AddIdentifierRef(Name.getAsIdentifierInfo()); 5771 break; 5772 5773 case DeclarationName::ObjCZeroArgSelector: 5774 case DeclarationName::ObjCOneArgSelector: 5775 case DeclarationName::ObjCMultiArgSelector: 5776 AddSelectorRef(Name.getObjCSelector()); 5777 break; 5778 5779 case DeclarationName::CXXConstructorName: 5780 case DeclarationName::CXXDestructorName: 5781 case DeclarationName::CXXConversionFunctionName: 5782 AddTypeRef(Name.getCXXNameType()); 5783 break; 5784 5785 case DeclarationName::CXXDeductionGuideName: 5786 AddDeclRef(Name.getCXXDeductionGuideTemplate()); 5787 break; 5788 5789 case DeclarationName::CXXOperatorName: 5790 Record->push_back(Name.getCXXOverloadedOperator()); 5791 break; 5792 5793 case DeclarationName::CXXLiteralOperatorName: 5794 AddIdentifierRef(Name.getCXXLiteralIdentifier()); 5795 break; 5796 5797 case DeclarationName::CXXUsingDirective: 5798 // No extra data to emit 5799 break; 5800 } 5801 } 5802 5803 unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) { 5804 assert(needsAnonymousDeclarationNumber(D) && 5805 "expected an anonymous declaration"); 5806 5807 // Number the anonymous declarations within this context, if we've not 5808 // already done so. 5809 auto It = AnonymousDeclarationNumbers.find(D); 5810 if (It == AnonymousDeclarationNumbers.end()) { 5811 auto *DC = D->getLexicalDeclContext(); 5812 numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) { 5813 AnonymousDeclarationNumbers[ND] = Number; 5814 }); 5815 5816 It = AnonymousDeclarationNumbers.find(D); 5817 assert(It != AnonymousDeclarationNumbers.end() && 5818 "declaration not found within its lexical context"); 5819 } 5820 5821 return It->second; 5822 } 5823 5824 void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc, 5825 DeclarationName Name) { 5826 switch (Name.getNameKind()) { 5827 case DeclarationName::CXXConstructorName: 5828 case DeclarationName::CXXDestructorName: 5829 case DeclarationName::CXXConversionFunctionName: 5830 AddTypeSourceInfo(DNLoc.NamedType.TInfo); 5831 break; 5832 5833 case DeclarationName::CXXOperatorName: 5834 AddSourceLocation(SourceLocation::getFromRawEncoding( 5835 DNLoc.CXXOperatorName.BeginOpNameLoc)); 5836 AddSourceLocation( 5837 SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc)); 5838 break; 5839 5840 case DeclarationName::CXXLiteralOperatorName: 5841 AddSourceLocation(SourceLocation::getFromRawEncoding( 5842 DNLoc.CXXLiteralOperatorName.OpNameLoc)); 5843 break; 5844 5845 case DeclarationName::Identifier: 5846 case DeclarationName::ObjCZeroArgSelector: 5847 case DeclarationName::ObjCOneArgSelector: 5848 case DeclarationName::ObjCMultiArgSelector: 5849 case DeclarationName::CXXUsingDirective: 5850 case DeclarationName::CXXDeductionGuideName: 5851 break; 5852 } 5853 } 5854 5855 void ASTRecordWriter::AddDeclarationNameInfo( 5856 const DeclarationNameInfo &NameInfo) { 5857 AddDeclarationName(NameInfo.getName()); 5858 AddSourceLocation(NameInfo.getLoc()); 5859 AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName()); 5860 } 5861 5862 void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) { 5863 AddNestedNameSpecifierLoc(Info.QualifierLoc); 5864 Record->push_back(Info.NumTemplParamLists); 5865 for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i) 5866 AddTemplateParameterList(Info.TemplParamLists[i]); 5867 } 5868 5869 void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) { 5870 // Nested name specifiers usually aren't too long. I think that 8 would 5871 // typically accommodate the vast majority. 5872 SmallVector<NestedNameSpecifier *, 8> NestedNames; 5873 5874 // Push each of the NNS's onto a stack for serialization in reverse order. 5875 while (NNS) { 5876 NestedNames.push_back(NNS); 5877 NNS = NNS->getPrefix(); 5878 } 5879 5880 Record->push_back(NestedNames.size()); 5881 while(!NestedNames.empty()) { 5882 NNS = NestedNames.pop_back_val(); 5883 NestedNameSpecifier::SpecifierKind Kind = NNS->getKind(); 5884 Record->push_back(Kind); 5885 switch (Kind) { 5886 case NestedNameSpecifier::Identifier: 5887 AddIdentifierRef(NNS->getAsIdentifier()); 5888 break; 5889 5890 case NestedNameSpecifier::Namespace: 5891 AddDeclRef(NNS->getAsNamespace()); 5892 break; 5893 5894 case NestedNameSpecifier::NamespaceAlias: 5895 AddDeclRef(NNS->getAsNamespaceAlias()); 5896 break; 5897 5898 case NestedNameSpecifier::TypeSpec: 5899 case NestedNameSpecifier::TypeSpecWithTemplate: 5900 AddTypeRef(QualType(NNS->getAsType(), 0)); 5901 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5902 break; 5903 5904 case NestedNameSpecifier::Global: 5905 // Don't need to write an associated value. 5906 break; 5907 5908 case NestedNameSpecifier::Super: 5909 AddDeclRef(NNS->getAsRecordDecl()); 5910 break; 5911 } 5912 } 5913 } 5914 5915 void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 5916 // Nested name specifiers usually aren't too long. I think that 8 would 5917 // typically accommodate the vast majority. 5918 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 5919 5920 // Push each of the nested-name-specifiers's onto a stack for 5921 // serialization in reverse order. 5922 while (NNS) { 5923 NestedNames.push_back(NNS); 5924 NNS = NNS.getPrefix(); 5925 } 5926 5927 Record->push_back(NestedNames.size()); 5928 while(!NestedNames.empty()) { 5929 NNS = NestedNames.pop_back_val(); 5930 NestedNameSpecifier::SpecifierKind Kind 5931 = NNS.getNestedNameSpecifier()->getKind(); 5932 Record->push_back(Kind); 5933 switch (Kind) { 5934 case NestedNameSpecifier::Identifier: 5935 AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier()); 5936 AddSourceRange(NNS.getLocalSourceRange()); 5937 break; 5938 5939 case NestedNameSpecifier::Namespace: 5940 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace()); 5941 AddSourceRange(NNS.getLocalSourceRange()); 5942 break; 5943 5944 case NestedNameSpecifier::NamespaceAlias: 5945 AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias()); 5946 AddSourceRange(NNS.getLocalSourceRange()); 5947 break; 5948 5949 case NestedNameSpecifier::TypeSpec: 5950 case NestedNameSpecifier::TypeSpecWithTemplate: 5951 Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate); 5952 AddTypeRef(NNS.getTypeLoc().getType()); 5953 AddTypeLoc(NNS.getTypeLoc()); 5954 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5955 break; 5956 5957 case NestedNameSpecifier::Global: 5958 AddSourceLocation(NNS.getLocalSourceRange().getEnd()); 5959 break; 5960 5961 case NestedNameSpecifier::Super: 5962 AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl()); 5963 AddSourceRange(NNS.getLocalSourceRange()); 5964 break; 5965 } 5966 } 5967 } 5968 5969 void ASTRecordWriter::AddTemplateName(TemplateName Name) { 5970 TemplateName::NameKind Kind = Name.getKind(); 5971 Record->push_back(Kind); 5972 switch (Kind) { 5973 case TemplateName::Template: 5974 AddDeclRef(Name.getAsTemplateDecl()); 5975 break; 5976 5977 case TemplateName::OverloadedTemplate: { 5978 OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate(); 5979 Record->push_back(OvT->size()); 5980 for (const auto &I : *OvT) 5981 AddDeclRef(I); 5982 break; 5983 } 5984 5985 case TemplateName::AssumedTemplate: { 5986 AssumedTemplateStorage *ADLT = Name.getAsAssumedTemplateName(); 5987 AddDeclarationName(ADLT->getDeclName()); 5988 break; 5989 } 5990 5991 case TemplateName::QualifiedTemplate: { 5992 QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName(); 5993 AddNestedNameSpecifier(QualT->getQualifier()); 5994 Record->push_back(QualT->hasTemplateKeyword()); 5995 AddDeclRef(QualT->getTemplateDecl()); 5996 break; 5997 } 5998 5999 case TemplateName::DependentTemplate: { 6000 DependentTemplateName *DepT = Name.getAsDependentTemplateName(); 6001 AddNestedNameSpecifier(DepT->getQualifier()); 6002 Record->push_back(DepT->isIdentifier()); 6003 if (DepT->isIdentifier()) 6004 AddIdentifierRef(DepT->getIdentifier()); 6005 else 6006 Record->push_back(DepT->getOperator()); 6007 break; 6008 } 6009 6010 case TemplateName::SubstTemplateTemplateParm: { 6011 SubstTemplateTemplateParmStorage *subst 6012 = Name.getAsSubstTemplateTemplateParm(); 6013 AddDeclRef(subst->getParameter()); 6014 AddTemplateName(subst->getReplacement()); 6015 break; 6016 } 6017 6018 case TemplateName::SubstTemplateTemplateParmPack: { 6019 SubstTemplateTemplateParmPackStorage *SubstPack 6020 = Name.getAsSubstTemplateTemplateParmPack(); 6021 AddDeclRef(SubstPack->getParameterPack()); 6022 AddTemplateArgument(SubstPack->getArgumentPack()); 6023 break; 6024 } 6025 } 6026 } 6027 6028 void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) { 6029 Record->push_back(Arg.getKind()); 6030 switch (Arg.getKind()) { 6031 case TemplateArgument::Null: 6032 break; 6033 case TemplateArgument::Type: 6034 AddTypeRef(Arg.getAsType()); 6035 break; 6036 case TemplateArgument::Declaration: 6037 AddDeclRef(Arg.getAsDecl()); 6038 AddTypeRef(Arg.getParamTypeForDecl()); 6039 break; 6040 case TemplateArgument::NullPtr: 6041 AddTypeRef(Arg.getNullPtrType()); 6042 break; 6043 case TemplateArgument::Integral: 6044 AddAPSInt(Arg.getAsIntegral()); 6045 AddTypeRef(Arg.getIntegralType()); 6046 break; 6047 case TemplateArgument::Template: 6048 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 6049 break; 6050 case TemplateArgument::TemplateExpansion: 6051 AddTemplateName(Arg.getAsTemplateOrTemplatePattern()); 6052 if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions()) 6053 Record->push_back(*NumExpansions + 1); 6054 else 6055 Record->push_back(0); 6056 break; 6057 case TemplateArgument::Expression: 6058 AddStmt(Arg.getAsExpr()); 6059 break; 6060 case TemplateArgument::Pack: 6061 Record->push_back(Arg.pack_size()); 6062 for (const auto &P : Arg.pack_elements()) 6063 AddTemplateArgument(P); 6064 break; 6065 } 6066 } 6067 6068 void ASTRecordWriter::AddTemplateParameterList( 6069 const TemplateParameterList *TemplateParams) { 6070 assert(TemplateParams && "No TemplateParams!"); 6071 AddSourceLocation(TemplateParams->getTemplateLoc()); 6072 AddSourceLocation(TemplateParams->getLAngleLoc()); 6073 AddSourceLocation(TemplateParams->getRAngleLoc()); 6074 6075 Record->push_back(TemplateParams->size()); 6076 for (const auto &P : *TemplateParams) 6077 AddDeclRef(P); 6078 if (const Expr *RequiresClause = TemplateParams->getRequiresClause()) { 6079 Record->push_back(true); 6080 AddStmt(const_cast<Expr*>(RequiresClause)); 6081 } else { 6082 Record->push_back(false); 6083 } 6084 } 6085 6086 /// Emit a template argument list. 6087 void ASTRecordWriter::AddTemplateArgumentList( 6088 const TemplateArgumentList *TemplateArgs) { 6089 assert(TemplateArgs && "No TemplateArgs!"); 6090 Record->push_back(TemplateArgs->size()); 6091 for (int i = 0, e = TemplateArgs->size(); i != e; ++i) 6092 AddTemplateArgument(TemplateArgs->get(i)); 6093 } 6094 6095 void ASTRecordWriter::AddASTTemplateArgumentListInfo( 6096 const ASTTemplateArgumentListInfo *ASTTemplArgList) { 6097 assert(ASTTemplArgList && "No ASTTemplArgList!"); 6098 AddSourceLocation(ASTTemplArgList->LAngleLoc); 6099 AddSourceLocation(ASTTemplArgList->RAngleLoc); 6100 Record->push_back(ASTTemplArgList->NumTemplateArgs); 6101 const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs(); 6102 for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i) 6103 AddTemplateArgumentLoc(TemplArgs[i]); 6104 } 6105 6106 void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) { 6107 Record->push_back(Set.size()); 6108 for (ASTUnresolvedSet::const_iterator 6109 I = Set.begin(), E = Set.end(); I != E; ++I) { 6110 AddDeclRef(I.getDecl()); 6111 Record->push_back(I.getAccess()); 6112 } 6113 } 6114 6115 // FIXME: Move this out of the main ASTRecordWriter interface. 6116 void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) { 6117 Record->push_back(Base.isVirtual()); 6118 Record->push_back(Base.isBaseOfClass()); 6119 Record->push_back(Base.getAccessSpecifierAsWritten()); 6120 Record->push_back(Base.getInheritConstructors()); 6121 AddTypeSourceInfo(Base.getTypeSourceInfo()); 6122 AddSourceRange(Base.getSourceRange()); 6123 AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc() 6124 : SourceLocation()); 6125 } 6126 6127 static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W, 6128 ArrayRef<CXXBaseSpecifier> Bases) { 6129 ASTWriter::RecordData Record; 6130 ASTRecordWriter Writer(W, Record); 6131 Writer.push_back(Bases.size()); 6132 6133 for (auto &Base : Bases) 6134 Writer.AddCXXBaseSpecifier(Base); 6135 6136 return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS); 6137 } 6138 6139 // FIXME: Move this out of the main ASTRecordWriter interface. 6140 void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) { 6141 AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases)); 6142 } 6143 6144 static uint64_t 6145 EmitCXXCtorInitializers(ASTWriter &W, 6146 ArrayRef<CXXCtorInitializer *> CtorInits) { 6147 ASTWriter::RecordData Record; 6148 ASTRecordWriter Writer(W, Record); 6149 Writer.push_back(CtorInits.size()); 6150 6151 for (auto *Init : CtorInits) { 6152 if (Init->isBaseInitializer()) { 6153 Writer.push_back(CTOR_INITIALIZER_BASE); 6154 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 6155 Writer.push_back(Init->isBaseVirtual()); 6156 } else if (Init->isDelegatingInitializer()) { 6157 Writer.push_back(CTOR_INITIALIZER_DELEGATING); 6158 Writer.AddTypeSourceInfo(Init->getTypeSourceInfo()); 6159 } else if (Init->isMemberInitializer()){ 6160 Writer.push_back(CTOR_INITIALIZER_MEMBER); 6161 Writer.AddDeclRef(Init->getMember()); 6162 } else { 6163 Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER); 6164 Writer.AddDeclRef(Init->getIndirectMember()); 6165 } 6166 6167 Writer.AddSourceLocation(Init->getMemberLocation()); 6168 Writer.AddStmt(Init->getInit()); 6169 Writer.AddSourceLocation(Init->getLParenLoc()); 6170 Writer.AddSourceLocation(Init->getRParenLoc()); 6171 Writer.push_back(Init->isWritten()); 6172 if (Init->isWritten()) 6173 Writer.push_back(Init->getSourceOrder()); 6174 } 6175 6176 return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS); 6177 } 6178 6179 // FIXME: Move this out of the main ASTRecordWriter interface. 6180 void ASTRecordWriter::AddCXXCtorInitializers( 6181 ArrayRef<CXXCtorInitializer *> CtorInits) { 6182 AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits)); 6183 } 6184 6185 void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) { 6186 auto &Data = D->data(); 6187 Record->push_back(Data.IsLambda); 6188 6189 #define FIELD(Name, Width, Merge) \ 6190 Record->push_back(Data.Name); 6191 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 6192 6193 // getODRHash will compute the ODRHash if it has not been previously computed. 6194 Record->push_back(D->getODRHash()); 6195 bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo && 6196 Writer->WritingModule && !D->isDependentType(); 6197 Record->push_back(ModulesDebugInfo); 6198 if (ModulesDebugInfo) 6199 Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D)); 6200 6201 // IsLambda bit is already saved. 6202 6203 Record->push_back(Data.NumBases); 6204 if (Data.NumBases > 0) 6205 AddCXXBaseSpecifiers(Data.bases()); 6206 6207 // FIXME: Make VBases lazily computed when needed to avoid storing them. 6208 Record->push_back(Data.NumVBases); 6209 if (Data.NumVBases > 0) 6210 AddCXXBaseSpecifiers(Data.vbases()); 6211 6212 AddUnresolvedSet(Data.Conversions.get(*Writer->Context)); 6213 Record->push_back(Data.ComputedVisibleConversions); 6214 if (Data.ComputedVisibleConversions) 6215 AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context)); 6216 // Data.Definition is the owning decl, no need to write it. 6217 AddDeclRef(D->getFirstFriend()); 6218 6219 // Add lambda-specific data. 6220 if (Data.IsLambda) { 6221 auto &Lambda = D->getLambdaData(); 6222 Record->push_back(Lambda.Dependent); 6223 Record->push_back(Lambda.IsGenericLambda); 6224 Record->push_back(Lambda.CaptureDefault); 6225 Record->push_back(Lambda.NumCaptures); 6226 Record->push_back(Lambda.NumExplicitCaptures); 6227 Record->push_back(Lambda.HasKnownInternalLinkage); 6228 Record->push_back(Lambda.ManglingNumber); 6229 AddDeclRef(D->getLambdaContextDecl()); 6230 AddTypeSourceInfo(Lambda.MethodTyInfo); 6231 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) { 6232 const LambdaCapture &Capture = Lambda.Captures[I]; 6233 AddSourceLocation(Capture.getLocation()); 6234 Record->push_back(Capture.isImplicit()); 6235 Record->push_back(Capture.getCaptureKind()); 6236 switch (Capture.getCaptureKind()) { 6237 case LCK_StarThis: 6238 case LCK_This: 6239 case LCK_VLAType: 6240 break; 6241 case LCK_ByCopy: 6242 case LCK_ByRef: 6243 VarDecl *Var = 6244 Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr; 6245 AddDeclRef(Var); 6246 AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc() 6247 : SourceLocation()); 6248 break; 6249 } 6250 } 6251 } 6252 } 6253 6254 void ASTWriter::ReaderInitialized(ASTReader *Reader) { 6255 assert(Reader && "Cannot remove chain"); 6256 assert((!Chain || Chain == Reader) && "Cannot replace chain"); 6257 assert(FirstDeclID == NextDeclID && 6258 FirstTypeID == NextTypeID && 6259 FirstIdentID == NextIdentID && 6260 FirstMacroID == NextMacroID && 6261 FirstSubmoduleID == NextSubmoduleID && 6262 FirstSelectorID == NextSelectorID && 6263 "Setting chain after writing has started."); 6264 6265 Chain = Reader; 6266 6267 // Note, this will get called multiple times, once one the reader starts up 6268 // and again each time it's done reading a PCH or module. 6269 FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls(); 6270 FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes(); 6271 FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers(); 6272 FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros(); 6273 FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules(); 6274 FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors(); 6275 NextDeclID = FirstDeclID; 6276 NextTypeID = FirstTypeID; 6277 NextIdentID = FirstIdentID; 6278 NextMacroID = FirstMacroID; 6279 NextSelectorID = FirstSelectorID; 6280 NextSubmoduleID = FirstSubmoduleID; 6281 } 6282 6283 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) { 6284 // Always keep the highest ID. See \p TypeRead() for more information. 6285 IdentID &StoredID = IdentifierIDs[II]; 6286 if (ID > StoredID) 6287 StoredID = ID; 6288 } 6289 6290 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) { 6291 // Always keep the highest ID. See \p TypeRead() for more information. 6292 MacroID &StoredID = MacroIDs[MI]; 6293 if (ID > StoredID) 6294 StoredID = ID; 6295 } 6296 6297 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) { 6298 // Always take the highest-numbered type index. This copes with an interesting 6299 // case for chained AST writing where we schedule writing the type and then, 6300 // later, deserialize the type from another AST. In this case, we want to 6301 // keep the higher-numbered entry so that we can properly write it out to 6302 // the AST file. 6303 TypeIdx &StoredIdx = TypeIdxs[T]; 6304 if (Idx.getIndex() >= StoredIdx.getIndex()) 6305 StoredIdx = Idx; 6306 } 6307 6308 void ASTWriter::SelectorRead(SelectorID ID, Selector S) { 6309 // Always keep the highest ID. See \p TypeRead() for more information. 6310 SelectorID &StoredID = SelectorIDs[S]; 6311 if (ID > StoredID) 6312 StoredID = ID; 6313 } 6314 6315 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID, 6316 MacroDefinitionRecord *MD) { 6317 assert(MacroDefinitions.find(MD) == MacroDefinitions.end()); 6318 MacroDefinitions[MD] = ID; 6319 } 6320 6321 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) { 6322 assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end()); 6323 SubmoduleIDs[Mod] = ID; 6324 } 6325 6326 void ASTWriter::CompletedTagDefinition(const TagDecl *D) { 6327 if (Chain && Chain->isProcessingUpdateRecords()) return; 6328 assert(D->isCompleteDefinition()); 6329 assert(!WritingAST && "Already writing the AST!"); 6330 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 6331 // We are interested when a PCH decl is modified. 6332 if (RD->isFromASTFile()) { 6333 // A forward reference was mutated into a definition. Rewrite it. 6334 // FIXME: This happens during template instantiation, should we 6335 // have created a new definition decl instead ? 6336 assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) && 6337 "completed a tag from another module but not by instantiation?"); 6338 DeclUpdates[RD].push_back( 6339 DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION)); 6340 } 6341 } 6342 } 6343 6344 static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) { 6345 if (D->isFromASTFile()) 6346 return true; 6347 6348 // The predefined __va_list_tag struct is imported if we imported any decls. 6349 // FIXME: This is a gross hack. 6350 return D == D->getASTContext().getVaListTagDecl(); 6351 } 6352 6353 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) { 6354 if (Chain && Chain->isProcessingUpdateRecords()) return; 6355 assert(DC->isLookupContext() && 6356 "Should not add lookup results to non-lookup contexts!"); 6357 6358 // TU is handled elsewhere. 6359 if (isa<TranslationUnitDecl>(DC)) 6360 return; 6361 6362 // Namespaces are handled elsewhere, except for template instantiations of 6363 // FunctionTemplateDecls in namespaces. We are interested in cases where the 6364 // local instantiations are added to an imported context. Only happens when 6365 // adding ADL lookup candidates, for example templated friends. 6366 if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None && 6367 !isa<FunctionTemplateDecl>(D)) 6368 return; 6369 6370 // We're only interested in cases where a local declaration is added to an 6371 // imported context. 6372 if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC))) 6373 return; 6374 6375 assert(DC == DC->getPrimaryContext() && "added to non-primary context"); 6376 assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!"); 6377 assert(!WritingAST && "Already writing the AST!"); 6378 if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) { 6379 // We're adding a visible declaration to a predefined decl context. Ensure 6380 // that we write out all of its lookup results so we don't get a nasty 6381 // surprise when we try to emit its lookup table. 6382 for (auto *Child : DC->decls()) 6383 DeclsToEmitEvenIfUnreferenced.push_back(Child); 6384 } 6385 DeclsToEmitEvenIfUnreferenced.push_back(D); 6386 } 6387 6388 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) { 6389 if (Chain && Chain->isProcessingUpdateRecords()) return; 6390 assert(D->isImplicit()); 6391 6392 // We're only interested in cases where a local declaration is added to an 6393 // imported context. 6394 if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD)) 6395 return; 6396 6397 if (!isa<CXXMethodDecl>(D)) 6398 return; 6399 6400 // A decl coming from PCH was modified. 6401 assert(RD->isCompleteDefinition()); 6402 assert(!WritingAST && "Already writing the AST!"); 6403 DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D)); 6404 } 6405 6406 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) { 6407 if (Chain && Chain->isProcessingUpdateRecords()) return; 6408 assert(!DoneWritingDeclsAndTypes && "Already done writing updates!"); 6409 if (!Chain) return; 6410 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6411 // If we don't already know the exception specification for this redecl 6412 // chain, add an update record for it. 6413 if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D) 6414 ->getType() 6415 ->castAs<FunctionProtoType>() 6416 ->getExceptionSpecType())) 6417 DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC); 6418 }); 6419 } 6420 6421 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) { 6422 if (Chain && Chain->isProcessingUpdateRecords()) return; 6423 assert(!WritingAST && "Already writing the AST!"); 6424 if (!Chain) return; 6425 Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) { 6426 DeclUpdates[D].push_back( 6427 DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType)); 6428 }); 6429 } 6430 6431 void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD, 6432 const FunctionDecl *Delete, 6433 Expr *ThisArg) { 6434 if (Chain && Chain->isProcessingUpdateRecords()) return; 6435 assert(!WritingAST && "Already writing the AST!"); 6436 assert(Delete && "Not given an operator delete"); 6437 if (!Chain) return; 6438 Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) { 6439 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete)); 6440 }); 6441 } 6442 6443 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) { 6444 if (Chain && Chain->isProcessingUpdateRecords()) return; 6445 assert(!WritingAST && "Already writing the AST!"); 6446 if (!D->isFromASTFile()) 6447 return; // Declaration not imported from PCH. 6448 6449 // Implicit function decl from a PCH was defined. 6450 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6451 } 6452 6453 void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) { 6454 if (Chain && Chain->isProcessingUpdateRecords()) return; 6455 assert(!WritingAST && "Already writing the AST!"); 6456 if (!D->isFromASTFile()) 6457 return; 6458 6459 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION)); 6460 } 6461 6462 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) { 6463 if (Chain && Chain->isProcessingUpdateRecords()) return; 6464 assert(!WritingAST && "Already writing the AST!"); 6465 if (!D->isFromASTFile()) 6466 return; 6467 6468 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION)); 6469 } 6470 6471 void ASTWriter::InstantiationRequested(const ValueDecl *D) { 6472 if (Chain && Chain->isProcessingUpdateRecords()) return; 6473 assert(!WritingAST && "Already writing the AST!"); 6474 if (!D->isFromASTFile()) 6475 return; 6476 6477 // Since the actual instantiation is delayed, this really means that we need 6478 // to update the instantiation location. 6479 SourceLocation POI; 6480 if (auto *VD = dyn_cast<VarDecl>(D)) 6481 POI = VD->getPointOfInstantiation(); 6482 else 6483 POI = cast<FunctionDecl>(D)->getPointOfInstantiation(); 6484 DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI)); 6485 } 6486 6487 void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) { 6488 if (Chain && Chain->isProcessingUpdateRecords()) return; 6489 assert(!WritingAST && "Already writing the AST!"); 6490 if (!D->isFromASTFile()) 6491 return; 6492 6493 DeclUpdates[D].push_back( 6494 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D)); 6495 } 6496 6497 void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) { 6498 assert(!WritingAST && "Already writing the AST!"); 6499 if (!D->isFromASTFile()) 6500 return; 6501 6502 DeclUpdates[D].push_back( 6503 DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D)); 6504 } 6505 6506 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD, 6507 const ObjCInterfaceDecl *IFD) { 6508 if (Chain && Chain->isProcessingUpdateRecords()) return; 6509 assert(!WritingAST && "Already writing the AST!"); 6510 if (!IFD->isFromASTFile()) 6511 return; // Declaration not imported from PCH. 6512 6513 assert(IFD->getDefinition() && "Category on a class without a definition?"); 6514 ObjCClassesWithCategories.insert( 6515 const_cast<ObjCInterfaceDecl *>(IFD->getDefinition())); 6516 } 6517 6518 void ASTWriter::DeclarationMarkedUsed(const Decl *D) { 6519 if (Chain && Chain->isProcessingUpdateRecords()) return; 6520 assert(!WritingAST && "Already writing the AST!"); 6521 6522 // If there is *any* declaration of the entity that's not from an AST file, 6523 // we can skip writing the update record. We make sure that isUsed() triggers 6524 // completion of the redeclaration chain of the entity. 6525 for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl()) 6526 if (IsLocalDecl(Prev)) 6527 return; 6528 6529 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED)); 6530 } 6531 6532 void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) { 6533 if (Chain && Chain->isProcessingUpdateRecords()) return; 6534 assert(!WritingAST && "Already writing the AST!"); 6535 if (!D->isFromASTFile()) 6536 return; 6537 6538 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE)); 6539 } 6540 6541 void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) { 6542 if (Chain && Chain->isProcessingUpdateRecords()) return; 6543 assert(!WritingAST && "Already writing the AST!"); 6544 if (!D->isFromASTFile()) 6545 return; 6546 6547 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A)); 6548 } 6549 6550 void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D, 6551 const Attr *Attr) { 6552 if (Chain && Chain->isProcessingUpdateRecords()) return; 6553 assert(!WritingAST && "Already writing the AST!"); 6554 if (!D->isFromASTFile()) 6555 return; 6556 6557 DeclUpdates[D].push_back( 6558 DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr)); 6559 } 6560 6561 void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) { 6562 if (Chain && Chain->isProcessingUpdateRecords()) return; 6563 assert(!WritingAST && "Already writing the AST!"); 6564 assert(D->isHidden() && "expected a hidden declaration"); 6565 DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M)); 6566 } 6567 6568 void ASTWriter::AddedAttributeToRecord(const Attr *Attr, 6569 const RecordDecl *Record) { 6570 if (Chain && Chain->isProcessingUpdateRecords()) return; 6571 assert(!WritingAST && "Already writing the AST!"); 6572 if (!Record->isFromASTFile()) 6573 return; 6574 DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr)); 6575 } 6576 6577 void ASTWriter::AddedCXXTemplateSpecialization( 6578 const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) { 6579 assert(!WritingAST && "Already writing the AST!"); 6580 6581 if (!TD->getFirstDecl()->isFromASTFile()) 6582 return; 6583 if (Chain && Chain->isProcessingUpdateRecords()) 6584 return; 6585 6586 DeclsToEmitEvenIfUnreferenced.push_back(D); 6587 } 6588 6589 void ASTWriter::AddedCXXTemplateSpecialization( 6590 const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) { 6591 assert(!WritingAST && "Already writing the AST!"); 6592 6593 if (!TD->getFirstDecl()->isFromASTFile()) 6594 return; 6595 if (Chain && Chain->isProcessingUpdateRecords()) 6596 return; 6597 6598 DeclsToEmitEvenIfUnreferenced.push_back(D); 6599 } 6600 6601 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD, 6602 const FunctionDecl *D) { 6603 assert(!WritingAST && "Already writing the AST!"); 6604 6605 if (!TD->getFirstDecl()->isFromASTFile()) 6606 return; 6607 if (Chain && Chain->isProcessingUpdateRecords()) 6608 return; 6609 6610 DeclsToEmitEvenIfUnreferenced.push_back(D); 6611 } 6612 6613 //===----------------------------------------------------------------------===// 6614 //// OMPClause Serialization 6615 ////===----------------------------------------------------------------------===// 6616 6617 void OMPClauseWriter::writeClause(OMPClause *C) { 6618 Record.push_back(C->getClauseKind()); 6619 Visit(C); 6620 Record.AddSourceLocation(C->getBeginLoc()); 6621 Record.AddSourceLocation(C->getEndLoc()); 6622 } 6623 6624 void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) { 6625 Record.push_back(C->getCaptureRegion()); 6626 Record.AddStmt(C->getPreInitStmt()); 6627 } 6628 6629 void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) { 6630 VisitOMPClauseWithPreInit(C); 6631 Record.AddStmt(C->getPostUpdateExpr()); 6632 } 6633 6634 void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) { 6635 VisitOMPClauseWithPreInit(C); 6636 Record.push_back(C->getNameModifier()); 6637 Record.AddSourceLocation(C->getNameModifierLoc()); 6638 Record.AddSourceLocation(C->getColonLoc()); 6639 Record.AddStmt(C->getCondition()); 6640 Record.AddSourceLocation(C->getLParenLoc()); 6641 } 6642 6643 void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) { 6644 VisitOMPClauseWithPreInit(C); 6645 Record.AddStmt(C->getCondition()); 6646 Record.AddSourceLocation(C->getLParenLoc()); 6647 } 6648 6649 void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) { 6650 VisitOMPClauseWithPreInit(C); 6651 Record.AddStmt(C->getNumThreads()); 6652 Record.AddSourceLocation(C->getLParenLoc()); 6653 } 6654 6655 void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) { 6656 Record.AddStmt(C->getSafelen()); 6657 Record.AddSourceLocation(C->getLParenLoc()); 6658 } 6659 6660 void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) { 6661 Record.AddStmt(C->getSimdlen()); 6662 Record.AddSourceLocation(C->getLParenLoc()); 6663 } 6664 6665 void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) { 6666 Record.AddStmt(C->getAllocator()); 6667 Record.AddSourceLocation(C->getLParenLoc()); 6668 } 6669 6670 void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) { 6671 Record.AddStmt(C->getNumForLoops()); 6672 Record.AddSourceLocation(C->getLParenLoc()); 6673 } 6674 6675 void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) { 6676 Record.push_back(C->getDefaultKind()); 6677 Record.AddSourceLocation(C->getLParenLoc()); 6678 Record.AddSourceLocation(C->getDefaultKindKwLoc()); 6679 } 6680 6681 void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) { 6682 Record.push_back(C->getProcBindKind()); 6683 Record.AddSourceLocation(C->getLParenLoc()); 6684 Record.AddSourceLocation(C->getProcBindKindKwLoc()); 6685 } 6686 6687 void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) { 6688 VisitOMPClauseWithPreInit(C); 6689 Record.push_back(C->getScheduleKind()); 6690 Record.push_back(C->getFirstScheduleModifier()); 6691 Record.push_back(C->getSecondScheduleModifier()); 6692 Record.AddStmt(C->getChunkSize()); 6693 Record.AddSourceLocation(C->getLParenLoc()); 6694 Record.AddSourceLocation(C->getFirstScheduleModifierLoc()); 6695 Record.AddSourceLocation(C->getSecondScheduleModifierLoc()); 6696 Record.AddSourceLocation(C->getScheduleKindLoc()); 6697 Record.AddSourceLocation(C->getCommaLoc()); 6698 } 6699 6700 void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) { 6701 Record.push_back(C->getLoopNumIterations().size()); 6702 Record.AddStmt(C->getNumForLoops()); 6703 for (Expr *NumIter : C->getLoopNumIterations()) 6704 Record.AddStmt(NumIter); 6705 for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I) 6706 Record.AddStmt(C->getLoopCounter(I)); 6707 Record.AddSourceLocation(C->getLParenLoc()); 6708 } 6709 6710 void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {} 6711 6712 void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {} 6713 6714 void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {} 6715 6716 void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {} 6717 6718 void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {} 6719 6720 void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {} 6721 6722 void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {} 6723 6724 void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {} 6725 6726 void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {} 6727 6728 void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {} 6729 6730 void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {} 6731 6732 void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) { 6733 Record.push_back(C->varlist_size()); 6734 Record.AddSourceLocation(C->getLParenLoc()); 6735 for (auto *VE : C->varlists()) { 6736 Record.AddStmt(VE); 6737 } 6738 for (auto *VE : C->private_copies()) { 6739 Record.AddStmt(VE); 6740 } 6741 } 6742 6743 void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) { 6744 Record.push_back(C->varlist_size()); 6745 VisitOMPClauseWithPreInit(C); 6746 Record.AddSourceLocation(C->getLParenLoc()); 6747 for (auto *VE : C->varlists()) { 6748 Record.AddStmt(VE); 6749 } 6750 for (auto *VE : C->private_copies()) { 6751 Record.AddStmt(VE); 6752 } 6753 for (auto *VE : C->inits()) { 6754 Record.AddStmt(VE); 6755 } 6756 } 6757 6758 void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) { 6759 Record.push_back(C->varlist_size()); 6760 VisitOMPClauseWithPostUpdate(C); 6761 Record.AddSourceLocation(C->getLParenLoc()); 6762 for (auto *VE : C->varlists()) 6763 Record.AddStmt(VE); 6764 for (auto *E : C->private_copies()) 6765 Record.AddStmt(E); 6766 for (auto *E : C->source_exprs()) 6767 Record.AddStmt(E); 6768 for (auto *E : C->destination_exprs()) 6769 Record.AddStmt(E); 6770 for (auto *E : C->assignment_ops()) 6771 Record.AddStmt(E); 6772 } 6773 6774 void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) { 6775 Record.push_back(C->varlist_size()); 6776 Record.AddSourceLocation(C->getLParenLoc()); 6777 for (auto *VE : C->varlists()) 6778 Record.AddStmt(VE); 6779 } 6780 6781 void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) { 6782 Record.push_back(C->varlist_size()); 6783 VisitOMPClauseWithPostUpdate(C); 6784 Record.AddSourceLocation(C->getLParenLoc()); 6785 Record.AddSourceLocation(C->getColonLoc()); 6786 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6787 Record.AddDeclarationNameInfo(C->getNameInfo()); 6788 for (auto *VE : C->varlists()) 6789 Record.AddStmt(VE); 6790 for (auto *VE : C->privates()) 6791 Record.AddStmt(VE); 6792 for (auto *E : C->lhs_exprs()) 6793 Record.AddStmt(E); 6794 for (auto *E : C->rhs_exprs()) 6795 Record.AddStmt(E); 6796 for (auto *E : C->reduction_ops()) 6797 Record.AddStmt(E); 6798 } 6799 6800 void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) { 6801 Record.push_back(C->varlist_size()); 6802 VisitOMPClauseWithPostUpdate(C); 6803 Record.AddSourceLocation(C->getLParenLoc()); 6804 Record.AddSourceLocation(C->getColonLoc()); 6805 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6806 Record.AddDeclarationNameInfo(C->getNameInfo()); 6807 for (auto *VE : C->varlists()) 6808 Record.AddStmt(VE); 6809 for (auto *VE : C->privates()) 6810 Record.AddStmt(VE); 6811 for (auto *E : C->lhs_exprs()) 6812 Record.AddStmt(E); 6813 for (auto *E : C->rhs_exprs()) 6814 Record.AddStmt(E); 6815 for (auto *E : C->reduction_ops()) 6816 Record.AddStmt(E); 6817 } 6818 6819 void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) { 6820 Record.push_back(C->varlist_size()); 6821 VisitOMPClauseWithPostUpdate(C); 6822 Record.AddSourceLocation(C->getLParenLoc()); 6823 Record.AddSourceLocation(C->getColonLoc()); 6824 Record.AddNestedNameSpecifierLoc(C->getQualifierLoc()); 6825 Record.AddDeclarationNameInfo(C->getNameInfo()); 6826 for (auto *VE : C->varlists()) 6827 Record.AddStmt(VE); 6828 for (auto *VE : C->privates()) 6829 Record.AddStmt(VE); 6830 for (auto *E : C->lhs_exprs()) 6831 Record.AddStmt(E); 6832 for (auto *E : C->rhs_exprs()) 6833 Record.AddStmt(E); 6834 for (auto *E : C->reduction_ops()) 6835 Record.AddStmt(E); 6836 for (auto *E : C->taskgroup_descriptors()) 6837 Record.AddStmt(E); 6838 } 6839 6840 void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) { 6841 Record.push_back(C->varlist_size()); 6842 VisitOMPClauseWithPostUpdate(C); 6843 Record.AddSourceLocation(C->getLParenLoc()); 6844 Record.AddSourceLocation(C->getColonLoc()); 6845 Record.push_back(C->getModifier()); 6846 Record.AddSourceLocation(C->getModifierLoc()); 6847 for (auto *VE : C->varlists()) { 6848 Record.AddStmt(VE); 6849 } 6850 for (auto *VE : C->privates()) { 6851 Record.AddStmt(VE); 6852 } 6853 for (auto *VE : C->inits()) { 6854 Record.AddStmt(VE); 6855 } 6856 for (auto *VE : C->updates()) { 6857 Record.AddStmt(VE); 6858 } 6859 for (auto *VE : C->finals()) { 6860 Record.AddStmt(VE); 6861 } 6862 Record.AddStmt(C->getStep()); 6863 Record.AddStmt(C->getCalcStep()); 6864 for (auto *VE : C->used_expressions()) 6865 Record.AddStmt(VE); 6866 } 6867 6868 void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) { 6869 Record.push_back(C->varlist_size()); 6870 Record.AddSourceLocation(C->getLParenLoc()); 6871 Record.AddSourceLocation(C->getColonLoc()); 6872 for (auto *VE : C->varlists()) 6873 Record.AddStmt(VE); 6874 Record.AddStmt(C->getAlignment()); 6875 } 6876 6877 void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) { 6878 Record.push_back(C->varlist_size()); 6879 Record.AddSourceLocation(C->getLParenLoc()); 6880 for (auto *VE : C->varlists()) 6881 Record.AddStmt(VE); 6882 for (auto *E : C->source_exprs()) 6883 Record.AddStmt(E); 6884 for (auto *E : C->destination_exprs()) 6885 Record.AddStmt(E); 6886 for (auto *E : C->assignment_ops()) 6887 Record.AddStmt(E); 6888 } 6889 6890 void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) { 6891 Record.push_back(C->varlist_size()); 6892 Record.AddSourceLocation(C->getLParenLoc()); 6893 for (auto *VE : C->varlists()) 6894 Record.AddStmt(VE); 6895 for (auto *E : C->source_exprs()) 6896 Record.AddStmt(E); 6897 for (auto *E : C->destination_exprs()) 6898 Record.AddStmt(E); 6899 for (auto *E : C->assignment_ops()) 6900 Record.AddStmt(E); 6901 } 6902 6903 void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) { 6904 Record.push_back(C->varlist_size()); 6905 Record.AddSourceLocation(C->getLParenLoc()); 6906 for (auto *VE : C->varlists()) 6907 Record.AddStmt(VE); 6908 } 6909 6910 void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) { 6911 Record.push_back(C->varlist_size()); 6912 Record.push_back(C->getNumLoops()); 6913 Record.AddSourceLocation(C->getLParenLoc()); 6914 Record.push_back(C->getDependencyKind()); 6915 Record.AddSourceLocation(C->getDependencyLoc()); 6916 Record.AddSourceLocation(C->getColonLoc()); 6917 for (auto *VE : C->varlists()) 6918 Record.AddStmt(VE); 6919 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) 6920 Record.AddStmt(C->getLoopData(I)); 6921 } 6922 6923 void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) { 6924 VisitOMPClauseWithPreInit(C); 6925 Record.AddStmt(C->getDevice()); 6926 Record.AddSourceLocation(C->getLParenLoc()); 6927 } 6928 6929 void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) { 6930 Record.push_back(C->varlist_size()); 6931 Record.push_back(C->getUniqueDeclarationsNum()); 6932 Record.push_back(C->getTotalComponentListNum()); 6933 Record.push_back(C->getTotalComponentsNum()); 6934 Record.AddSourceLocation(C->getLParenLoc()); 6935 for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) { 6936 Record.push_back(C->getMapTypeModifier(I)); 6937 Record.AddSourceLocation(C->getMapTypeModifierLoc(I)); 6938 } 6939 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 6940 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 6941 Record.push_back(C->getMapType()); 6942 Record.AddSourceLocation(C->getMapLoc()); 6943 Record.AddSourceLocation(C->getColonLoc()); 6944 for (auto *E : C->varlists()) 6945 Record.AddStmt(E); 6946 for (auto *E : C->mapperlists()) 6947 Record.AddStmt(E); 6948 for (auto *D : C->all_decls()) 6949 Record.AddDeclRef(D); 6950 for (auto N : C->all_num_lists()) 6951 Record.push_back(N); 6952 for (auto N : C->all_lists_sizes()) 6953 Record.push_back(N); 6954 for (auto &M : C->all_components()) { 6955 Record.AddStmt(M.getAssociatedExpression()); 6956 Record.AddDeclRef(M.getAssociatedDeclaration()); 6957 } 6958 } 6959 6960 void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) { 6961 Record.push_back(C->varlist_size()); 6962 Record.AddSourceLocation(C->getLParenLoc()); 6963 Record.AddSourceLocation(C->getColonLoc()); 6964 Record.AddStmt(C->getAllocator()); 6965 for (auto *VE : C->varlists()) 6966 Record.AddStmt(VE); 6967 } 6968 6969 void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) { 6970 VisitOMPClauseWithPreInit(C); 6971 Record.AddStmt(C->getNumTeams()); 6972 Record.AddSourceLocation(C->getLParenLoc()); 6973 } 6974 6975 void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) { 6976 VisitOMPClauseWithPreInit(C); 6977 Record.AddStmt(C->getThreadLimit()); 6978 Record.AddSourceLocation(C->getLParenLoc()); 6979 } 6980 6981 void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) { 6982 VisitOMPClauseWithPreInit(C); 6983 Record.AddStmt(C->getPriority()); 6984 Record.AddSourceLocation(C->getLParenLoc()); 6985 } 6986 6987 void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) { 6988 VisitOMPClauseWithPreInit(C); 6989 Record.AddStmt(C->getGrainsize()); 6990 Record.AddSourceLocation(C->getLParenLoc()); 6991 } 6992 6993 void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) { 6994 VisitOMPClauseWithPreInit(C); 6995 Record.AddStmt(C->getNumTasks()); 6996 Record.AddSourceLocation(C->getLParenLoc()); 6997 } 6998 6999 void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) { 7000 Record.AddStmt(C->getHint()); 7001 Record.AddSourceLocation(C->getLParenLoc()); 7002 } 7003 7004 void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) { 7005 VisitOMPClauseWithPreInit(C); 7006 Record.push_back(C->getDistScheduleKind()); 7007 Record.AddStmt(C->getChunkSize()); 7008 Record.AddSourceLocation(C->getLParenLoc()); 7009 Record.AddSourceLocation(C->getDistScheduleKindLoc()); 7010 Record.AddSourceLocation(C->getCommaLoc()); 7011 } 7012 7013 void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) { 7014 Record.push_back(C->getDefaultmapKind()); 7015 Record.push_back(C->getDefaultmapModifier()); 7016 Record.AddSourceLocation(C->getLParenLoc()); 7017 Record.AddSourceLocation(C->getDefaultmapModifierLoc()); 7018 Record.AddSourceLocation(C->getDefaultmapKindLoc()); 7019 } 7020 7021 void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) { 7022 Record.push_back(C->varlist_size()); 7023 Record.push_back(C->getUniqueDeclarationsNum()); 7024 Record.push_back(C->getTotalComponentListNum()); 7025 Record.push_back(C->getTotalComponentsNum()); 7026 Record.AddSourceLocation(C->getLParenLoc()); 7027 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 7028 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 7029 for (auto *E : C->varlists()) 7030 Record.AddStmt(E); 7031 for (auto *E : C->mapperlists()) 7032 Record.AddStmt(E); 7033 for (auto *D : C->all_decls()) 7034 Record.AddDeclRef(D); 7035 for (auto N : C->all_num_lists()) 7036 Record.push_back(N); 7037 for (auto N : C->all_lists_sizes()) 7038 Record.push_back(N); 7039 for (auto &M : C->all_components()) { 7040 Record.AddStmt(M.getAssociatedExpression()); 7041 Record.AddDeclRef(M.getAssociatedDeclaration()); 7042 } 7043 } 7044 7045 void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) { 7046 Record.push_back(C->varlist_size()); 7047 Record.push_back(C->getUniqueDeclarationsNum()); 7048 Record.push_back(C->getTotalComponentListNum()); 7049 Record.push_back(C->getTotalComponentsNum()); 7050 Record.AddSourceLocation(C->getLParenLoc()); 7051 Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc()); 7052 Record.AddDeclarationNameInfo(C->getMapperIdInfo()); 7053 for (auto *E : C->varlists()) 7054 Record.AddStmt(E); 7055 for (auto *E : C->mapperlists()) 7056 Record.AddStmt(E); 7057 for (auto *D : C->all_decls()) 7058 Record.AddDeclRef(D); 7059 for (auto N : C->all_num_lists()) 7060 Record.push_back(N); 7061 for (auto N : C->all_lists_sizes()) 7062 Record.push_back(N); 7063 for (auto &M : C->all_components()) { 7064 Record.AddStmt(M.getAssociatedExpression()); 7065 Record.AddDeclRef(M.getAssociatedDeclaration()); 7066 } 7067 } 7068 7069 void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) { 7070 Record.push_back(C->varlist_size()); 7071 Record.push_back(C->getUniqueDeclarationsNum()); 7072 Record.push_back(C->getTotalComponentListNum()); 7073 Record.push_back(C->getTotalComponentsNum()); 7074 Record.AddSourceLocation(C->getLParenLoc()); 7075 for (auto *E : C->varlists()) 7076 Record.AddStmt(E); 7077 for (auto *VE : C->private_copies()) 7078 Record.AddStmt(VE); 7079 for (auto *VE : C->inits()) 7080 Record.AddStmt(VE); 7081 for (auto *D : C->all_decls()) 7082 Record.AddDeclRef(D); 7083 for (auto N : C->all_num_lists()) 7084 Record.push_back(N); 7085 for (auto N : C->all_lists_sizes()) 7086 Record.push_back(N); 7087 for (auto &M : C->all_components()) { 7088 Record.AddStmt(M.getAssociatedExpression()); 7089 Record.AddDeclRef(M.getAssociatedDeclaration()); 7090 } 7091 } 7092 7093 void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) { 7094 Record.push_back(C->varlist_size()); 7095 Record.push_back(C->getUniqueDeclarationsNum()); 7096 Record.push_back(C->getTotalComponentListNum()); 7097 Record.push_back(C->getTotalComponentsNum()); 7098 Record.AddSourceLocation(C->getLParenLoc()); 7099 for (auto *E : C->varlists()) 7100 Record.AddStmt(E); 7101 for (auto *D : C->all_decls()) 7102 Record.AddDeclRef(D); 7103 for (auto N : C->all_num_lists()) 7104 Record.push_back(N); 7105 for (auto N : C->all_lists_sizes()) 7106 Record.push_back(N); 7107 for (auto &M : C->all_components()) { 7108 Record.AddStmt(M.getAssociatedExpression()); 7109 Record.AddDeclRef(M.getAssociatedDeclaration()); 7110 } 7111 } 7112 7113 void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {} 7114 7115 void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause( 7116 OMPUnifiedSharedMemoryClause *) {} 7117 7118 void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {} 7119 7120 void 7121 OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) { 7122 } 7123 7124 void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause( 7125 OMPAtomicDefaultMemOrderClause *C) { 7126 Record.push_back(C->getAtomicDefaultMemOrderKind()); 7127 Record.AddSourceLocation(C->getLParenLoc()); 7128 Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc()); 7129 } 7130