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