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