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