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