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