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