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