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