clang  8.0.0svn
ASTWriter.cpp
Go to the documentation of this file.
1 //===- ASTWriter.cpp - AST File Writer ------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "MultiOnDiskHashTable.h"
18 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
34 #include "clang/AST/TemplateName.h"
35 #include "clang/AST/Type.h"
37 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/Lambda.h"
46 #include "clang/Basic/Module.h"
52 #include "clang/Basic/Specifiers.h"
53 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/Version.h"
56 #include "clang/Lex/HeaderSearch.h"
58 #include "clang/Lex/MacroInfo.h"
59 #include "clang/Lex/ModuleMap.h"
61 #include "clang/Lex/Preprocessor.h"
63 #include "clang/Lex/Token.h"
66 #include "clang/Sema/Sema.h"
67 #include "clang/Sema/Weak.h"
72 #include "llvm/ADT/APFloat.h"
73 #include "llvm/ADT/APInt.h"
74 #include "llvm/ADT/APSInt.h"
75 #include "llvm/ADT/ArrayRef.h"
76 #include "llvm/ADT/DenseMap.h"
77 #include "llvm/ADT/Hashing.h"
78 #include "llvm/ADT/Optional.h"
79 #include "llvm/ADT/PointerIntPair.h"
80 #include "llvm/ADT/STLExtras.h"
81 #include "llvm/ADT/ScopeExit.h"
82 #include "llvm/ADT/SmallSet.h"
83 #include "llvm/ADT/SmallString.h"
84 #include "llvm/ADT/SmallVector.h"
85 #include "llvm/ADT/StringMap.h"
86 #include "llvm/ADT/StringRef.h"
87 #include "llvm/Bitcode/BitCodes.h"
88 #include "llvm/Bitcode/BitstreamWriter.h"
89 #include "llvm/Support/Casting.h"
90 #include "llvm/Support/Compression.h"
91 #include "llvm/Support/DJB.h"
92 #include "llvm/Support/Endian.h"
93 #include "llvm/Support/EndianStream.h"
94 #include "llvm/Support/Error.h"
95 #include "llvm/Support/ErrorHandling.h"
96 #include "llvm/Support/MemoryBuffer.h"
97 #include "llvm/Support/OnDiskHashTable.h"
98 #include "llvm/Support/Path.h"
99 #include "llvm/Support/SHA1.h"
100 #include "llvm/Support/VersionTuple.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include <algorithm>
103 #include <cassert>
104 #include <cstdint>
105 #include <cstdlib>
106 #include <cstring>
107 #include <ctime>
108 #include <deque>
109 #include <limits>
110 #include <memory>
111 #include <queue>
112 #include <tuple>
113 #include <utility>
114 #include <vector>
115 
116 using namespace clang;
117 using namespace clang::serialization;
118 
119 template <typename T, typename Allocator>
120 static StringRef bytes(const std::vector<T, Allocator> &v) {
121  if (v.empty()) return StringRef();
122  return StringRef(reinterpret_cast<const char*>(&v[0]),
123  sizeof(T) * v.size());
124 }
125 
126 template <typename T>
127 static StringRef bytes(const SmallVectorImpl<T> &v) {
128  return StringRef(reinterpret_cast<const char*>(v.data()),
129  sizeof(T) * v.size());
130 }
131 
132 //===----------------------------------------------------------------------===//
133 // Type serialization
134 //===----------------------------------------------------------------------===//
135 
136 namespace clang {
137 
139  ASTWriter &Writer;
140  ASTRecordWriter Record;
141 
142  /// Type code that corresponds to the record generated.
143  TypeCode Code = static_cast<TypeCode>(0);
144 
145  /// Abbreviation to use for the record, if any.
146  unsigned AbbrevToUse = 0;
147 
148  public:
150  : Writer(Writer), Record(Writer, Record) {}
151 
152  uint64_t Emit() {
153  return Record.Emit(Code, AbbrevToUse);
154  }
155 
156  void Visit(QualType T) {
157  if (T.hasLocalNonFastQualifiers()) {
160  Record.push_back(Qs.getAsOpaqueValue());
161  Code = TYPE_EXT_QUAL;
162  AbbrevToUse = Writer.TypeExtQualAbbrev;
163  } else {
164  switch (T->getTypeClass()) {
165  // For all of the concrete, non-dependent types, call the
166  // appropriate visitor function.
167 #define TYPE(Class, Base) \
168  case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
169 #define ABSTRACT_TYPE(Class, Base)
170 #include "clang/AST/TypeNodes.def"
171  }
172  }
173  }
174 
175  void VisitArrayType(const ArrayType *T);
176  void VisitFunctionType(const FunctionType *T);
177  void VisitTagType(const TagType *T);
178 
179 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
180 #define ABSTRACT_TYPE(Class, Base)
181 #include "clang/AST/TypeNodes.def"
182  };
183 
184 } // namespace clang
185 
186 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
187  llvm_unreachable("Built-in types are never serialized");
188 }
189 
190 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
191  Record.AddTypeRef(T->getElementType());
192  Code = TYPE_COMPLEX;
193 }
194 
195 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
196  Record.AddTypeRef(T->getPointeeType());
197  Code = TYPE_POINTER;
198 }
199 
200 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
201  Record.AddTypeRef(T->getOriginalType());
202  Code = TYPE_DECAYED;
203 }
204 
205 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
206  Record.AddTypeRef(T->getOriginalType());
207  Record.AddTypeRef(T->getAdjustedType());
208  Code = TYPE_ADJUSTED;
209 }
210 
211 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
212  Record.AddTypeRef(T->getPointeeType());
213  Code = TYPE_BLOCK_POINTER;
214 }
215 
216 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
217  Record.AddTypeRef(T->getPointeeTypeAsWritten());
218  Record.push_back(T->isSpelledAsLValue());
219  Code = TYPE_LVALUE_REFERENCE;
220 }
221 
222 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
223  Record.AddTypeRef(T->getPointeeTypeAsWritten());
224  Code = TYPE_RVALUE_REFERENCE;
225 }
226 
227 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
228  Record.AddTypeRef(T->getPointeeType());
229  Record.AddTypeRef(QualType(T->getClass(), 0));
230  Code = TYPE_MEMBER_POINTER;
231 }
232 
234  Record.AddTypeRef(T->getElementType());
235  Record.push_back(T->getSizeModifier()); // FIXME: stable values
236  Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
237 }
238 
239 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
240  VisitArrayType(T);
241  Record.AddAPInt(T->getSize());
242  Code = TYPE_CONSTANT_ARRAY;
243 }
244 
245 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
246  VisitArrayType(T);
247  Code = TYPE_INCOMPLETE_ARRAY;
248 }
249 
250 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
251  VisitArrayType(T);
252  Record.AddSourceLocation(T->getLBracketLoc());
253  Record.AddSourceLocation(T->getRBracketLoc());
254  Record.AddStmt(T->getSizeExpr());
255  Code = TYPE_VARIABLE_ARRAY;
256 }
257 
258 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
259  Record.AddTypeRef(T->getElementType());
260  Record.push_back(T->getNumElements());
261  Record.push_back(T->getVectorKind());
262  Code = TYPE_VECTOR;
263 }
264 
265 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
266  VisitVectorType(T);
267  Code = TYPE_EXT_VECTOR;
268 }
269 
271  Record.AddTypeRef(T->getReturnType());
273  Record.push_back(C.getNoReturn());
274  Record.push_back(C.getHasRegParm());
275  Record.push_back(C.getRegParm());
276  // FIXME: need to stabilize encoding of calling convention...
277  Record.push_back(C.getCC());
278  Record.push_back(C.getProducesResult());
279  Record.push_back(C.getNoCallerSavedRegs());
280  Record.push_back(C.getNoCfCheck());
281 
282  if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
283  AbbrevToUse = 0;
284 }
285 
286 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
287  VisitFunctionType(T);
288  Code = TYPE_FUNCTION_NO_PROTO;
289 }
290 
291 static void addExceptionSpec(const FunctionProtoType *T,
292  ASTRecordWriter &Record) {
293  Record.push_back(T->getExceptionSpecType());
294  if (T->getExceptionSpecType() == EST_Dynamic) {
295  Record.push_back(T->getNumExceptions());
296  for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
297  Record.AddTypeRef(T->getExceptionType(I));
298  } else if (isComputedNoexcept(T->getExceptionSpecType())) {
299  Record.AddStmt(T->getNoexceptExpr());
300  } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
301  Record.AddDeclRef(T->getExceptionSpecDecl());
303  } else if (T->getExceptionSpecType() == EST_Unevaluated) {
304  Record.AddDeclRef(T->getExceptionSpecDecl());
305  }
306 }
307 
308 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
309  VisitFunctionType(T);
310 
311  Record.push_back(T->isVariadic());
312  Record.push_back(T->hasTrailingReturn());
313  Record.push_back(T->getTypeQuals());
314  Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
315  addExceptionSpec(T, Record);
316 
317  Record.push_back(T->getNumParams());
318  for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
319  Record.AddTypeRef(T->getParamType(I));
320 
321  if (T->hasExtParameterInfos()) {
322  for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
323  Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
324  }
325 
326  if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
329  AbbrevToUse = 0;
330 
331  Code = TYPE_FUNCTION_PROTO;
332 }
333 
334 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
335  Record.AddDeclRef(T->getDecl());
336  Code = TYPE_UNRESOLVED_USING;
337 }
338 
339 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
340  Record.AddDeclRef(T->getDecl());
341  assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
342  Record.AddTypeRef(T->getCanonicalTypeInternal());
343  Code = TYPE_TYPEDEF;
344 }
345 
346 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
347  Record.AddStmt(T->getUnderlyingExpr());
348  Code = TYPE_TYPEOF_EXPR;
349 }
350 
351 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
352  Record.AddTypeRef(T->getUnderlyingType());
353  Code = TYPE_TYPEOF;
354 }
355 
356 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
357  Record.AddTypeRef(T->getUnderlyingType());
358  Record.AddStmt(T->getUnderlyingExpr());
359  Code = TYPE_DECLTYPE;
360 }
361 
362 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
363  Record.AddTypeRef(T->getBaseType());
364  Record.AddTypeRef(T->getUnderlyingType());
365  Record.push_back(T->getUTTKind());
366  Code = TYPE_UNARY_TRANSFORM;
367 }
368 
369 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
370  Record.AddTypeRef(T->getDeducedType());
371  Record.push_back((unsigned)T->getKeyword());
372  if (T->getDeducedType().isNull())
373  Record.push_back(T->isDependentType());
374  Code = TYPE_AUTO;
375 }
376 
377 void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
379  Record.AddTemplateName(T->getTemplateName());
380  Record.AddTypeRef(T->getDeducedType());
381  if (T->getDeducedType().isNull())
382  Record.push_back(T->isDependentType());
384 }
385 
387  Record.push_back(T->isDependentType());
388  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
389  assert(!T->isBeingDefined() &&
390  "Cannot serialize in the middle of a type definition");
391 }
392 
393 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
394  VisitTagType(T);
395  Code = TYPE_RECORD;
396 }
397 
398 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
399  VisitTagType(T);
400  Code = TYPE_ENUM;
401 }
402 
403 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
404  Record.AddTypeRef(T->getModifiedType());
405  Record.AddTypeRef(T->getEquivalentType());
406  Record.push_back(T->getAttrKind());
407  Code = TYPE_ATTRIBUTED;
408 }
409 
410 void
411 ASTTypeWriter::VisitSubstTemplateTypeParmType(
412  const SubstTemplateTypeParmType *T) {
413  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
414  Record.AddTypeRef(T->getReplacementType());
416 }
417 
418 void
419 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
421  Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
422  Record.AddTemplateArgument(T->getArgumentPack());
424 }
425 
426 void
427 ASTTypeWriter::VisitTemplateSpecializationType(
428  const TemplateSpecializationType *T) {
429  Record.push_back(T->isDependentType());
430  Record.AddTemplateName(T->getTemplateName());
431  Record.push_back(T->getNumArgs());
432  for (const auto &ArgI : *T)
433  Record.AddTemplateArgument(ArgI);
434  Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
435  : T->isCanonicalUnqualified()
436  ? QualType()
437  : T->getCanonicalTypeInternal());
439 }
440 
441 void
442 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
443  VisitArrayType(T);
444  Record.AddStmt(T->getSizeExpr());
445  Record.AddSourceRange(T->getBracketsRange());
447 }
448 
449 void
450 ASTTypeWriter::VisitDependentSizedExtVectorType(
451  const DependentSizedExtVectorType *T) {
452  Record.AddTypeRef(T->getElementType());
453  Record.AddStmt(T->getSizeExpr());
454  Record.AddSourceLocation(T->getAttributeLoc());
456 }
457 
458 void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) {
459  Record.AddTypeRef(T->getElementType());
460  Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
461  Record.AddSourceLocation(T->getAttributeLoc());
462  Record.push_back(T->getVectorKind());
464 }
465 
466 void
467 ASTTypeWriter::VisitDependentAddressSpaceType(
468  const DependentAddressSpaceType *T) {
469  Record.AddTypeRef(T->getPointeeType());
470  Record.AddStmt(T->getAddrSpaceExpr());
471  Record.AddSourceLocation(T->getAttributeLoc());
473 }
474 
475 void
476 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
477  Record.push_back(T->getDepth());
478  Record.push_back(T->getIndex());
479  Record.push_back(T->isParameterPack());
480  Record.AddDeclRef(T->getDecl());
482 }
483 
484 void
485 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
486  Record.push_back(T->getKeyword());
487  Record.AddNestedNameSpecifier(T->getQualifier());
488  Record.AddIdentifierRef(T->getIdentifier());
489  Record.AddTypeRef(
491  Code = TYPE_DEPENDENT_NAME;
492 }
493 
494 void
495 ASTTypeWriter::VisitDependentTemplateSpecializationType(
497  Record.push_back(T->getKeyword());
498  Record.AddNestedNameSpecifier(T->getQualifier());
499  Record.AddIdentifierRef(T->getIdentifier());
500  Record.push_back(T->getNumArgs());
501  for (const auto &I : *T)
502  Record.AddTemplateArgument(I);
504 }
505 
506 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
507  Record.AddTypeRef(T->getPattern());
508  if (Optional<unsigned> NumExpansions = T->getNumExpansions())
509  Record.push_back(*NumExpansions + 1);
510  else
511  Record.push_back(0);
512  Code = TYPE_PACK_EXPANSION;
513 }
514 
515 void ASTTypeWriter::VisitParenType(const ParenType *T) {
516  Record.AddTypeRef(T->getInnerType());
517  Code = TYPE_PAREN;
518 }
519 
520 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
521  Record.push_back(T->getKeyword());
522  Record.AddNestedNameSpecifier(T->getQualifier());
523  Record.AddTypeRef(T->getNamedType());
524  Record.AddDeclRef(T->getOwnedTagDecl());
525  Code = TYPE_ELABORATED;
526 }
527 
528 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
529  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
530  Record.AddTypeRef(T->getInjectedSpecializationType());
532 }
533 
534 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
535  Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
536  Code = TYPE_OBJC_INTERFACE;
537 }
538 
539 void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
540  Record.AddDeclRef(T->getDecl());
541  Record.push_back(T->getNumProtocols());
542  for (const auto *I : T->quals())
543  Record.AddDeclRef(I);
544  Code = TYPE_OBJC_TYPE_PARAM;
545 }
546 
547 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
548  Record.AddTypeRef(T->getBaseType());
549  Record.push_back(T->getTypeArgsAsWritten().size());
550  for (auto TypeArg : T->getTypeArgsAsWritten())
551  Record.AddTypeRef(TypeArg);
552  Record.push_back(T->getNumProtocols());
553  for (const auto *I : T->quals())
554  Record.AddDeclRef(I);
555  Record.push_back(T->isKindOfTypeAsWritten());
556  Code = TYPE_OBJC_OBJECT;
557 }
558 
559 void
560 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
561  Record.AddTypeRef(T->getPointeeType());
563 }
564 
565 void
566 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
567  Record.AddTypeRef(T->getValueType());
568  Code = TYPE_ATOMIC;
569 }
570 
571 void
572 ASTTypeWriter::VisitPipeType(const PipeType *T) {
573  Record.AddTypeRef(T->getElementType());
574  Record.push_back(T->isReadOnly());
575  Code = TYPE_PIPE;
576 }
577 
578 namespace {
579 
580 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
581  ASTRecordWriter &Record;
582 
583 public:
584  TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
585 
586 #define ABSTRACT_TYPELOC(CLASS, PARENT)
587 #define TYPELOC(CLASS, PARENT) \
588  void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
589 #include "clang/AST/TypeLocNodes.def"
590 
591  void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
592  void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
593 };
594 
595 } // namespace
596 
597 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
598  // nothing to do
599 }
600 
601 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
602  Record.AddSourceLocation(TL.getBuiltinLoc());
603  if (TL.needsExtraLocalData()) {
604  Record.push_back(TL.getWrittenTypeSpec());
605  Record.push_back(TL.getWrittenSignSpec());
606  Record.push_back(TL.getWrittenWidthSpec());
607  Record.push_back(TL.hasModeAttr());
608  }
609 }
610 
611 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
612  Record.AddSourceLocation(TL.getNameLoc());
613 }
614 
615 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
616  Record.AddSourceLocation(TL.getStarLoc());
617 }
618 
619 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
620  // nothing to do
621 }
622 
623 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
624  // nothing to do
625 }
626 
627 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
628  Record.AddSourceLocation(TL.getCaretLoc());
629 }
630 
631 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
632  Record.AddSourceLocation(TL.getAmpLoc());
633 }
634 
635 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
636  Record.AddSourceLocation(TL.getAmpAmpLoc());
637 }
638 
639 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
640  Record.AddSourceLocation(TL.getStarLoc());
641  Record.AddTypeSourceInfo(TL.getClassTInfo());
642 }
643 
644 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
645  Record.AddSourceLocation(TL.getLBracketLoc());
646  Record.AddSourceLocation(TL.getRBracketLoc());
647  Record.push_back(TL.getSizeExpr() ? 1 : 0);
648  if (TL.getSizeExpr())
649  Record.AddStmt(TL.getSizeExpr());
650 }
651 
652 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
653  VisitArrayTypeLoc(TL);
654 }
655 
656 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
657  VisitArrayTypeLoc(TL);
658 }
659 
660 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
661  VisitArrayTypeLoc(TL);
662 }
663 
664 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
666  VisitArrayTypeLoc(TL);
667 }
668 
669 void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
671  Record.AddSourceLocation(TL.getAttrNameLoc());
673  Record.AddSourceLocation(range.getBegin());
674  Record.AddSourceLocation(range.getEnd());
675  Record.AddStmt(TL.getAttrExprOperand());
676 }
677 
678 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
680  Record.AddSourceLocation(TL.getNameLoc());
681 }
682 
683 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
684  Record.AddSourceLocation(TL.getNameLoc());
685 }
686 
687 void TypeLocWriter::VisitDependentVectorTypeLoc(
689  Record.AddSourceLocation(TL.getNameLoc());
690 }
691 
692 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
693  Record.AddSourceLocation(TL.getNameLoc());
694 }
695 
696 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
697  Record.AddSourceLocation(TL.getLocalRangeBegin());
698  Record.AddSourceLocation(TL.getLParenLoc());
699  Record.AddSourceLocation(TL.getRParenLoc());
700  Record.AddSourceRange(TL.getExceptionSpecRange());
701  Record.AddSourceLocation(TL.getLocalRangeEnd());
702  for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
703  Record.AddDeclRef(TL.getParam(i));
704 }
705 
706 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
707  VisitFunctionTypeLoc(TL);
708 }
709 
710 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
711  VisitFunctionTypeLoc(TL);
712 }
713 
714 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
715  Record.AddSourceLocation(TL.getNameLoc());
716 }
717 
718 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
719  Record.AddSourceLocation(TL.getNameLoc());
720 }
721 
722 void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
723  if (TL.getNumProtocols()) {
724  Record.AddSourceLocation(TL.getProtocolLAngleLoc());
725  Record.AddSourceLocation(TL.getProtocolRAngleLoc());
726  }
727  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
728  Record.AddSourceLocation(TL.getProtocolLoc(i));
729 }
730 
731 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
732  Record.AddSourceLocation(TL.getTypeofLoc());
733  Record.AddSourceLocation(TL.getLParenLoc());
734  Record.AddSourceLocation(TL.getRParenLoc());
735 }
736 
737 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
738  Record.AddSourceLocation(TL.getTypeofLoc());
739  Record.AddSourceLocation(TL.getLParenLoc());
740  Record.AddSourceLocation(TL.getRParenLoc());
741  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
742 }
743 
744 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
745  Record.AddSourceLocation(TL.getNameLoc());
746 }
747 
748 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
749  Record.AddSourceLocation(TL.getKWLoc());
750  Record.AddSourceLocation(TL.getLParenLoc());
751  Record.AddSourceLocation(TL.getRParenLoc());
752  Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
753 }
754 
755 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
756  Record.AddSourceLocation(TL.getNameLoc());
757 }
758 
759 void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
761  Record.AddSourceLocation(TL.getTemplateNameLoc());
762 }
763 
764 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
765  Record.AddSourceLocation(TL.getNameLoc());
766 }
767 
768 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
769  Record.AddSourceLocation(TL.getNameLoc());
770 }
771 
772 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
773  Record.AddAttr(TL.getAttr());
774 }
775 
776 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
777  Record.AddSourceLocation(TL.getNameLoc());
778 }
779 
780 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
782  Record.AddSourceLocation(TL.getNameLoc());
783 }
784 
785 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
787  Record.AddSourceLocation(TL.getNameLoc());
788 }
789 
790 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
792  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
793  Record.AddSourceLocation(TL.getTemplateNameLoc());
794  Record.AddSourceLocation(TL.getLAngleLoc());
795  Record.AddSourceLocation(TL.getRAngleLoc());
796  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
797  Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
798  TL.getArgLoc(i).getLocInfo());
799 }
800 
801 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
802  Record.AddSourceLocation(TL.getLParenLoc());
803  Record.AddSourceLocation(TL.getRParenLoc());
804 }
805 
806 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
807  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
808  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
809 }
810 
811 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
812  Record.AddSourceLocation(TL.getNameLoc());
813 }
814 
815 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
816  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
817  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
818  Record.AddSourceLocation(TL.getNameLoc());
819 }
820 
821 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
823  Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
824  Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
825  Record.AddSourceLocation(TL.getTemplateKeywordLoc());
826  Record.AddSourceLocation(TL.getTemplateNameLoc());
827  Record.AddSourceLocation(TL.getLAngleLoc());
828  Record.AddSourceLocation(TL.getRAngleLoc());
829  for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
830  Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
831  TL.getArgLoc(I).getLocInfo());
832 }
833 
834 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
835  Record.AddSourceLocation(TL.getEllipsisLoc());
836 }
837 
838 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
839  Record.AddSourceLocation(TL.getNameLoc());
840 }
841 
842 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
843  Record.push_back(TL.hasBaseTypeAsWritten());
844  Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
845  Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
846  for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
847  Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
848  Record.AddSourceLocation(TL.getProtocolLAngleLoc());
849  Record.AddSourceLocation(TL.getProtocolRAngleLoc());
850  for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
851  Record.AddSourceLocation(TL.getProtocolLoc(i));
852 }
853 
854 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
855  Record.AddSourceLocation(TL.getStarLoc());
856 }
857 
858 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
859  Record.AddSourceLocation(TL.getKWLoc());
860  Record.AddSourceLocation(TL.getLParenLoc());
861  Record.AddSourceLocation(TL.getRParenLoc());
862 }
863 
864 void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
865  Record.AddSourceLocation(TL.getKWLoc());
866 }
867 
868 void ASTWriter::WriteTypeAbbrevs() {
869  using namespace llvm;
870 
871  std::shared_ptr<BitCodeAbbrev> Abv;
872 
873  // Abbreviation for TYPE_EXT_QUAL
874  Abv = std::make_shared<BitCodeAbbrev>();
875  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
876  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
877  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
878  TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
879 
880  // Abbreviation for TYPE_FUNCTION_PROTO
881  Abv = std::make_shared<BitCodeAbbrev>();
882  Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
883  // FunctionType
884  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
885  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
886  Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
887  Abv->Add(BitCodeAbbrevOp(0)); // RegParm
888  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
889  Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
890  Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
891  Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
892  // FunctionProtoType
893  Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
894  Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
895  Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
896  Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
897  Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
898  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
899  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
900  Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
901  TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
902 }
903 
904 //===----------------------------------------------------------------------===//
905 // ASTWriter Implementation
906 //===----------------------------------------------------------------------===//
907 
908 static void EmitBlockID(unsigned ID, const char *Name,
909  llvm::BitstreamWriter &Stream,
910  ASTWriter::RecordDataImpl &Record) {
911  Record.clear();
912  Record.push_back(ID);
913  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
914 
915  // Emit the block name if present.
916  if (!Name || Name[0] == 0)
917  return;
918  Record.clear();
919  while (*Name)
920  Record.push_back(*Name++);
921  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
922 }
923 
924 static void EmitRecordID(unsigned ID, const char *Name,
925  llvm::BitstreamWriter &Stream,
926  ASTWriter::RecordDataImpl &Record) {
927  Record.clear();
928  Record.push_back(ID);
929  while (*Name)
930  Record.push_back(*Name++);
931  Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
932 }
933 
934 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
935  ASTWriter::RecordDataImpl &Record) {
936 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
937  RECORD(STMT_STOP);
940  RECORD(STMT_NULL);
942  RECORD(STMT_CASE);
946  RECORD(STMT_IF);
949  RECORD(STMT_DO);
950  RECORD(STMT_FOR);
951  RECORD(STMT_GOTO);
956  RECORD(STMT_DECL);
971  RECORD(EXPR_CALL);
987  RECORD(EXPR_STMT);
1060 #undef RECORD
1061 }
1062 
1063 void ASTWriter::WriteBlockInfoBlock() {
1064  RecordData Record;
1065  Stream.EnterBlockInfoBlock();
1066 
1067 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
1068 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
1069 
1070  // Control Block.
1071  BLOCK(CONTROL_BLOCK);
1072  RECORD(METADATA);
1076  RECORD(IMPORTS);
1081 
1082  BLOCK(OPTIONS_BLOCK);
1088 
1089  BLOCK(INPUT_FILES_BLOCK);
1090  RECORD(INPUT_FILE);
1091 
1092  // AST Top-Level Block.
1093  BLOCK(AST_BLOCK);
1101  RECORD(STATISTICS);
1146 
1147  // SourceManager Block.
1148  BLOCK(SOURCE_MANAGER_BLOCK);
1154 
1155  // Preprocessor Block.
1156  BLOCK(PREPROCESSOR_BLOCK);
1161  RECORD(PP_TOKEN);
1162 
1163  // Submodule Block.
1164  BLOCK(SUBMODULE_BLOCK);
1183 
1184  // Comments Block.
1185  BLOCK(COMMENTS_BLOCK);
1187 
1188  // Decls and Types block.
1189  BLOCK(DECLTYPES_BLOCK);
1208  RECORD(TYPE_ENUM);
1222  RECORD(TYPE_PAREN);
1226  RECORD(TYPE_AUTO);
1235  RECORD(DECL_ENUM);
1250  RECORD(DECL_FIELD);
1252  RECORD(DECL_VAR);
1256  RECORD(DECL_BLOCK);
1261  RECORD(DECL_USING);
1296  RECORD(DECL_EMPTY);
1302 
1303  // Statements and Exprs can occur in the Decls and Types block.
1304  AddStmtsExprs(Stream, Record);
1305 
1306  BLOCK(PREPROCESSOR_DETAIL_BLOCK);
1310 
1311  // Decls and Types block.
1312  BLOCK(EXTENSION_BLOCK);
1314 
1315  BLOCK(UNHASHED_CONTROL_BLOCK);
1316  RECORD(SIGNATURE);
1319 
1320 #undef RECORD
1321 #undef BLOCK
1322  Stream.ExitBlock();
1323 }
1324 
1325 /// Prepares a path for being written to an AST file by converting it
1326 /// to an absolute path and removing nested './'s.
1327 ///
1328 /// \return \c true if the path was changed.
1329 static bool cleanPathForOutput(FileManager &FileMgr,
1330  SmallVectorImpl<char> &Path) {
1331  bool Changed = FileMgr.makeAbsolutePath(Path);
1332  return Changed | llvm::sys::path::remove_dots(Path);
1333 }
1334 
1335 /// Adjusts the given filename to only write out the portion of the
1336 /// filename that is not part of the system root directory.
1337 ///
1338 /// \param Filename the file name to adjust.
1339 ///
1340 /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
1341 /// the returned filename will be adjusted by this root directory.
1342 ///
1343 /// \returns either the original filename (if it needs no adjustment) or the
1344 /// adjusted filename (which points into the @p Filename parameter).
1345 static const char *
1346 adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
1347  assert(Filename && "No file name to adjust?");
1348 
1349  if (BaseDir.empty())
1350  return Filename;
1351 
1352  // Verify that the filename and the system root have the same prefix.
1353  unsigned Pos = 0;
1354  for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
1355  if (Filename[Pos] != BaseDir[Pos])
1356  return Filename; // Prefixes don't match.
1357 
1358  // We hit the end of the filename before we hit the end of the system root.
1359  if (!Filename[Pos])
1360  return Filename;
1361 
1362  // If there's not a path separator at the end of the base directory nor
1363  // immediately after it, then this isn't within the base directory.
1364  if (!llvm::sys::path::is_separator(Filename[Pos])) {
1365  if (!llvm::sys::path::is_separator(BaseDir.back()))
1366  return Filename;
1367  } else {
1368  // If the file name has a '/' at the current position, skip over the '/'.
1369  // We distinguish relative paths from absolute paths by the
1370  // absence of '/' at the beginning of relative paths.
1371  //
1372  // FIXME: This is wrong. We distinguish them by asking if the path is
1373  // absolute, which isn't the same thing. And there might be multiple '/'s
1374  // in a row. Use a better mechanism to indicate whether we have emitted an
1375  // absolute or relative path.
1376  ++Pos;
1377  }
1378 
1379  return Filename + Pos;
1380 }
1381 
1382 ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
1383  // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
1384  llvm::SHA1 Hasher;
1385  Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
1386  auto Hash = Hasher.result();
1387 
1388  // Convert to an array [5*i32].
1389  ASTFileSignature Signature;
1390  auto LShift = [&](unsigned char Val, unsigned Shift) {
1391  return (uint32_t)Val << Shift;
1392  };
1393  for (int I = 0; I != 5; ++I)
1394  Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
1395  LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
1396 
1397  return Signature;
1398 }
1399 
1400 ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
1401  ASTContext &Context) {
1402  // Flush first to prepare the PCM hash (signature).
1403  Stream.FlushToWord();
1404  auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
1405 
1406  // Enter the block and prepare to write records.
1407  RecordData Record;
1408  Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
1409 
1410  // For implicit modules, write the hash of the PCM as its signature.
1411  ASTFileSignature Signature;
1412  if (WritingModule &&
1414  Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
1415  Record.append(Signature.begin(), Signature.end());
1416  Stream.EmitRecord(SIGNATURE, Record);
1417  Record.clear();
1418  }
1419 
1420  // Diagnostic options.
1421  const auto &Diags = Context.getDiagnostics();
1422  const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
1423 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1424 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1425  Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1426 #include "clang/Basic/DiagnosticOptions.def"
1427  Record.push_back(DiagOpts.Warnings.size());
1428  for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1429  AddString(DiagOpts.Warnings[I], Record);
1430  Record.push_back(DiagOpts.Remarks.size());
1431  for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
1432  AddString(DiagOpts.Remarks[I], Record);
1433  // Note: we don't serialize the log or serialization file names, because they
1434  // are generally transient files and will almost always be overridden.
1435  Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1436 
1437  // Write out the diagnostic/pragma mappings.
1438  WritePragmaDiagnosticMappings(Diags, /* IsModule = */ WritingModule);
1439 
1440  // Leave the options block.
1441  Stream.ExitBlock();
1442  return Signature;
1443 }
1444 
1445 /// Write the control block.
1446 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1447  StringRef isysroot,
1448  const std::string &OutputFile) {
1449  using namespace llvm;
1450 
1451  Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1452  RecordData Record;
1453 
1454  // Metadata
1455  auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
1456  MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1457  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1458  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1459  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1460  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1461  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1462  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
1463  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
1464  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1465  MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1466  unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
1467  assert((!WritingModule || isysroot.empty()) &&
1468  "writing module as a relocatable PCH?");
1469  {
1470  RecordData::value_type Record[] = {
1471  METADATA,
1472  VERSION_MAJOR,
1473  VERSION_MINOR,
1474  CLANG_VERSION_MAJOR,
1475  CLANG_VERSION_MINOR,
1476  !isysroot.empty(),
1477  IncludeTimestamps,
1478  Context.getLangOpts().BuildingPCHWithObjectFile,
1479  ASTHasCompilerErrors};
1480  Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1482  }
1483 
1484  if (WritingModule) {
1485  // Module name
1486  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1487  Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1488  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1489  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1490  RecordData::value_type Record[] = {MODULE_NAME};
1491  Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1492  }
1493 
1494  if (WritingModule && WritingModule->Directory) {
1495  SmallString<128> BaseDir(WritingModule->Directory->getName());
1496  cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
1497 
1498  // If the home of the module is the current working directory, then we
1499  // want to pick up the cwd of the build process loading the module, not
1500  // our cwd, when we load this module.
1501  if (!PP.getHeaderSearchInfo()
1504  WritingModule->Directory->getName() != StringRef(".")) {
1505  // Module directory.
1506  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1507  Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
1508  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
1509  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1510 
1511  RecordData::value_type Record[] = {MODULE_DIRECTORY};
1512  Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
1513  }
1514 
1515  // Write out all other paths relative to the base directory if possible.
1516  BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
1517  } else if (!isysroot.empty()) {
1518  // Write out paths relative to the sysroot if possible.
1519  BaseDirectory = isysroot;
1520  }
1521 
1522  // Module map file
1523  if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
1524  Record.clear();
1525 
1526  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1527  AddPath(WritingModule->PresumedModuleMapFile.empty()
1528  ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
1529  : StringRef(WritingModule->PresumedModuleMapFile),
1530  Record);
1531 
1532  // Additional module map files.
1533  if (auto *AdditionalModMaps =
1534  Map.getAdditionalModuleMapFiles(WritingModule)) {
1535  Record.push_back(AdditionalModMaps->size());
1536  for (const FileEntry *F : *AdditionalModMaps)
1537  AddPath(F->getName(), Record);
1538  } else {
1539  Record.push_back(0);
1540  }
1541 
1542  Stream.EmitRecord(MODULE_MAP_FILE, Record);
1543  }
1544 
1545  // Imports
1546  if (Chain) {
1547  serialization::ModuleManager &Mgr = Chain->getModuleManager();
1548  Record.clear();
1549 
1550  for (ModuleFile &M : Mgr) {
1551  // Skip modules that weren't directly imported.
1552  if (!M.isDirectlyImported())
1553  continue;
1554 
1555  Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
1556  AddSourceLocation(M.ImportLoc, Record);
1557 
1558  // If we have calculated signature, there is no need to store
1559  // the size or timestamp.
1560  Record.push_back(M.Signature ? 0 : M.File->getSize());
1561  Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
1562 
1563  for (auto I : M.Signature)
1564  Record.push_back(I);
1565 
1566  AddString(M.ModuleName, Record);
1567  AddPath(M.FileName, Record);
1568  }
1569  Stream.EmitRecord(IMPORTS, Record);
1570  }
1571 
1572  // Write the options block.
1573  Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
1574 
1575  // Language options.
1576  Record.clear();
1577  const LangOptions &LangOpts = Context.getLangOpts();
1578 #define LANGOPT(Name, Bits, Default, Description) \
1579  Record.push_back(LangOpts.Name);
1580 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1581  Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1582 #include "clang/Basic/LangOptions.def"
1583 #define SANITIZER(NAME, ID) \
1584  Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
1585 #include "clang/Basic/Sanitizers.def"
1586 
1587  Record.push_back(LangOpts.ModuleFeatures.size());
1588  for (StringRef Feature : LangOpts.ModuleFeatures)
1589  AddString(Feature, Record);
1590 
1591  Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1592  AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1593 
1594  AddString(LangOpts.CurrentModule, Record);
1595 
1596  // Comment options.
1597  Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1598  for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
1599  AddString(I, Record);
1600  }
1601  Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1602 
1603  // OpenMP offloading options.
1604  Record.push_back(LangOpts.OMPTargetTriples.size());
1605  for (auto &T : LangOpts.OMPTargetTriples)
1606  AddString(T.getTriple(), Record);
1607 
1608  AddString(LangOpts.OMPHostIRFile, Record);
1609 
1610  Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1611 
1612  // Target options.
1613  Record.clear();
1614  const TargetInfo &Target = Context.getTargetInfo();
1615  const TargetOptions &TargetOpts = Target.getTargetOpts();
1616  AddString(TargetOpts.Triple, Record);
1617  AddString(TargetOpts.CPU, Record);
1618  AddString(TargetOpts.ABI, Record);
1619  Record.push_back(TargetOpts.FeaturesAsWritten.size());
1620  for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1621  AddString(TargetOpts.FeaturesAsWritten[I], Record);
1622  }
1623  Record.push_back(TargetOpts.Features.size());
1624  for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1625  AddString(TargetOpts.Features[I], Record);
1626  }
1627  Stream.EmitRecord(TARGET_OPTIONS, Record);
1628 
1629  // File system options.
1630  Record.clear();
1631  const FileSystemOptions &FSOpts =
1633  AddString(FSOpts.WorkingDir, Record);
1634  Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1635 
1636  // Header search options.
1637  Record.clear();
1638  const HeaderSearchOptions &HSOpts
1640  AddString(HSOpts.Sysroot, Record);
1641 
1642  // Include entries.
1643  Record.push_back(HSOpts.UserEntries.size());
1644  for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1645  const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1646  AddString(Entry.Path, Record);
1647  Record.push_back(static_cast<unsigned>(Entry.Group));
1648  Record.push_back(Entry.IsFramework);
1649  Record.push_back(Entry.IgnoreSysRoot);
1650  }
1651 
1652  // System header prefixes.
1653  Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1654  for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1655  AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1656  Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1657  }
1658 
1659  AddString(HSOpts.ResourceDir, Record);
1660  AddString(HSOpts.ModuleCachePath, Record);
1661  AddString(HSOpts.ModuleUserBuildPath, Record);
1662  Record.push_back(HSOpts.DisableModuleHash);
1663  Record.push_back(HSOpts.ImplicitModuleMaps);
1664  Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
1665  Record.push_back(HSOpts.UseBuiltinIncludes);
1666  Record.push_back(HSOpts.UseStandardSystemIncludes);
1667  Record.push_back(HSOpts.UseStandardCXXIncludes);
1668  Record.push_back(HSOpts.UseLibcxx);
1669  // Write out the specific module cache path that contains the module files.
1670  AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
1671  Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1672 
1673  // Preprocessor options.
1674  Record.clear();
1675  const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1676 
1677  // Macro definitions.
1678  Record.push_back(PPOpts.Macros.size());
1679  for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1680  AddString(PPOpts.Macros[I].first, Record);
1681  Record.push_back(PPOpts.Macros[I].second);
1682  }
1683 
1684  // Includes
1685  Record.push_back(PPOpts.Includes.size());
1686  for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1687  AddString(PPOpts.Includes[I], Record);
1688 
1689  // Macro includes
1690  Record.push_back(PPOpts.MacroIncludes.size());
1691  for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1692  AddString(PPOpts.MacroIncludes[I], Record);
1693 
1694  Record.push_back(PPOpts.UsePredefines);
1695  // Detailed record is important since it is used for the module cache hash.
1696  Record.push_back(PPOpts.DetailedRecord);
1697  AddString(PPOpts.ImplicitPCHInclude, Record);
1698  AddString(PPOpts.ImplicitPTHInclude, Record);
1699  Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1700  Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1701 
1702  // Leave the options block.
1703  Stream.ExitBlock();
1704 
1705  // Original file name and file ID
1706  SourceManager &SM = Context.getSourceManager();
1707  if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1708  auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
1709  FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1710  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1711  FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1712  unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
1713 
1714  Record.clear();
1715  Record.push_back(ORIGINAL_FILE);
1716  Record.push_back(SM.getMainFileID().getOpaqueValue());
1717  EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
1718  }
1719 
1720  Record.clear();
1721  Record.push_back(SM.getMainFileID().getOpaqueValue());
1722  Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1723 
1724  // Original PCH directory
1725  if (!OutputFile.empty() && OutputFile != "-") {
1726  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1727  Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1728  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1729  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
1730 
1731  SmallString<128> OutputPath(OutputFile);
1732 
1733  SM.getFileManager().makeAbsolutePath(OutputPath);
1734  StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1735 
1736  RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
1737  Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1738  }
1739 
1740  WriteInputFiles(Context.SourceMgr,
1742  PP.getLangOpts().Modules);
1743  Stream.ExitBlock();
1744 }
1745 
1746 namespace {
1747 
1748 /// An input file.
1749 struct InputFileEntry {
1750  const FileEntry *File;
1751  bool IsSystemFile;
1752  bool IsTransient;
1753  bool BufferOverridden;
1754  bool IsTopLevelModuleMap;
1755 };
1756 
1757 } // namespace
1758 
1759 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1760  HeaderSearchOptions &HSOpts,
1761  bool Modules) {
1762  using namespace llvm;
1763 
1764  Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1765 
1766  // Create input-file abbreviation.
1767  auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
1768  IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1769  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1770  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1771  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1772  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1773  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
1774  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
1775  IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1776  unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
1777 
1778  // Get all ContentCache objects for files, sorted by whether the file is a
1779  // system one or not. System files go at the back, users files at the front.
1780  std::deque<InputFileEntry> SortedFiles;
1781  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1782  // Get this source location entry.
1783  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1784  assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1785 
1786  // We only care about file entries that were not overridden.
1787  if (!SLoc->isFile())
1788  continue;
1789  const SrcMgr::FileInfo &File = SLoc->getFile();
1790  const SrcMgr::ContentCache *Cache = File.getContentCache();
1791  if (!Cache->OrigEntry)
1792  continue;
1793 
1794  InputFileEntry Entry;
1795  Entry.File = Cache->OrigEntry;
1796  Entry.IsSystemFile = Cache->IsSystemFile;
1797  Entry.IsTransient = Cache->IsTransient;
1798  Entry.BufferOverridden = Cache->BufferOverridden;
1799  Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
1800  File.getIncludeLoc().isInvalid();
1801  if (Cache->IsSystemFile)
1802  SortedFiles.push_back(Entry);
1803  else
1804  SortedFiles.push_front(Entry);
1805  }
1806 
1807  unsigned UserFilesNum = 0;
1808  // Write out all of the input files.
1809  std::vector<uint64_t> InputFileOffsets;
1810  for (const auto &Entry : SortedFiles) {
1811  uint32_t &InputFileID = InputFileIDs[Entry.File];
1812  if (InputFileID != 0)
1813  continue; // already recorded this file.
1814 
1815  // Record this entry's offset.
1816  InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1817 
1818  InputFileID = InputFileOffsets.size();
1819 
1820  if (!Entry.IsSystemFile)
1821  ++UserFilesNum;
1822 
1823  // Emit size/modification time for this file.
1824  // And whether this file was overridden.
1825  RecordData::value_type Record[] = {
1826  INPUT_FILE,
1827  InputFileOffsets.size(),
1828  (uint64_t)Entry.File->getSize(),
1829  (uint64_t)getTimestampForOutput(Entry.File),
1830  Entry.BufferOverridden,
1831  Entry.IsTransient,
1832  Entry.IsTopLevelModuleMap};
1833 
1834  EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
1835  }
1836 
1837  Stream.ExitBlock();
1838 
1839  // Create input file offsets abbreviation.
1840  auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
1841  OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1842  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1843  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1844  // input files
1845  OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
1846  unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
1847 
1848  // Write input file offsets.
1849  RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
1850  InputFileOffsets.size(), UserFilesNum};
1851  Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
1852 }
1853 
1854 //===----------------------------------------------------------------------===//
1855 // Source Manager Serialization
1856 //===----------------------------------------------------------------------===//
1857 
1858 /// Create an abbreviation for the SLocEntry that refers to a
1859 /// file.
1860 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1861  using namespace llvm;
1862 
1863  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1864  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1865  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1866  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1867  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1868  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1869  // FileEntry fields.
1870  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1871  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1872  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1873  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1874  return Stream.EmitAbbrev(std::move(Abbrev));
1875 }
1876 
1877 /// Create an abbreviation for the SLocEntry that refers to a
1878 /// buffer.
1879 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1880  using namespace llvm;
1881 
1882  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1883  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1884  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1885  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1886  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
1887  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1888  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1889  return Stream.EmitAbbrev(std::move(Abbrev));
1890 }
1891 
1892 /// Create an abbreviation for the SLocEntry that refers to a
1893 /// buffer's blob.
1894 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
1895  bool Compressed) {
1896  using namespace llvm;
1897 
1898  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1899  Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
1900  : SM_SLOC_BUFFER_BLOB));
1901  if (Compressed)
1902  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
1903  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1904  return Stream.EmitAbbrev(std::move(Abbrev));
1905 }
1906 
1907 /// Create an abbreviation for the SLocEntry that refers to a macro
1908 /// expansion.
1909 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1910  using namespace llvm;
1911 
1912  auto Abbrev = std::make_shared<BitCodeAbbrev>();
1913  Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1914  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1915  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1916  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1917  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1918  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
1919  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1920  return Stream.EmitAbbrev(std::move(Abbrev));
1921 }
1922 
1923 namespace {
1924 
1925  // Trait used for the on-disk hash table of header search information.
1926  class HeaderFileInfoTrait {
1927  ASTWriter &Writer;
1928 
1929  // Keep track of the framework names we've used during serialization.
1930  SmallVector<char, 128> FrameworkStringData;
1931  llvm::StringMap<unsigned> FrameworkNameOffset;
1932 
1933  public:
1934  HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
1935 
1936  struct key_type {
1937  StringRef Filename;
1938  off_t Size;
1939  time_t ModTime;
1940  };
1941  using key_type_ref = const key_type &;
1942 
1943  using UnresolvedModule =
1944  llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
1945 
1946  struct data_type {
1947  const HeaderFileInfo &HFI;
1948  ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
1949  UnresolvedModule Unresolved;
1950  };
1951  using data_type_ref = const data_type &;
1952 
1953  using hash_value_type = unsigned;
1954  using offset_type = unsigned;
1955 
1956  hash_value_type ComputeHash(key_type_ref key) {
1957  // The hash is based only on size/time of the file, so that the reader can
1958  // match even when symlinking or excess path elements ("foo/../", "../")
1959  // change the form of the name. However, complete path is still the key.
1960  return llvm::hash_combine(key.Size, key.ModTime);
1961  }
1962 
1963  std::pair<unsigned, unsigned>
1964  EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1965  using namespace llvm::support;
1966 
1967  endian::Writer LE(Out, little);
1968  unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
1969  LE.write<uint16_t>(KeyLen);
1970  unsigned DataLen = 1 + 2 + 4 + 4;
1971  for (auto ModInfo : Data.KnownHeaders)
1972  if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
1973  DataLen += 4;
1974  if (Data.Unresolved.getPointer())
1975  DataLen += 4;
1976  LE.write<uint8_t>(DataLen);
1977  return std::make_pair(KeyLen, DataLen);
1978  }
1979 
1980  void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1981  using namespace llvm::support;
1982 
1983  endian::Writer LE(Out, little);
1984  LE.write<uint64_t>(key.Size);
1985  KeyLen -= 8;
1986  LE.write<uint64_t>(key.ModTime);
1987  KeyLen -= 8;
1988  Out.write(key.Filename.data(), KeyLen);
1989  }
1990 
1991  void EmitData(raw_ostream &Out, key_type_ref key,
1992  data_type_ref Data, unsigned DataLen) {
1993  using namespace llvm::support;
1994 
1995  endian::Writer LE(Out, little);
1996  uint64_t Start = Out.tell(); (void)Start;
1997 
1998  unsigned char Flags = (Data.HFI.isImport << 5)
1999  | (Data.HFI.isPragmaOnce << 4)
2000  | (Data.HFI.DirInfo << 1)
2001  | Data.HFI.IndexHeaderMapHeader;
2002  LE.write<uint8_t>(Flags);
2003  LE.write<uint16_t>(Data.HFI.NumIncludes);
2004 
2005  if (!Data.HFI.ControllingMacro)
2006  LE.write<uint32_t>(Data.HFI.ControllingMacroID);
2007  else
2008  LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
2009 
2010  unsigned Offset = 0;
2011  if (!Data.HFI.Framework.empty()) {
2012  // If this header refers into a framework, save the framework name.
2013  llvm::StringMap<unsigned>::iterator Pos
2014  = FrameworkNameOffset.find(Data.HFI.Framework);
2015  if (Pos == FrameworkNameOffset.end()) {
2016  Offset = FrameworkStringData.size() + 1;
2017  FrameworkStringData.append(Data.HFI.Framework.begin(),
2018  Data.HFI.Framework.end());
2019  FrameworkStringData.push_back(0);
2020 
2021  FrameworkNameOffset[Data.HFI.Framework] = Offset;
2022  } else
2023  Offset = Pos->second;
2024  }
2025  LE.write<uint32_t>(Offset);
2026 
2027  auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
2028  if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
2029  uint32_t Value = (ModID << 2) | (unsigned)Role;
2030  assert((Value >> 2) == ModID && "overflow in header module info");
2031  LE.write<uint32_t>(Value);
2032  }
2033  };
2034 
2035  // FIXME: If the header is excluded, we should write out some
2036  // record of that fact.
2037  for (auto ModInfo : Data.KnownHeaders)
2038  EmitModule(ModInfo.getModule(), ModInfo.getRole());
2039  if (Data.Unresolved.getPointer())
2040  EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
2041 
2042  assert(Out.tell() - Start == DataLen && "Wrong data length");
2043  }
2044 
2045  const char *strings_begin() const { return FrameworkStringData.begin(); }
2046  const char *strings_end() const { return FrameworkStringData.end(); }
2047  };
2048 
2049 } // namespace
2050 
2051 /// Write the header search block for the list of files that
2052 ///
2053 /// \param HS The header search structure to save.
2054 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
2055  HeaderFileInfoTrait GeneratorTrait(*this);
2056  llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
2057  SmallVector<const char *, 4> SavedStrings;
2058  unsigned NumHeaderSearchEntries = 0;
2059 
2060  // Find all unresolved headers for the current module. We generally will
2061  // have resolved them before we get here, but not necessarily: we might be
2062  // compiling a preprocessed module, where there is no requirement for the
2063  // original files to exist any more.
2064  const HeaderFileInfo Empty; // So we can take a reference.
2065  if (WritingModule) {
2066  llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
2067  while (!Worklist.empty()) {
2068  Module *M = Worklist.pop_back_val();
2069  if (!M->isAvailable())
2070  continue;
2071 
2072  // Map to disk files where possible, to pick up any missing stat
2073  // information. This also means we don't need to check the unresolved
2074  // headers list when emitting resolved headers in the first loop below.
2075  // FIXME: It'd be preferable to avoid doing this if we were given
2076  // sufficient stat information in the module map.
2078 
2079  // If the file didn't exist, we can still create a module if we were given
2080  // enough information in the module map.
2081  for (auto U : M->MissingHeaders) {
2082  // Check that we were given enough information to build a module
2083  // without this file existing on disk.
2084  if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
2085  PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
2086  << WritingModule->getFullModuleName() << U.Size.hasValue()
2087  << U.FileName;
2088  continue;
2089  }
2090 
2091  // Form the effective relative pathname for the file.
2093  llvm::sys::path::append(Filename, U.FileName);
2094  PreparePathForOutput(Filename);
2095 
2096  StringRef FilenameDup = strdup(Filename.c_str());
2097  SavedStrings.push_back(FilenameDup.data());
2098 
2099  HeaderFileInfoTrait::key_type Key = {
2100  FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
2101  };
2102  HeaderFileInfoTrait::data_type Data = {
2103  Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
2104  };
2105  // FIXME: Deal with cases where there are multiple unresolved header
2106  // directives in different submodules for the same header.
2107  Generator.insert(Key, Data, GeneratorTrait);
2108  ++NumHeaderSearchEntries;
2109  }
2110 
2111  Worklist.append(M->submodule_begin(), M->submodule_end());
2112  }
2113  }
2114 
2116  HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
2117 
2118  if (FilesByUID.size() > HS.header_file_size())
2119  FilesByUID.resize(HS.header_file_size());
2120 
2121  for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
2122  const FileEntry *File = FilesByUID[UID];
2123  if (!File)
2124  continue;
2125 
2126  // Get the file info. This will load info from the external source if
2127  // necessary. Skip emitting this file if we have no information on it
2128  // as a header file (in which case HFI will be null) or if it hasn't
2129  // changed since it was loaded. Also skip it if it's for a modular header
2130  // from a different module; in that case, we rely on the module(s)
2131  // containing the header to provide this information.
2132  const HeaderFileInfo *HFI =
2133  HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
2134  if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
2135  continue;
2136 
2137  // Massage the file path into an appropriate form.
2138  StringRef Filename = File->getName();
2139  SmallString<128> FilenameTmp(Filename);
2140  if (PreparePathForOutput(FilenameTmp)) {
2141  // If we performed any translation on the file name at all, we need to
2142  // save this string, since the generator will refer to it later.
2143  Filename = StringRef(strdup(FilenameTmp.c_str()));
2144  SavedStrings.push_back(Filename.data());
2145  }
2146 
2147  HeaderFileInfoTrait::key_type Key = {
2148  Filename, File->getSize(), getTimestampForOutput(File)
2149  };
2150  HeaderFileInfoTrait::data_type Data = {
2151  *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
2152  };
2153  Generator.insert(Key, Data, GeneratorTrait);
2154  ++NumHeaderSearchEntries;
2155  }
2156 
2157  // Create the on-disk hash table in a buffer.
2158  SmallString<4096> TableData;
2159  uint32_t BucketOffset;
2160  {
2161  using namespace llvm::support;
2162 
2163  llvm::raw_svector_ostream Out(TableData);
2164  // Make sure that no bucket is at offset 0
2165  endian::write<uint32_t>(Out, 0, little);
2166  BucketOffset = Generator.Emit(Out, GeneratorTrait);
2167  }
2168 
2169  // Create a blob abbreviation
2170  using namespace llvm;
2171 
2172  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2173  Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
2174  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2175  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2176  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2177  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2178  unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2179 
2180  // Write the header search table
2181  RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
2182  NumHeaderSearchEntries, TableData.size()};
2183  TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
2184  Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
2185 
2186  // Free all of the strings we had to duplicate.
2187  for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
2188  free(const_cast<char *>(SavedStrings[I]));
2189 }
2190 
2191 static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
2192  unsigned SLocBufferBlobCompressedAbbrv,
2193  unsigned SLocBufferBlobAbbrv) {
2194  using RecordDataType = ASTWriter::RecordData::value_type;
2195 
2196  // Compress the buffer if possible. We expect that almost all PCM
2197  // consumers will not want its contents.
2198  SmallString<0> CompressedBuffer;
2199  if (llvm::zlib::isAvailable()) {
2200  llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
2201  if (!E) {
2202  RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
2203  Blob.size() - 1};
2204  Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
2205  CompressedBuffer);
2206  return;
2207  }
2208  llvm::consumeError(std::move(E));
2209  }
2210 
2211  RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
2212  Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
2213 }
2214 
2215 /// Writes the block containing the serialized form of the
2216 /// source manager.
2217 ///
2218 /// TODO: We should probably use an on-disk hash table (stored in a
2219 /// blob), indexed based on the file name, so that we only create
2220 /// entries for files that we actually need. In the common case (no
2221 /// errors), we probably won't have to create file entries for any of
2222 /// the files in the AST.
2223 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
2224  const Preprocessor &PP) {
2225  RecordData Record;
2226 
2227  // Enter the source manager block.
2228  Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
2229 
2230  // Abbreviations for the various kinds of source-location entries.
2231  unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
2232  unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
2233  unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
2234  unsigned SLocBufferBlobCompressedAbbrv =
2235  CreateSLocBufferBlobAbbrev(Stream, true);
2236  unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
2237 
2238  // Write out the source location entry table. We skip the first
2239  // entry, which is always the same dummy entry.
2240  std::vector<uint32_t> SLocEntryOffsets;
2241  RecordData PreloadSLocs;
2242  SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
2243  for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
2244  I != N; ++I) {
2245  // Get this source location entry.
2246  const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
2247  FileID FID = FileID::get(I);
2248  assert(&SourceMgr.getSLocEntry(FID) == SLoc);
2249 
2250  // Record the offset of this source-location entry.
2251  SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
2252 
2253  // Figure out which record code to use.
2254  unsigned Code;
2255  if (SLoc->isFile()) {
2257  if (Cache->OrigEntry) {
2258  Code = SM_SLOC_FILE_ENTRY;
2259  } else
2260  Code = SM_SLOC_BUFFER_ENTRY;
2261  } else
2262  Code = SM_SLOC_EXPANSION_ENTRY;
2263  Record.clear();
2264  Record.push_back(Code);
2265 
2266  // Starting offset of this entry within this module, so skip the dummy.
2267  Record.push_back(SLoc->getOffset() - 2);
2268  if (SLoc->isFile()) {
2269  const SrcMgr::FileInfo &File = SLoc->getFile();
2270  AddSourceLocation(File.getIncludeLoc(), Record);
2271  Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
2272  Record.push_back(File.hasLineDirectives());
2273 
2274  const SrcMgr::ContentCache *Content = File.getContentCache();
2275  bool EmitBlob = false;
2276  if (Content->OrigEntry) {
2277  assert(Content->OrigEntry == Content->ContentsEntry &&
2278  "Writing to AST an overridden file is not supported");
2279 
2280  // The source location entry is a file. Emit input file ID.
2281  assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
2282  Record.push_back(InputFileIDs[Content->OrigEntry]);
2283 
2284  Record.push_back(File.NumCreatedFIDs);
2285 
2286  FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
2287  if (FDI != FileDeclIDs.end()) {
2288  Record.push_back(FDI->second->FirstDeclIndex);
2289  Record.push_back(FDI->second->DeclIDs.size());
2290  } else {
2291  Record.push_back(0);
2292  Record.push_back(0);
2293  }
2294 
2295  Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
2296 
2297  if (Content->BufferOverridden || Content->IsTransient)
2298  EmitBlob = true;
2299  } else {
2300  // The source location entry is a buffer. The blob associated
2301  // with this entry contains the contents of the buffer.
2302 
2303  // We add one to the size so that we capture the trailing NULL
2304  // that is required by llvm::MemoryBuffer::getMemBuffer (on
2305  // the reader side).
2306  const llvm::MemoryBuffer *Buffer
2307  = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2308  StringRef Name = Buffer->getBufferIdentifier();
2309  Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
2310  StringRef(Name.data(), Name.size() + 1));
2311  EmitBlob = true;
2312 
2313  if (Name == "<built-in>")
2314  PreloadSLocs.push_back(SLocEntryOffsets.size());
2315  }
2316 
2317  if (EmitBlob) {
2318  // Include the implicit terminating null character in the on-disk buffer
2319  // if we're writing it uncompressed.
2320  const llvm::MemoryBuffer *Buffer =
2321  Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
2322  StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
2323  emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
2324  SLocBufferBlobAbbrv);
2325  }
2326  } else {
2327  // The source location entry is a macro expansion.
2328  const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
2329  AddSourceLocation(Expansion.getSpellingLoc(), Record);
2330  AddSourceLocation(Expansion.getExpansionLocStart(), Record);
2331  AddSourceLocation(Expansion.isMacroArgExpansion()
2332  ? SourceLocation()
2333  : Expansion.getExpansionLocEnd(),
2334  Record);
2335  Record.push_back(Expansion.isExpansionTokenRange());
2336 
2337  // Compute the token length for this macro expansion.
2338  unsigned NextOffset = SourceMgr.getNextLocalOffset();
2339  if (I + 1 != N)
2340  NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
2341  Record.push_back(NextOffset - SLoc->getOffset() - 1);
2342  Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
2343  }
2344  }
2345 
2346  Stream.ExitBlock();
2347 
2348  if (SLocEntryOffsets.empty())
2349  return;
2350 
2351  // Write the source-location offsets table into the AST block. This
2352  // table is used for lazily loading source-location information.
2353  using namespace llvm;
2354 
2355  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2356  Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
2357  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
2358  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
2359  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
2360  unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2361  {
2362  RecordData::value_type Record[] = {
2363  SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
2364  SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
2365  Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
2366  bytes(SLocEntryOffsets));
2367  }
2368  // Write the source location entry preloads array, telling the AST
2369  // reader which source locations entries it should load eagerly.
2370  Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
2371 
2372  // Write the line table. It depends on remapping working, so it must come
2373  // after the source location offsets.
2374  if (SourceMgr.hasLineTable()) {
2375  LineTableInfo &LineTable = SourceMgr.getLineTable();
2376 
2377  Record.clear();
2378 
2379  // Emit the needed file names.
2380  llvm::DenseMap<int, int> FilenameMap;
2381  FilenameMap[-1] = -1; // For unspecified filenames.
2382  for (const auto &L : LineTable) {
2383  if (L.first.ID < 0)
2384  continue;
2385  for (auto &LE : L.second) {
2386  if (FilenameMap.insert(std::make_pair(LE.FilenameID,
2387  FilenameMap.size() - 1)).second)
2388  AddPath(LineTable.getFilename(LE.FilenameID), Record);
2389  }
2390  }
2391  Record.push_back(0);
2392 
2393  // Emit the line entries
2394  for (const auto &L : LineTable) {
2395  // Only emit entries for local files.
2396  if (L.first.ID < 0)
2397  continue;
2398 
2399  // Emit the file ID
2400  Record.push_back(L.first.ID);
2401 
2402  // Emit the line entries
2403  Record.push_back(L.second.size());
2404  for (const auto &LE : L.second) {
2405  Record.push_back(LE.FileOffset);
2406  Record.push_back(LE.LineNo);
2407  Record.push_back(FilenameMap[LE.FilenameID]);
2408  Record.push_back((unsigned)LE.FileKind);
2409  Record.push_back(LE.IncludeOffset);
2410  }
2411  }
2412 
2413  Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
2414  }
2415 }
2416 
2417 //===----------------------------------------------------------------------===//
2418 // Preprocessor Serialization
2419 //===----------------------------------------------------------------------===//
2420 
2421 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
2422  const Preprocessor &PP) {
2423  if (MacroInfo *MI = MD->getMacroInfo())
2424  if (MI->isBuiltinMacro())
2425  return true;
2426 
2427  if (IsModule) {
2428  SourceLocation Loc = MD->getLocation();
2429  if (Loc.isInvalid())
2430  return true;
2431  if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
2432  return true;
2433  }
2434 
2435  return false;
2436 }
2437 
2438 /// Writes the block containing the serialized form of the
2439 /// preprocessor.
2440 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
2442  if (PPRec)
2443  WritePreprocessorDetail(*PPRec);
2444 
2445  RecordData Record;
2446  RecordData ModuleMacroRecord;
2447 
2448  // If the preprocessor __COUNTER__ value has been bumped, remember it.
2449  if (PP.getCounterValue() != 0) {
2450  RecordData::value_type Record[] = {PP.getCounterValue()};
2451  Stream.EmitRecord(PP_COUNTER_VALUE, Record);
2452  }
2453 
2454  if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
2455  assert(!IsModule);
2456  auto SkipInfo = PP.getPreambleSkipInfo();
2457  if (SkipInfo.hasValue()) {
2458  Record.push_back(true);
2459  AddSourceLocation(SkipInfo->HashTokenLoc, Record);
2460  AddSourceLocation(SkipInfo->IfTokenLoc, Record);
2461  Record.push_back(SkipInfo->FoundNonSkipPortion);
2462  Record.push_back(SkipInfo->FoundElse);
2463  AddSourceLocation(SkipInfo->ElseLoc, Record);
2464  } else {
2465  Record.push_back(false);
2466  }
2467  for (const auto &Cond : PP.getPreambleConditionalStack()) {
2468  AddSourceLocation(Cond.IfLoc, Record);
2469  Record.push_back(Cond.WasSkipping);
2470  Record.push_back(Cond.FoundNonSkip);
2471  Record.push_back(Cond.FoundElse);
2472  }
2473  Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
2474  Record.clear();
2475  }
2476 
2477  // Enter the preprocessor block.
2478  Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
2479 
2480  // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
2481  // FIXME: Include a location for the use, and say which one was used.
2482  if (PP.SawDateOrTime())
2483  PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
2484 
2485  // Loop over all the macro directives that are live at the end of the file,
2486  // emitting each to the PP section.
2487 
2488  // Construct the list of identifiers with macro directives that need to be
2489  // serialized.
2491  for (auto &Id : PP.getIdentifierTable())
2492  if (Id.second->hadMacroDefinition() &&
2493  (!Id.second->isFromAST() ||
2494  Id.second->hasChangedSinceDeserialization()))
2495  MacroIdentifiers.push_back(Id.second);
2496  // Sort the set of macro definitions that need to be serialized by the
2497  // name of the macro, to provide a stable ordering.
2498  llvm::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
2499  llvm::less_ptr<IdentifierInfo>());
2500 
2501  // Emit the macro directives as a list and associate the offset with the
2502  // identifier they belong to.
2503  for (const IdentifierInfo *Name : MacroIdentifiers) {
2505  auto StartOffset = Stream.GetCurrentBitNo();
2506 
2507  // Emit the macro directives in reverse source order.
2508  for (; MD; MD = MD->getPrevious()) {
2509  // Once we hit an ignored macro, we're done: the rest of the chain
2510  // will all be ignored macros.
2511  if (shouldIgnoreMacro(MD, IsModule, PP))
2512  break;
2513 
2514  AddSourceLocation(MD->getLocation(), Record);
2515  Record.push_back(MD->getKind());
2516  if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
2517  Record.push_back(getMacroRef(DefMD->getInfo(), Name));
2518  } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
2519  Record.push_back(VisMD->isPublic());
2520  }
2521  }
2522 
2523  // Write out any exported module macros.
2524  bool EmittedModuleMacros = false;
2525  // We write out exported module macros for PCH as well.
2526  auto Leafs = PP.getLeafModuleMacros(Name);
2527  SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
2528  llvm::DenseMap<ModuleMacro*, unsigned> Visits;
2529  while (!Worklist.empty()) {
2530  auto *Macro = Worklist.pop_back_val();
2531 
2532  // Emit a record indicating this submodule exports this macro.
2533  ModuleMacroRecord.push_back(
2534  getSubmoduleID(Macro->getOwningModule()));
2535  ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
2536  for (auto *M : Macro->overrides())
2537  ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
2538 
2539  Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
2540  ModuleMacroRecord.clear();
2541 
2542  // Enqueue overridden macros once we've visited all their ancestors.
2543  for (auto *M : Macro->overrides())
2544  if (++Visits[M] == M->getNumOverridingMacros())
2545  Worklist.push_back(M);
2546 
2547  EmittedModuleMacros = true;
2548  }
2549 
2550  if (Record.empty() && !EmittedModuleMacros)
2551  continue;
2552 
2553  IdentMacroDirectivesOffsetMap[Name] = StartOffset;
2554  Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2555  Record.clear();
2556  }
2557 
2558  /// Offsets of each of the macros into the bitstream, indexed by
2559  /// the local macro ID
2560  ///
2561  /// For each identifier that is associated with a macro, this map
2562  /// provides the offset into the bitstream where that macro is
2563  /// defined.
2564  std::vector<uint32_t> MacroOffsets;
2565 
2566  for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2567  const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2568  MacroInfo *MI = MacroInfosToEmit[I].MI;
2569  MacroID ID = MacroInfosToEmit[I].ID;
2570 
2571  if (ID < FirstMacroID) {
2572  assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2573  continue;
2574  }
2575 
2576  // Record the local offset of this macro.
2577  unsigned Index = ID - FirstMacroID;
2578  if (Index == MacroOffsets.size())
2579  MacroOffsets.push_back(Stream.GetCurrentBitNo());
2580  else {
2581  if (Index > MacroOffsets.size())
2582  MacroOffsets.resize(Index + 1);
2583 
2584  MacroOffsets[Index] = Stream.GetCurrentBitNo();
2585  }
2586 
2587  AddIdentifierRef(Name, Record);
2588  AddSourceLocation(MI->getDefinitionLoc(), Record);
2589  AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2590  Record.push_back(MI->isUsed());
2591  Record.push_back(MI->isUsedForHeaderGuard());
2592  unsigned Code;
2593  if (MI->isObjectLike()) {
2594  Code = PP_MACRO_OBJECT_LIKE;
2595  } else {
2596  Code = PP_MACRO_FUNCTION_LIKE;
2597 
2598  Record.push_back(MI->isC99Varargs());
2599  Record.push_back(MI->isGNUVarargs());
2600  Record.push_back(MI->hasCommaPasting());
2601  Record.push_back(MI->getNumParams());
2602  for (const IdentifierInfo *Param : MI->params())
2603  AddIdentifierRef(Param, Record);
2604  }
2605 
2606  // If we have a detailed preprocessing record, record the macro definition
2607  // ID that corresponds to this macro.
2608  if (PPRec)
2609  Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2610 
2611  Stream.EmitRecord(Code, Record);
2612  Record.clear();
2613 
2614  // Emit the tokens array.
2615  for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2616  // Note that we know that the preprocessor does not have any annotation
2617  // tokens in it because they are created by the parser, and thus can't
2618  // be in a macro definition.
2619  const Token &Tok = MI->getReplacementToken(TokNo);
2620  AddToken(Tok, Record);
2621  Stream.EmitRecord(PP_TOKEN, Record);
2622  Record.clear();
2623  }
2624  ++NumMacros;
2625  }
2626 
2627  Stream.ExitBlock();
2628 
2629  // Write the offsets table for macro IDs.
2630  using namespace llvm;
2631 
2632  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2633  Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2634  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2635  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2636  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2637 
2638  unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2639  {
2640  RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
2641  FirstMacroID - NUM_PREDEF_MACRO_IDS};
2642  Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
2643  }
2644 }
2645 
2646 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2647  if (PPRec.local_begin() == PPRec.local_end())
2648  return;
2649 
2650  SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2651 
2652  // Enter the preprocessor block.
2653  Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2654 
2655  // If the preprocessor has a preprocessing record, emit it.
2656  unsigned NumPreprocessingRecords = 0;
2657  using namespace llvm;
2658 
2659  // Set up the abbreviation for
2660  unsigned InclusionAbbrev = 0;
2661  {
2662  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2663  Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2664  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2665  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2666  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2667  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2668  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2669  InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2670  }
2671 
2672  unsigned FirstPreprocessorEntityID
2673  = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2675  unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2676  RecordData Record;
2677  for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2678  EEnd = PPRec.local_end();
2679  E != EEnd;
2680  (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2681  Record.clear();
2682 
2683  PreprocessedEntityOffsets.push_back(
2684  PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
2685 
2686  if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
2687  // Record this macro definition's ID.
2688  MacroDefinitions[MD] = NextPreprocessorEntityID;
2689 
2690  AddIdentifierRef(MD->getName(), Record);
2691  Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2692  continue;
2693  }
2694 
2695  if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
2696  Record.push_back(ME->isBuiltinMacro());
2697  if (ME->isBuiltinMacro())
2698  AddIdentifierRef(ME->getName(), Record);
2699  else
2700  Record.push_back(MacroDefinitions[ME->getDefinition()]);
2701  Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2702  continue;
2703  }
2704 
2705  if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
2706  Record.push_back(PPD_INCLUSION_DIRECTIVE);
2707  Record.push_back(ID->getFileName().size());
2708  Record.push_back(ID->wasInQuotes());
2709  Record.push_back(static_cast<unsigned>(ID->getKind()));
2710  Record.push_back(ID->importedModule());
2711  SmallString<64> Buffer;
2712  Buffer += ID->getFileName();
2713  // Check that the FileEntry is not null because it was not resolved and
2714  // we create a PCH even with compiler errors.
2715  if (ID->getFile())
2716  Buffer += ID->getFile()->getName();
2717  Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2718  continue;
2719  }
2720 
2721  llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2722  }
2723  Stream.ExitBlock();
2724 
2725  // Write the offsets table for the preprocessing record.
2726  if (NumPreprocessingRecords > 0) {
2727  assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2728 
2729  // Write the offsets table for identifier IDs.
2730  using namespace llvm;
2731 
2732  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2733  Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2734  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2735  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2736  unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2737 
2738  RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
2739  FirstPreprocessorEntityID -
2741  Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2742  bytes(PreprocessedEntityOffsets));
2743  }
2744 
2745  // Write the skipped region table for the preprocessing record.
2746  ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
2747  if (SkippedRanges.size() > 0) {
2748  std::vector<PPSkippedRange> SerializedSkippedRanges;
2749  SerializedSkippedRanges.reserve(SkippedRanges.size());
2750  for (auto const& Range : SkippedRanges)
2751  SerializedSkippedRanges.emplace_back(Range);
2752 
2753  using namespace llvm;
2754  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2755  Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
2756  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2757  unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2758 
2759  Record.clear();
2760  Record.push_back(PPD_SKIPPED_RANGES);
2761  Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
2762  bytes(SerializedSkippedRanges));
2763  }
2764 }
2765 
2767  if (!Mod)
2768  return 0;
2769 
2770  llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2771  if (Known != SubmoduleIDs.end())
2772  return Known->second;
2773 
2774  auto *Top = Mod->getTopLevelModule();
2775  if (Top != WritingModule &&
2776  (getLangOpts().CompilingPCH ||
2777  !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
2778  return 0;
2779 
2780  return SubmoduleIDs[Mod] = NextSubmoduleID++;
2781 }
2782 
2783 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2784  // FIXME: This can easily happen, if we have a reference to a submodule that
2785  // did not result in us loading a module file for that submodule. For
2786  // instance, a cross-top-level-module 'conflict' declaration will hit this.
2787  unsigned ID = getLocalOrImportedSubmoduleID(Mod);
2788  assert((ID || !Mod) &&
2789  "asked for module ID for non-local, non-imported module");
2790  return ID;
2791 }
2792 
2793 /// Compute the number of modules within the given tree (including the
2794 /// given module).
2795 static unsigned getNumberOfModules(Module *Mod) {
2796  unsigned ChildModules = 0;
2797  for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
2798  Sub != SubEnd; ++Sub)
2799  ChildModules += getNumberOfModules(*Sub);
2800 
2801  return ChildModules + 1;
2802 }
2803 
2804 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2805  // Enter the submodule description block.
2806  Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
2807 
2808  // Write the abbreviations needed for the submodules block.
2809  using namespace llvm;
2810 
2811  auto Abbrev = std::make_shared<BitCodeAbbrev>();
2812  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2813  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2814  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2815  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
2816  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2817  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2818  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2819  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2820  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2821  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2822  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2823  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2824  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
2825  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2826  unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2827 
2828  Abbrev = std::make_shared<BitCodeAbbrev>();
2829  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2830  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2831  unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2832 
2833  Abbrev = std::make_shared<BitCodeAbbrev>();
2834  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2835  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2836  unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2837 
2838  Abbrev = std::make_shared<BitCodeAbbrev>();
2839  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2840  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2841  unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2842 
2843  Abbrev = std::make_shared<BitCodeAbbrev>();
2844  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2845  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2846  unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2847 
2848  Abbrev = std::make_shared<BitCodeAbbrev>();
2849  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2850  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2851  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
2852  unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2853 
2854  Abbrev = std::make_shared<BitCodeAbbrev>();
2855  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2856  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2857  unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2858 
2859  Abbrev = std::make_shared<BitCodeAbbrev>();
2860  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
2861  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2862  unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2863 
2864  Abbrev = std::make_shared<BitCodeAbbrev>();
2865  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2866  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2867  unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2868 
2869  Abbrev = std::make_shared<BitCodeAbbrev>();
2870  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
2871  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2872  unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2873 
2874  Abbrev = std::make_shared<BitCodeAbbrev>();
2875  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2876  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2877  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2878  unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2879 
2880  Abbrev = std::make_shared<BitCodeAbbrev>();
2881  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2882  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2883  unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2884 
2885  Abbrev = std::make_shared<BitCodeAbbrev>();
2886  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2887  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
2888  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
2889  unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2890 
2891  Abbrev = std::make_shared<BitCodeAbbrev>();
2892  Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
2893  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
2894  unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
2895 
2896  // Write the submodule metadata block.
2897  RecordData::value_type Record[] = {
2898  getNumberOfModules(WritingModule),
2899  FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
2900  Stream.EmitRecord(SUBMODULE_METADATA, Record);
2901 
2902  // Write all of the submodules.
2903  std::queue<Module *> Q;
2904  Q.push(WritingModule);
2905  while (!Q.empty()) {
2906  Module *Mod = Q.front();
2907  Q.pop();
2908  unsigned ID = getSubmoduleID(Mod);
2909 
2910  uint64_t ParentID = 0;
2911  if (Mod->Parent) {
2912  assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2913  ParentID = SubmoduleIDs[Mod->Parent];
2914  }
2915 
2916  // Emit the definition of the block.
2917  {
2918  RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
2919  ID,
2920  ParentID,
2921  (RecordData::value_type)Mod->Kind,
2922  Mod->IsFramework,
2923  Mod->IsExplicit,
2924  Mod->IsSystem,
2925  Mod->IsExternC,
2926  Mod->InferSubmodules,
2928  Mod->InferExportWildcard,
2930  Mod->ModuleMapIsPrivate};
2931  Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2932  }
2933 
2934  // Emit the requirements.
2935  for (const auto &R : Mod->Requirements) {
2936  RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
2937  Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
2938  }
2939 
2940  // Emit the umbrella header, if there is one.
2941  if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
2942  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
2943  Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2944  UmbrellaHeader.NameAsWritten);
2945  } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
2946  RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
2947  Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2948  UmbrellaDir.NameAsWritten);
2949  }
2950 
2951  // Emit the headers.
2952  struct {
2953  unsigned RecordKind;
2954  unsigned Abbrev;
2955  Module::HeaderKind HeaderKind;
2956  } HeaderLists[] = {
2957  {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
2958  {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
2959  {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
2960  {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
2962  {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
2963  };
2964  for (auto &HL : HeaderLists) {
2965  RecordData::value_type Record[] = {HL.RecordKind};
2966  for (auto &H : Mod->Headers[HL.HeaderKind])
2967  Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
2968  }
2969 
2970  // Emit the top headers.
2971  {
2972  auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2973  RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
2974  for (auto *H : TopHeaders)
2975  Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
2976  }
2977 
2978  // Emit the imports.
2979  if (!Mod->Imports.empty()) {
2980  RecordData Record;
2981  for (auto *I : Mod->Imports)
2982  Record.push_back(getSubmoduleID(I));
2983  Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2984  }
2985 
2986  // Emit the exports.
2987  if (!Mod->Exports.empty()) {
2988  RecordData Record;
2989  for (const auto &E : Mod->Exports) {
2990  // FIXME: This may fail; we don't require that all exported modules
2991  // are local or imported.
2992  Record.push_back(getSubmoduleID(E.getPointer()));
2993  Record.push_back(E.getInt());
2994  }
2995  Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2996  }
2997 
2998  //FIXME: How do we emit the 'use'd modules? They may not be submodules.
2999  // Might be unnecessary as use declarations are only used to build the
3000  // module itself.
3001 
3002  // Emit the link libraries.
3003  for (const auto &LL : Mod->LinkLibraries) {
3004  RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
3005  LL.IsFramework};
3006  Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
3007  }
3008 
3009  // Emit the conflicts.
3010  for (const auto &C : Mod->Conflicts) {
3011  // FIXME: This may fail; we don't require that all conflicting modules
3012  // are local or imported.
3013  RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
3014  getSubmoduleID(C.Other)};
3015  Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
3016  }
3017 
3018  // Emit the configuration macros.
3019  for (const auto &CM : Mod->ConfigMacros) {
3020  RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
3021  Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
3022  }
3023 
3024  // Emit the initializers, if any.
3025  RecordData Inits;
3026  for (Decl *D : Context->getModuleInitializers(Mod))
3027  Inits.push_back(GetDeclRef(D));
3028  if (!Inits.empty())
3029  Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
3030 
3031  // Emit the name of the re-exported module, if any.
3032  if (!Mod->ExportAsModule.empty()) {
3033  RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
3034  Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
3035  }
3036 
3037  // Queue up the submodules of this module.
3038  for (auto *M : Mod->submodules())
3039  Q.push(M);
3040  }
3041 
3042  Stream.ExitBlock();
3043 
3044  assert((NextSubmoduleID - FirstSubmoduleID ==
3045  getNumberOfModules(WritingModule)) &&
3046  "Wrong # of submodules; found a reference to a non-local, "
3047  "non-imported submodule?");
3048 }
3049 
3050 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
3051  bool isModule) {
3052  llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
3053  DiagStateIDMap;
3054  unsigned CurrID = 0;
3055  RecordData Record;
3056 
3057  auto EncodeDiagStateFlags =
3058  [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
3059  unsigned Result = (unsigned)DS->ExtBehavior;
3060  for (unsigned Val :
3061  {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
3062  (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
3063  (unsigned)DS->SuppressSystemWarnings})
3064  Result = (Result << 1) | Val;
3065  return Result;
3066  };
3067 
3068  unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
3069  Record.push_back(Flags);
3070 
3071  auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
3072  bool IncludeNonPragmaStates) {
3073  // Ensure that the diagnostic state wasn't modified since it was created.
3074  // We will not correctly round-trip this information otherwise.
3075  assert(Flags == EncodeDiagStateFlags(State) &&
3076  "diag state flags vary in single AST file");
3077 
3078  unsigned &DiagStateID = DiagStateIDMap[State];
3079  Record.push_back(DiagStateID);
3080 
3081  if (DiagStateID == 0) {
3082  DiagStateID = ++CurrID;
3083 
3084  // Add a placeholder for the number of mappings.
3085  auto SizeIdx = Record.size();
3086  Record.emplace_back();
3087  for (const auto &I : *State) {
3088  if (I.second.isPragma() || IncludeNonPragmaStates) {
3089  Record.push_back(I.first);
3090  Record.push_back(I.second.serialize());
3091  }
3092  }
3093  // Update the placeholder.
3094  Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
3095  }
3096  };
3097 
3098  AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
3099 
3100  // Reserve a spot for the number of locations with state transitions.
3101  auto NumLocationsIdx = Record.size();
3102  Record.emplace_back();
3103 
3104  // Emit the state transitions.
3105  unsigned NumLocations = 0;
3106  for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
3107  if (!FileIDAndFile.first.isValid() ||
3108  !FileIDAndFile.second.HasLocalTransitions)
3109  continue;
3110  ++NumLocations;
3111 
3112  SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
3113  assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
3114  AddSourceLocation(Loc, Record);
3115 
3116  Record.push_back(FileIDAndFile.second.StateTransitions.size());
3117  for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
3118  Record.push_back(StatePoint.Offset);
3119  AddDiagState(StatePoint.State, false);
3120  }
3121  }
3122 
3123  // Backpatch the number of locations.
3124  Record[NumLocationsIdx] = NumLocations;
3125 
3126  // Emit CurDiagStateLoc. Do it last in order to match source order.
3127  //
3128  // This also protects against a hypothetical corner case with simulating
3129  // -Werror settings for implicit modules in the ASTReader, where reading
3130  // CurDiagState out of context could change whether warning pragmas are
3131  // treated as errors.
3132  AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
3133  AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
3134 
3135  Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
3136 }
3137 
3138 //===----------------------------------------------------------------------===//
3139 // Type Serialization
3140 //===----------------------------------------------------------------------===//
3141 
3142 /// Write the representation of a type to the AST stream.
3143 void ASTWriter::WriteType(QualType T) {
3144  TypeIdx &IdxRef = TypeIdxs[T];
3145  if (IdxRef.getIndex() == 0) // we haven't seen this type before.
3146  IdxRef = TypeIdx(NextTypeID++);
3147  TypeIdx Idx = IdxRef;
3148 
3149  assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
3150 
3151  RecordData Record;
3152 
3153  // Emit the type's representation.
3154  ASTTypeWriter W(*this, Record);
3155  W.Visit(T);
3156  uint64_t Offset = W.Emit();
3157 
3158  // Record the offset for this type.
3159  unsigned Index = Idx.getIndex() - FirstTypeID;
3160  if (TypeOffsets.size() == Index)
3161  TypeOffsets.push_back(Offset);
3162  else if (TypeOffsets.size() < Index) {
3163  TypeOffsets.resize(Index + 1);
3164  TypeOffsets[Index] = Offset;
3165  } else {
3166  llvm_unreachable("Types emitted in wrong order");
3167  }
3168 }
3169 
3170 //===----------------------------------------------------------------------===//
3171 // Declaration Serialization
3172 //===----------------------------------------------------------------------===//
3173 
3174 /// Write the block containing all of the declaration IDs
3175 /// lexically declared within the given DeclContext.
3176 ///
3177 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
3178 /// bitstream, or 0 if no block was written.
3179 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
3180  DeclContext *DC) {
3181  if (DC->decls_empty())
3182  return 0;
3183 
3184  uint64_t Offset = Stream.GetCurrentBitNo();
3185  SmallVector<uint32_t, 128> KindDeclPairs;
3186  for (const auto *D : DC->decls()) {
3187  KindDeclPairs.push_back(D->getKind());
3188  KindDeclPairs.push_back(GetDeclRef(D));
3189  }
3190 
3191  ++NumLexicalDeclContexts;
3192  RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
3193  Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
3194  bytes(KindDeclPairs));
3195  return Offset;
3196 }
3197 
3198 void ASTWriter::WriteTypeDeclOffsets() {
3199  using namespace llvm;
3200 
3201  // Write the type offsets array
3202  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3203  Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
3204  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
3205  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
3206  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
3207  unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3208  {
3209  RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
3210  FirstTypeID - NUM_PREDEF_TYPE_IDS};
3211  Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
3212  }
3213 
3214  // Write the declaration offsets array
3215  Abbrev = std::make_shared<BitCodeAbbrev>();
3216  Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
3217  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
3218  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
3219  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
3220  unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3221  {
3222  RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
3223  FirstDeclID - NUM_PREDEF_DECL_IDS};
3224  Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
3225  }
3226 }
3227 
3228 void ASTWriter::WriteFileDeclIDsMap() {
3229  using namespace llvm;
3230 
3232  FileDeclIDs.begin(), FileDeclIDs.end());
3233  llvm::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
3234  llvm::less_first());
3235 
3236  // Join the vectors of DeclIDs from all files.
3237  SmallVector<DeclID, 256> FileGroupedDeclIDs;
3238  for (auto &FileDeclEntry : SortedFileDeclIDs) {
3239  DeclIDInFileInfo &Info = *FileDeclEntry.second;
3240  Info.FirstDeclIndex = FileGroupedDeclIDs.size();
3241  for (auto &LocDeclEntry : Info.DeclIDs)
3242  FileGroupedDeclIDs.push_back(LocDeclEntry.second);
3243  }
3244 
3245  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3246  Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
3247  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3248  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3249  unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
3250  RecordData::value_type Record[] = {FILE_SORTED_DECLS,
3251  FileGroupedDeclIDs.size()};
3252  Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
3253 }
3254 
3255 void ASTWriter::WriteComments() {
3256  Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
3257  auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
3259  return;
3260  ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
3261  RecordData Record;
3262  for (const auto *I : RawComments) {
3263  Record.clear();
3264  AddSourceRange(I->getSourceRange(), Record);
3265  Record.push_back(I->getKind());
3266  Record.push_back(I->isTrailingComment());
3267  Record.push_back(I->isAlmostTrailingComment());
3268  Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
3269  }
3270 }
3271 
3272 //===----------------------------------------------------------------------===//
3273 // Global Method Pool and Selector Serialization
3274 //===----------------------------------------------------------------------===//
3275 
3276 namespace {
3277 
3278 // Trait used for the on-disk hash table used in the method pool.
3279 class ASTMethodPoolTrait {
3280  ASTWriter &Writer;
3281 
3282 public:
3283  using key_type = Selector;
3284  using key_type_ref = key_type;
3285 
3286  struct data_type {
3287  SelectorID ID;
3288  ObjCMethodList Instance, Factory;
3289  };
3290  using data_type_ref = const data_type &;
3291 
3292  using hash_value_type = unsigned;
3293  using offset_type = unsigned;
3294 
3295  explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
3296 
3297  static hash_value_type ComputeHash(Selector Sel) {
3298  return serialization::ComputeHash(Sel);
3299  }
3300 
3301  std::pair<unsigned, unsigned>
3302  EmitKeyDataLength(raw_ostream& Out, Selector Sel,
3303  data_type_ref Methods) {
3304  using namespace llvm::support;
3305 
3306  endian::Writer LE(Out, little);
3307  unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
3308  LE.write<uint16_t>(KeyLen);
3309  unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
3310  for (const ObjCMethodList *Method = &Methods.Instance; Method;
3311  Method = Method->getNext())
3312  if (Method->getMethod())
3313  DataLen += 4;
3314  for (const ObjCMethodList *Method = &Methods.Factory; Method;
3315  Method = Method->getNext())
3316  if (Method->getMethod())
3317  DataLen += 4;
3318  LE.write<uint16_t>(DataLen);
3319  return std::make_pair(KeyLen, DataLen);
3320  }
3321 
3322  void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
3323  using namespace llvm::support;
3324 
3325  endian::Writer LE(Out, little);
3326  uint64_t Start = Out.tell();
3327  assert((Start >> 32) == 0 && "Selector key offset too large");
3328  Writer.SetSelectorOffset(Sel, Start);
3329  unsigned N = Sel.getNumArgs();
3330  LE.write<uint16_t>(N);
3331  if (N == 0)
3332  N = 1;
3333  for (unsigned I = 0; I != N; ++I)
3334  LE.write<uint32_t>(
3336  }
3337 
3338  void EmitData(raw_ostream& Out, key_type_ref,
3339  data_type_ref Methods, unsigned DataLen) {
3340  using namespace llvm::support;
3341 
3342  endian::Writer LE(Out, little);
3343  uint64_t Start = Out.tell(); (void)Start;
3344  LE.write<uint32_t>(Methods.ID);
3345  unsigned NumInstanceMethods = 0;
3346  for (const ObjCMethodList *Method = &Methods.Instance; Method;
3347  Method = Method->getNext())
3348  if (Method->getMethod())
3349  ++NumInstanceMethods;
3350 
3351  unsigned NumFactoryMethods = 0;
3352  for (const ObjCMethodList *Method = &Methods.Factory; Method;
3353  Method = Method->getNext())
3354  if (Method->getMethod())
3355  ++NumFactoryMethods;
3356 
3357  unsigned InstanceBits = Methods.Instance.getBits();
3358  assert(InstanceBits < 4);
3359  unsigned InstanceHasMoreThanOneDeclBit =
3360  Methods.Instance.hasMoreThanOneDecl();
3361  unsigned FullInstanceBits = (NumInstanceMethods << 3) |
3362  (InstanceHasMoreThanOneDeclBit << 2) |
3363  InstanceBits;
3364  unsigned FactoryBits = Methods.Factory.getBits();
3365  assert(FactoryBits < 4);
3366  unsigned FactoryHasMoreThanOneDeclBit =
3367  Methods.Factory.hasMoreThanOneDecl();
3368  unsigned FullFactoryBits = (NumFactoryMethods << 3) |
3369  (FactoryHasMoreThanOneDeclBit << 2) |
3370  FactoryBits;
3371  LE.write<uint16_t>(FullInstanceBits);
3372  LE.write<uint16_t>(FullFactoryBits);
3373  for (const ObjCMethodList *Method = &Methods.Instance; Method;
3374  Method = Method->getNext())
3375  if (Method->getMethod())
3376  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3377  for (const ObjCMethodList *Method = &Methods.Factory; Method;
3378  Method = Method->getNext())
3379  if (Method->getMethod())
3380  LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
3381 
3382  assert(Out.tell() - Start == DataLen && "Data length is wrong");
3383  }
3384 };
3385 
3386 } // namespace
3387 
3388 /// Write ObjC data: selectors and the method pool.
3389 ///
3390 /// The method pool contains both instance and factory methods, stored
3391 /// in an on-disk hash table indexed by the selector. The hash table also
3392 /// contains an empty entry for every other selector known to Sema.
3393 void ASTWriter::WriteSelectors(Sema &SemaRef) {
3394  using namespace llvm;
3395 
3396  // Do we have to do anything at all?
3397  if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
3398  return;
3399  unsigned NumTableEntries = 0;
3400  // Create and write out the blob that contains selectors and the method pool.
3401  {
3402  llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
3403  ASTMethodPoolTrait Trait(*this);
3404 
3405  // Create the on-disk hash table representation. We walk through every
3406  // selector we've seen and look it up in the method pool.
3407  SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
3408  for (auto &SelectorAndID : SelectorIDs) {
3409  Selector S = SelectorAndID.first;
3410  SelectorID ID = SelectorAndID.second;
3411  Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
3412  ASTMethodPoolTrait::data_type Data = {
3413  ID,
3414  ObjCMethodList(),
3415  ObjCMethodList()
3416  };
3417  if (F != SemaRef.MethodPool.end()) {
3418  Data.Instance = F->second.first;
3419  Data.Factory = F->second.second;
3420  }
3421  // Only write this selector if it's not in an existing AST or something
3422  // changed.
3423  if (Chain && ID < FirstSelectorID) {
3424  // Selector already exists. Did it change?
3425  bool changed = false;
3426  for (ObjCMethodList *M = &Data.Instance;
3427  !changed && M && M->getMethod(); M = M->getNext()) {
3428  if (!M->getMethod()->isFromASTFile())
3429  changed = true;
3430  }
3431  for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
3432  M = M->getNext()) {
3433  if (!M->getMethod()->isFromASTFile())
3434  changed = true;
3435  }
3436  if (!changed)
3437  continue;
3438  } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
3439  // A new method pool entry.
3440  ++NumTableEntries;
3441  }
3442  Generator.insert(S, Data, Trait);
3443  }
3444 
3445  // Create the on-disk hash table in a buffer.
3446  SmallString<4096> MethodPool;
3447  uint32_t BucketOffset;
3448  {
3449  using namespace llvm::support;
3450 
3451  ASTMethodPoolTrait Trait(*this);
3452  llvm::raw_svector_ostream Out(MethodPool);
3453  // Make sure that no bucket is at offset 0
3454  endian::write<uint32_t>(Out, 0, little);
3455  BucketOffset = Generator.Emit(Out, Trait);
3456  }
3457 
3458  // Create a blob abbreviation
3459  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3460  Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
3461  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3462  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3463  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3464  unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3465 
3466  // Write the method pool
3467  {
3468  RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
3469  NumTableEntries};
3470  Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
3471  }
3472 
3473  // Create a blob abbreviation for the selector table offsets.
3474  Abbrev = std::make_shared<BitCodeAbbrev>();
3475  Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
3476  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
3477  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3478  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3479  unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3480 
3481  // Write the selector offsets table.
3482  {
3483  RecordData::value_type Record[] = {
3484  SELECTOR_OFFSETS, SelectorOffsets.size(),
3485  FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
3486  Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
3487  bytes(SelectorOffsets));
3488  }
3489  }
3490 }
3491 
3492 /// Write the selectors referenced in @selector expression into AST file.
3493 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
3494  using namespace llvm;
3495 
3496  if (SemaRef.ReferencedSelectors.empty())
3497  return;
3498 
3499  RecordData Record;
3500  ASTRecordWriter Writer(*this, Record);
3501 
3502  // Note: this writes out all references even for a dependent AST. But it is
3503  // very tricky to fix, and given that @selector shouldn't really appear in
3504  // headers, probably not worth it. It's not a correctness issue.
3505  for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
3506  Selector Sel = SelectorAndLocation.first;
3507  SourceLocation Loc = SelectorAndLocation.second;
3508  Writer.AddSelectorRef(Sel);
3509  Writer.AddSourceLocation(Loc);
3510  }
3512 }
3513 
3514 //===----------------------------------------------------------------------===//
3515 // Identifier Table Serialization
3516 //===----------------------------------------------------------------------===//
3517 
3518 /// Determine the declaration that should be put into the name lookup table to
3519 /// represent the given declaration in this module. This is usually D itself,
3520 /// but if D was imported and merged into a local declaration, we want the most
3521 /// recent local declaration instead. The chosen declaration will be the most
3522 /// recent declaration in any module that imports this one.
3524  NamedDecl *D) {
3525  if (!LangOpts.Modules || !D->isFromASTFile())
3526  return D;
3527 
3528  if (Decl *Redecl = D->getPreviousDecl()) {
3529  // For Redeclarable decls, a prior declaration might be local.
3530  for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
3531  // If we find a local decl, we're done.
3532  if (!Redecl->isFromASTFile()) {
3533  // Exception: in very rare cases (for injected-class-names), not all
3534  // redeclarations are in the same semantic context. Skip ones in a
3535  // different context. They don't go in this lookup table at all.
3536  if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
3538  continue;
3539  return cast<NamedDecl>(Redecl);
3540  }
3541 
3542  // If we find a decl from a (chained-)PCH stop since we won't find a
3543  // local one.
3544  if (Redecl->getOwningModuleID() == 0)
3545  break;
3546  }
3547  } else if (Decl *First = D->getCanonicalDecl()) {
3548  // For Mergeable decls, the first decl might be local.
3549  if (!First->isFromASTFile())
3550  return cast<NamedDecl>(First);
3551  }
3552 
3553  // All declarations are imported. Our most recent declaration will also be
3554  // the most recent one in anyone who imports us.
3555  return D;
3556 }
3557 
3558 namespace {
3559 
3560 class ASTIdentifierTableTrait {
3561  ASTWriter &Writer;
3562  Preprocessor &PP;
3563  IdentifierResolver &IdResolver;
3564  bool IsModule;
3565  bool NeedDecls;
3566  ASTWriter::RecordData *InterestingIdentifierOffsets;
3567 
3568  /// Determines whether this is an "interesting" identifier that needs a
3569  /// full IdentifierInfo structure written into the hash table. Notably, this
3570  /// doesn't check whether the name has macros defined; use PublicMacroIterator
3571  /// to check that.
3572  bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
3573  if (MacroOffset ||
3574  II->isPoisoned() ||
3575  (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
3577  (NeedDecls && II->getFETokenInfo<void>()))
3578  return true;
3579 
3580  return false;
3581  }
3582 
3583 public:
3584  using key_type = IdentifierInfo *;
3585  using key_type_ref = key_type;
3586 
3587  using data_type = IdentID;
3588  using data_type_ref = data_type;
3589 
3590  using hash_value_type = unsigned;
3591  using offset_type = unsigned;
3592 
3593  ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3594  IdentifierResolver &IdResolver, bool IsModule,
3595  ASTWriter::RecordData *InterestingIdentifierOffsets)
3596  : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
3597  NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
3598  InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
3599 
3600  bool needDecls() const { return NeedDecls; }
3601 
3602  static hash_value_type ComputeHash(const IdentifierInfo* II) {
3603  return llvm::djbHash(II->getName());
3604  }
3605 
3606  bool isInterestingIdentifier(const IdentifierInfo *II) {
3607  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3608  return isInterestingIdentifier(II, MacroOffset);
3609  }
3610 
3611  bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
3612  return isInterestingIdentifier(II, 0);
3613  }
3614 
3615  std::pair<unsigned, unsigned>
3616  EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3617  unsigned KeyLen = II->getLength() + 1;
3618  unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3619  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3620  if (isInterestingIdentifier(II, MacroOffset)) {
3621  DataLen += 2; // 2 bytes for builtin ID
3622  DataLen += 2; // 2 bytes for flags
3623  if (MacroOffset)
3624  DataLen += 4; // MacroDirectives offset.
3625 
3626  if (NeedDecls) {
3627  for (IdentifierResolver::iterator D = IdResolver.begin(II),
3628  DEnd = IdResolver.end();
3629  D != DEnd; ++D)
3630  DataLen += 4;
3631  }
3632  }
3633 
3634  using namespace llvm::support;
3635 
3636  endian::Writer LE(Out, little);
3637 
3638  assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
3639  LE.write<uint16_t>(DataLen);
3640  // We emit the key length after the data length so that every
3641  // string is preceded by a 16-bit length. This matches the PTH
3642  // format for storing identifiers.
3643  LE.write<uint16_t>(KeyLen);
3644  return std::make_pair(KeyLen, DataLen);
3645  }
3646 
3647  void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3648  unsigned KeyLen) {
3649  // Record the location of the key data. This is used when generating
3650  // the mapping from persistent IDs to strings.
3651  Writer.SetIdentifierOffset(II, Out.tell());
3652 
3653  // Emit the offset of the key/data length information to the interesting
3654  // identifiers table if necessary.
3655  if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
3656  InterestingIdentifierOffsets->push_back(Out.tell() - 4);
3657 
3658  Out.write(II->getNameStart(), KeyLen);
3659  }
3660 
3661  void EmitData(raw_ostream& Out, IdentifierInfo* II,
3662  IdentID ID, unsigned) {
3663  using namespace llvm::support;
3664 
3665  endian::Writer LE(Out, little);
3666 
3667  auto MacroOffset = Writer.getMacroDirectivesOffset(II);
3668  if (!isInterestingIdentifier(II, MacroOffset)) {
3669  LE.write<uint32_t>(ID << 1);
3670  return;
3671  }
3672 
3673  LE.write<uint32_t>((ID << 1) | 0x01);
3674  uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3675  assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3676  LE.write<uint16_t>(Bits);
3677  Bits = 0;
3678  bool HadMacroDefinition = MacroOffset != 0;
3679  Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3680  Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3681  Bits = (Bits << 1) | unsigned(II->isPoisoned());
3682  Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
3683  Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3684  Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3685  LE.write<uint16_t>(Bits);
3686 
3687  if (HadMacroDefinition)
3688  LE.write<uint32_t>(MacroOffset);
3689 
3690  if (NeedDecls) {
3691  // Emit the declaration IDs in reverse order, because the
3692  // IdentifierResolver provides the declarations as they would be
3693  // visible (e.g., the function "stat" would come before the struct
3694  // "stat"), but the ASTReader adds declarations to the end of the list
3695  // (so we need to see the struct "stat" before the function "stat").
3696  // Only emit declarations that aren't from a chained PCH, though.
3697  SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
3698  IdResolver.end());
3699  for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
3700  DEnd = Decls.rend();
3701  D != DEnd; ++D)
3702  LE.write<uint32_t>(
3703  Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
3704  }
3705  }
3706 };
3707 
3708 } // namespace
3709 
3710 /// Write the identifier table into the AST file.
3711 ///
3712 /// The identifier table consists of a blob containing string data
3713 /// (the actual identifiers themselves) and a separate "offsets" index
3714 /// that maps identifier IDs to locations within the blob.
3715 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3716  IdentifierResolver &IdResolver,
3717  bool IsModule) {
3718  using namespace llvm;
3719 
3720  RecordData InterestingIdents;
3721 
3722  // Create and write out the blob that contains the identifier
3723  // strings.
3724  {
3725  llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3726  ASTIdentifierTableTrait Trait(
3727  *this, PP, IdResolver, IsModule,
3728  (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
3729 
3730  // Look for any identifiers that were named while processing the
3731  // headers, but are otherwise not needed. We add these to the hash
3732  // table to enable checking of the predefines buffer in the case
3733  // where the user adds new macro definitions when building the AST
3734  // file.
3736  for (const auto &ID : PP.getIdentifierTable())
3737  IIs.push_back(ID.second);
3738  // Sort the identifiers lexicographically before getting them references so
3739  // that their order is stable.
3740  llvm::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
3741  for (const IdentifierInfo *II : IIs)
3742  if (Trait.isInterestingNonMacroIdentifier(II))
3743  getIdentifierRef(II);
3744 
3745  // Create the on-disk hash table representation. We only store offsets
3746  // for identifiers that appear here for the first time.
3747  IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3748  for (auto IdentIDPair : IdentifierIDs) {
3749  auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
3750  IdentID ID = IdentIDPair.second;
3751  assert(II && "NULL identifier in identifier table");
3752  // Write out identifiers if either the ID is local or the identifier has
3753  // changed since it was loaded.
3754  if (ID >= FirstIdentID || !Chain || !II->isFromAST()
3755  || II->hasChangedSinceDeserialization() ||
3756  (Trait.needDecls() &&
3757  II->hasFETokenInfoChangedSinceDeserialization()))
3758  Generator.insert(II, ID, Trait);
3759  }
3760 
3761  // Create the on-disk hash table in a buffer.
3763  uint32_t BucketOffset;
3764  {
3765  using namespace llvm::support;
3766 
3767  llvm::raw_svector_ostream Out(IdentifierTable);
3768  // Make sure that no bucket is at offset 0
3769  endian::write<uint32_t>(Out, 0, little);
3770  BucketOffset = Generator.Emit(Out, Trait);
3771  }
3772 
3773  // Create a blob abbreviation
3774  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3775  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3776  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3777  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3778  unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3779 
3780  // Write the identifier table
3781  RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
3782  Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
3783  }
3784 
3785  // Write the offsets table for identifier IDs.
3786  auto Abbrev = std::make_shared<BitCodeAbbrev>();
3787  Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3788  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3789  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3790  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3791  unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
3792 
3793 #ifndef NDEBUG
3794  for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3795  assert(IdentifierOffsets[I] && "Missing identifier offset?");
3796 #endif
3797 
3798  RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
3799  IdentifierOffsets.size(),
3800  FirstIdentID - NUM_PREDEF_IDENT_IDS};
3801  Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3802  bytes(IdentifierOffsets));
3803 
3804  // In C++, write the list of interesting identifiers (those that are
3805  // defined as macros, poisoned, or similar unusual things).
3806  if (!InterestingIdents.empty())
3807  Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
3808 }
3809 
3810 //===----------------------------------------------------------------------===//
3811 // DeclContext's Name Lookup Table Serialization
3812 //===----------------------------------------------------------------------===//
3813 
3814 namespace {
3815 
3816 // Trait used for the on-disk hash table used in the method pool.
3817 class ASTDeclContextNameLookupTrait {
3818  ASTWriter &Writer;
3820 
3821 public:
3822  using key_type = DeclarationNameKey;
3823  using key_type_ref = key_type;
3824 
3825  /// A start and end index into DeclIDs, representing a sequence of decls.
3826  using data_type = std::pair<unsigned, unsigned>;
3827  using data_type_ref = const data_type &;
3828 
3829  using hash_value_type = unsigned;
3830  using offset_type = unsigned;
3831 
3832  explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
3833 
3834  template<typename Coll>
3835  data_type getData(const Coll &Decls) {
3836  unsigned Start = DeclIDs.size();
3837  for (NamedDecl *D : Decls) {
3838  DeclIDs.push_back(
3839  Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
3840  }
3841  return std::make_pair(Start, DeclIDs.size());
3842  }
3843 
3844  data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
3845  unsigned Start = DeclIDs.size();
3846  for (auto ID : FromReader)
3847  DeclIDs.push_back(ID);
3848  return std::make_pair(Start, DeclIDs.size());
3849  }
3850 
3851  static bool EqualKey(key_type_ref a, key_type_ref b) {
3852  return a == b;
3853  }
3854 
3855  hash_value_type ComputeHash(DeclarationNameKey Name) {
3856  return Name.getHash();
3857  }
3858 
3859  void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
3860  assert(Writer.hasChain() &&
3861  "have reference to loaded module file but no chain?");
3862 
3863  using namespace llvm::support;
3864 
3865  endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
3866  }
3867 
3868  std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
3869  DeclarationNameKey Name,
3870  data_type_ref Lookup) {
3871  using namespace llvm::support;
3872 
3873  endian::Writer LE(Out, little);
3874  unsigned KeyLen = 1;
3875  switch (Name.getKind()) {
3882  KeyLen += 4;
3883  break;
3885  KeyLen += 1;
3886  break;
3891  break;
3892  }
3893  LE.write<uint16_t>(KeyLen);
3894 
3895  // 4 bytes for each DeclID.
3896  unsigned DataLen = 4 * (Lookup.second - Lookup.first);
3897  assert(uint16_t(DataLen) == DataLen &&
3898  "too many decls for serialized lookup result");
3899  LE.write<uint16_t>(DataLen);
3900 
3901  return std::make_pair(KeyLen, DataLen);
3902  }
3903 
3904  void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
3905  using namespace llvm::support;
3906 
3907  endian::Writer LE(Out, little);
3908  LE.write<uint8_t>(Name.getKind());
3909  switch (Name.getKind()) {
3913  LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
3914  return;
3918  LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
3919  return;
3921  assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
3922  "Invalid operator?");
3923  LE.write<uint8_t>(Name.getOperatorKind());
3924  return;
3929  return;
3930  }
3931 
3932  llvm_unreachable("Invalid name kind?");
3933  }
3934 
3935  void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
3936  unsigned DataLen) {
3937  using namespace llvm::support;
3938 
3939  endian::Writer LE(Out, little);
3940  uint64_t Start = Out.tell(); (void)Start;
3941  for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
3942  LE.write<uint32_t>(DeclIDs[I]);
3943  assert(Out.tell() - Start == DataLen && "Data length is wrong");
3944  }
3945 };
3946 
3947 } // namespace
3948 
3949 bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
3950  DeclContext *DC) {
3951  return Result.hasExternalDecls() &&
3952  DC->hasNeedToReconcileExternalVisibleStorage();
3953 }
3954 
3955 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
3956  DeclContext *DC) {
3957  for (auto *D : Result.getLookupResult())
3958  if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
3959  return false;
3960 
3961  return true;
3962 }
3963 
3964 void
3965 ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
3966  llvm::SmallVectorImpl<char> &LookupTable) {
3967  assert(!ConstDC->hasLazyLocalLexicalLookups() &&
3968  !ConstDC->hasLazyExternalLexicalLookups() &&
3969  "must call buildLookups first");
3970 
3971  // FIXME: We need to build the lookups table, which is logically const.
3972  auto *DC = const_cast<DeclContext*>(ConstDC);
3973  assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3974 
3975  // Create the on-disk hash table representation.
3977  ASTDeclContextNameLookupTrait> Generator;
3978  ASTDeclContextNameLookupTrait Trait(*this);
3979 
3980  // The first step is to collect the declaration names which we need to
3981  // serialize into the name lookup table, and to collect them in a stable
3982  // order.
3984 
3985  // We also build up small sets of the constructor and conversion function
3986  // names which are visible.
3987  llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
3988 
3989  for (auto &Lookup : *DC->buildLookup()) {
3990  auto &Name = Lookup.first;
3991  auto &Result = Lookup.second;
3992 
3993  // If there are no local declarations in our lookup result, we
3994  // don't need to write an entry for the name at all. If we can't
3995  // write out a lookup set without performing more deserialization,
3996  // just skip this entry.
3997  if (isLookupResultExternal(Result, DC) &&
3998  isLookupResultEntirelyExternal(Result, DC))
3999  continue;
4000 
4001  // We also skip empty results. If any of the results could be external and
4002  // the currently available results are empty, then all of the results are
4003  // external and we skip it above. So the only way we get here with an empty
4004  // results is when no results could have been external *and* we have
4005  // external results.
4006  //
4007  // FIXME: While we might want to start emitting on-disk entries for negative
4008  // lookups into a decl context as an optimization, today we *have* to skip
4009  // them because there are names with empty lookup results in decl contexts
4010  // which we can't emit in any stable ordering: we lookup constructors and
4011  // conversion functions in the enclosing namespace scope creating empty
4012  // results for them. This in almost certainly a bug in Clang's name lookup,
4013  // but that is likely to be hard or impossible to fix and so we tolerate it
4014  // here by omitting lookups with empty results.
4015  if (Lookup.second.getLookupResult().empty())
4016  continue;
4017 
4018  switch (Lookup.first.getNameKind()) {
4019  default:
4020  Names.push_back(Lookup.first);
4021  break;
4022 
4024  assert(isa<CXXRecordDecl>(DC) &&
4025  "Cannot have a constructor name outside of a class!");
4026  ConstructorNameSet.insert(Name);
4027  break;
4028 
4030  assert(isa<CXXRecordDecl>(DC) &&
4031  "Cannot have a conversion function name outside of a class!");
4032  ConversionNameSet.insert(Name);
4033  break;
4034  }
4035  }
4036 
4037  // Sort the names into a stable order.
4038  llvm::sort(Names.begin(), Names.end());
4039 
4040  if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
4041  // We need to establish an ordering of constructor and conversion function
4042  // names, and they don't have an intrinsic ordering.
4043 
4044  // First we try the easy case by forming the current context's constructor
4045  // name and adding that name first. This is a very useful optimization to
4046  // avoid walking the lexical declarations in many cases, and it also
4047  // handles the only case where a constructor name can come from some other
4048  // lexical context -- when that name is an implicit constructor merged from
4049  // another declaration in the redecl chain. Any non-implicit constructor or
4050  // conversion function which doesn't occur in all the lexical contexts
4051  // would be an ODR violation.
4052  auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
4053  Context->getCanonicalType(Context->getRecordType(D)));
4054  if (ConstructorNameSet.erase(ImplicitCtorName))
4055  Names.push_back(ImplicitCtorName);
4056 
4057  // If we still have constructors or conversion functions, we walk all the
4058  // names in the decl and add the constructors and conversion functions
4059  // which are visible in the order they lexically occur within the context.
4060  if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
4061  for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
4062  if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
4063  auto Name = ChildND->getDeclName();
4064  switch (Name.getNameKind()) {
4065  default:
4066  continue;
4067 
4069  if (ConstructorNameSet.erase(Name))
4070  Names.push_back(Name);
4071  break;
4072 
4074  if (ConversionNameSet.erase(Name))
4075  Names.push_back(Name);
4076  break;
4077  }
4078 
4079  if (ConstructorNameSet.empty() && ConversionNameSet.empty())
4080  break;
4081  }
4082 
4083  assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
4084  "constructors by walking all the "
4085  "lexical members of the context.");
4086  assert(ConversionNameSet.empty() && "Failed to find all of the visible "
4087  "conversion functions by walking all "
4088  "the lexical members of the context.");
4089  }
4090 
4091  // Next we need to do a lookup with each name into this decl context to fully
4092  // populate any results from external sources. We don't actually use the
4093  // results of these lookups because we only want to use the results after all
4094  // results have been loaded and the pointers into them will be stable.
4095  for (auto &Name : Names)
4096  DC->lookup(Name);
4097 
4098  // Now we need to insert the results for each name into the hash table. For
4099  // constructor names and conversion function names, we actually need to merge
4100  // all of the results for them into one list of results each and insert
4101  // those.
4102  SmallVector<NamedDecl *, 8> ConstructorDecls;
4103  SmallVector<NamedDecl *, 8> ConversionDecls;
4104 
4105  // Now loop over the names, either inserting them or appending for the two
4106  // special cases.
4107  for (auto &Name : Names) {
4108  DeclContext::lookup_result Result = DC->noload_lookup(Name);
4109 
4110  switch (Name.getNameKind()) {
4111  default:
4112  Generator.insert(Name, Trait.getData(Result), Trait);
4113  break;
4114 
4116  ConstructorDecls.append(Result.begin(), Result.end());
4117  break;
4118 
4120  ConversionDecls.append(Result.begin(), Result.end());
4121  break;
4122  }
4123  }
4124 
4125  // Handle our two special cases if we ended up having any. We arbitrarily use
4126  // the first declaration's name here because the name itself isn't part of
4127  // the key, only the kind of name is used.
4128  if (!ConstructorDecls.empty())
4129  Generator.insert(ConstructorDecls.front()->getDeclName(),
4130  Trait.getData(ConstructorDecls), Trait);
4131  if (!ConversionDecls.empty())
4132  Generator.insert(ConversionDecls.front()->getDeclName(),
4133  Trait.getData(ConversionDecls), Trait);
4134 
4135  // Create the on-disk hash table. Also emit the existing imported and
4136  // merged table if there is one.
4137  auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
4138  Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
4139 }
4140 
4141 /// Write the block containing all of the declaration IDs
4142 /// visible from the given DeclContext.
4143 ///
4144 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
4145 /// bitstream, or 0 if no block was written.
4146 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
4147  DeclContext *DC) {
4148  // If we imported a key declaration of this namespace, write the visible
4149  // lookup results as an update record for it rather than including them
4150  // on this declaration. We will only look at key declarations on reload.
4151  if (isa<NamespaceDecl>(DC) && Chain &&
4152  Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
4153  // Only do this once, for the first local declaration of the namespace.
4154  for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
4155  Prev = Prev->getPreviousDecl())
4156  if (!Prev->isFromASTFile())
4157  return 0;
4158 
4159  // Note that we need to emit an update record for the primary context.
4160  UpdatedDeclContexts.insert(DC->getPrimaryContext());
4161 
4162  // Make sure all visible decls are written. They will be recorded later. We
4163  // do this using a side data structure so we can sort the names into
4164  // a deterministic order.
4167  LookupResults;
4168  if (Map) {
4169  LookupResults.reserve(Map->size());
4170  for (auto &Entry : *Map)
4171  LookupResults.push_back(
4172  std::make_pair(Entry.first, Entry.second.getLookupResult()));
4173  }
4174 
4175  llvm::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
4176  for (auto &NameAndResult : LookupResults) {
4177  DeclarationName Name = NameAndResult.first;
4178  DeclContext::lookup_result Result = NameAndResult.second;
4181  // We have to work around a name lookup bug here where negative lookup
4182  // results for these names get cached in namespace lookup tables (these
4183  // names should never be looked up in a namespace).
4184  assert(Result.empty() && "Cannot have a constructor or conversion "
4185  "function name in a namespace!");
4186  continue;
4187  }
4188 
4189  for (NamedDecl *ND : Result)
4190  if (!ND->isFromASTFile())
4191  GetDeclRef(ND);
4192  }
4193 
4194  return 0;
4195  }
4196 
4197  if (DC->getPrimaryContext() != DC)
4198  return 0;
4199 
4200  // Skip contexts which don't support name lookup.
4201  if (!DC->isLookupContext())
4202  return 0;
4203 
4204  // If not in C++, we perform name lookup for the translation unit via the
4205  // IdentifierInfo chains, don't bother to build a visible-declarations table.
4206  if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
4207  return 0;
4208 
4209  // Serialize the contents of the mapping used for lookup. Note that,
4210  // although we have two very different code paths, the serialized
4211  // representation is the same for both cases: a declaration name,
4212  // followed by a size, followed by references to the visible
4213  // declarations that have that name.
4214  uint64_t Offset = Stream.GetCurrentBitNo();
4215  StoredDeclsMap *Map = DC->buildLookup();
4216  if (!Map || Map->empty())
4217  return 0;
4218 
4219  // Create the on-disk hash table in a buffer.
4220  SmallString<4096> LookupTable;
4221  GenerateNameLookupTable(DC, LookupTable);
4222 
4223  // Write the lookup table
4224  RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
4225  Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
4226  LookupTable);
4227  ++NumVisibleDeclContexts;
4228  return Offset;
4229 }
4230 
4231 /// Write an UPDATE_VISIBLE block for the given context.
4232 ///
4233 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
4234 /// DeclContext in a dependent AST file. As such, they only exist for the TU
4235 /// (in C++), for namespaces, and for classes with forward-declared unscoped
4236 /// enumeration members (in C++11).
4237 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
4238  StoredDeclsMap *Map = DC->getLookupPtr();
4239  if (!Map || Map->empty())
4240  return;
4241 
4242  // Create the on-disk hash table in a buffer.
4243  SmallString<4096> LookupTable;
4244  GenerateNameLookupTable(DC, LookupTable);
4245 
4246  // If we're updating a namespace, select a key declaration as the key for the
4247  // update record; those are the only ones that will be checked on reload.
4248  if (isa<NamespaceDecl>(DC))
4249  DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
4250 
4251  // Write the lookup table
4252  RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
4253  Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
4254 }
4255 
4256 /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
4257 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
4258  RecordData::value_type Record[] = {Opts.getInt()};
4259  Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
4260 }
4261 
4262 /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
4263 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
4264  if (!SemaRef.Context.getLangOpts().OpenCL)
4265  return;
4266 
4267  const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
4268  RecordData Record;
4269  for (const auto &I:Opts.OptMap) {
4270  AddString(I.getKey(), Record);
4271  auto V = I.getValue();
4272  Record.push_back(V.Supported ? 1 : 0);
4273  Record.push_back(V.Enabled ? 1 : 0);
4274  Record.push_back(V.Avail);
4275  Record.push_back(V.Core);
4276  }
4277  Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
4278 }
4279 
4280 void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
4281  if (!SemaRef.Context.getLangOpts().OpenCL)
4282  return;
4283 
4284  RecordData Record;
4285  for (const auto &I : SemaRef.OpenCLTypeExtMap) {
4286  Record.push_back(
4287  static_cast<unsigned>(getTypeID(I.first->getCanonicalTypeInternal())));
4288  Record.push_back(I.second.size());
4289  for (auto Ext : I.second)
4290  AddString(Ext, Record);
4291  }
4292  Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
4293 }
4294 
4295 void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
4296  if (!SemaRef.Context.getLangOpts().OpenCL)
4297  return;
4298 
4299  RecordData Record;
4300  for (const auto &I : SemaRef.OpenCLDeclExtMap) {
4301  Record.push_back(getDeclID(I.first));
4302  Record.push_back(static_cast<unsigned>(I.second.size()));
4303  for (auto Ext : I.second)
4304  AddString(Ext, Record);
4305  }
4306  Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
4307 }
4308 
4309 void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
4310  if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
4311  RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
4312  Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
4313  }
4314 }
4315 
4316 void ASTWriter::WriteObjCCategories() {
4317  SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
4318  RecordData Categories;
4319 
4320  for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
4321  unsigned Size = 0;
4322  unsigned StartIndex = Categories.size();
4323 
4324  ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
4325 
4326  // Allocate space for the size.
4327  Categories.push_back(0);
4328 
4329  // Add the categories.
4331  Cat = Class->known_categories_begin(),
4332  CatEnd = Class->known_categories_end();
4333  Cat != CatEnd; ++Cat, ++Size) {
4334  assert(getDeclID(*Cat) != 0 && "Bogus category");
4335  AddDeclRef(*Cat, Categories);
4336  }
4337 
4338  // Update the size.
4339  Categories[StartIndex] = Size;
4340 
4341  // Record this interface -> category map.
4342  ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
4343  CategoriesMap.push_back(CatInfo);
4344  }
4345 
4346  // Sort the categories map by the definition ID, since the reader will be
4347  // performing binary searches on this information.
4348  llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
4349 
4350  // Emit the categories map.
4351  using namespace llvm;
4352 
4353  auto Abbrev = std::make_shared<BitCodeAbbrev>();
4354  Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
4355  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
4356  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4357  unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
4358 
4359  RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
4360  Stream.EmitRecordWithBlob(AbbrevID, Record,
4361  reinterpret_cast<char *>(CategoriesMap.data()),
4362  CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
4363 
4364  // Emit the category lists.
4365  Stream.EmitRecord(OBJC_CATEGORIES, Categories);
4366 }
4367 
4368 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
4370 
4371  if (LPTMap.empty())
4372  return;
4373 
4374  RecordData Record;
4375  for (auto &LPTMapEntry : LPTMap) {
4376  const FunctionDecl *FD = LPTMapEntry.first;
4377  LateParsedTemplate &LPT = *LPTMapEntry.second;
4378  AddDeclRef(FD, Record);
4379  AddDeclRef(LPT.D, Record);
4380  Record.push_back(LPT.Toks.size());
4381 
4382  for (const auto &Tok : LPT.Toks) {
4383  AddToken(Tok, Record);
4384  }
4385  }
4386  Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
4387 }
4388 
4389 /// Write the state of 'pragma clang optimize' at the end of the module.
4390 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
4391  RecordData Record;
4392  SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
4393  AddSourceLocation(PragmaLoc, Record);
4394  Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
4395 }
4396 
4397 /// Write the state of 'pragma ms_struct' at the end of the module.
4398 void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
4399  RecordData Record;
4400  Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
4401  Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
4402 }
4403 
4404 /// Write the state of 'pragma pointers_to_members' at the end of the
4405 //module.
4406 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
4407  RecordData Record;
4408  Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
4409  AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
4410  Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
4411 }
4412 
4413 /// Write the state of 'pragma pack' at the end of the module.
4414 void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
4415  // Don't serialize pragma pack state for modules, since it should only take
4416  // effect on a per-submodule basis.
4417  if (WritingModule)
4418  return;
4419 
4420  RecordData Record;
4421  Record.push_back(SemaRef.PackStack.CurrentValue);
4422  AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
4423  Record.push_back(SemaRef.PackStack.Stack.size());
4424  for (const auto &StackEntry : SemaRef.PackStack.Stack) {
4425  Record.push_back(StackEntry.Value);
4426  AddSourceLocation(StackEntry.PragmaLocation, Record);
4427  AddSourceLocation(StackEntry.PragmaPushLocation, Record);
4428  AddString(StackEntry.StackSlotLabel, Record);
4429  }
4430  Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
4431 }
4432 
4433 void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
4434  ModuleFileExtensionWriter &Writer) {
4435  // Enter the extension block.
4436  Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
4437 
4438  // Emit the metadata record abbreviation.
4439  auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
4440  Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
4441  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4442  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4443  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4444  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4445  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4446  unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
4447 
4448  // Emit the metadata record.
4449  RecordData Record;
4450  auto Metadata = Writer.getExtension()->getExtensionMetadata();
4451  Record.push_back(EXTENSION_METADATA);
4452  Record.push_back(Metadata.MajorVersion);
4453  Record.push_back(Metadata.MinorVersion);
4454  Record.push_back(Metadata.BlockName.size());
4455  Record.push_back(Metadata.UserInfo.size());
4456  SmallString<64> Buffer;
4457  Buffer += Metadata.BlockName;
4458  Buffer += Metadata.UserInfo;
4459  Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
4460 
4461  // Emit the contents of the extension block.
4462  Writer.writeExtensionContents(SemaRef, Stream);
4463 
4464  // Exit the extension block.
4465  Stream.ExitBlock();
4466 }
4467 
4468 //===----------------------------------------------------------------------===//
4469 // General Serialization Routines
4470 //===----------------------------------------------------------------------===//
4471 
4473  auto &Record = *this;
4474  if (!A)
4475  return Record.push_back(0);
4476  Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
4477  Record.AddSourceRange(A->getRange());
4478 
4479 #include "clang/Serialization/AttrPCHWrite.inc"
4480 }
4481 
4482 /// Emit the list of attributes to the specified record.
4484  push_back(Attrs.size());
4485  for (const auto *A : Attrs)
4486  AddAttr(A);
4487 }
4488 
4490  AddSourceLocation(Tok.getLocation(), Record);
4491  Record.push_back(Tok.getLength());
4492 
4493  // FIXME: When reading literal tokens, reconstruct the literal pointer
4494  // if it is needed.
4495  AddIdentifierRef(Tok.getIdentifierInfo(), Record);
4496  // FIXME: Should translate token kind to a stable encoding.
4497  Record.push_back(Tok.getKind());
4498  // FIXME: Should translate token flags to a stable encoding.
4499  Record.push_back(Tok.getFlags());
4500 }
4501 
4502 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
4503  Record.push_back(Str.size());
4504  Record.insert(Record.end(), Str.begin(), Str.end());
4505 }
4506 
4508  assert(Context && "should have context when outputting path");
4509 
4510  bool Changed =
4512 
4513  // Remove a prefix to make the path relative, if relevant.
4514  const char *PathBegin = Path.data();
4515  const char *PathPtr =
4516  adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
4517  if (PathPtr != PathBegin) {
4518  Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
4519  Changed = true;
4520  }
4521 
4522  return Changed;
4523 }
4524 
4525 void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
4526  SmallString<128> FilePath(Path);
4527  PreparePathForOutput(FilePath);
4528  AddString(FilePath, Record);
4529 }
4530 
4531 void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
4532  StringRef Path) {
4533  SmallString<128> FilePath(Path);
4534  PreparePathForOutput(FilePath);
4535  Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
4536 }
4537 
4538 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
4539  RecordDataImpl &Record) {
4540  Record.push_back(Version.getMajor());
4541  if (Optional<unsigned> Minor = Version.getMinor())
4542  Record.push_back(*Minor + 1);
4543  else
4544  Record.push_back(0);
4545  if (Optional<unsigned> Subminor = Version.getSubminor())
4546  Record.push_back(*Subminor + 1);
4547  else
4548  Record.push_back(0);
4549 }
4550 
4551 /// Note that the identifier II occurs at the given offset
4552 /// within the identifier table.
4554  IdentID ID = IdentifierIDs[II];
4555  // Only store offsets new to this AST file. Other identifier names are looked
4556  // up earlier in the chain and thus don't need an offset.
4557  if (ID >= FirstIdentID)
4558  IdentifierOffsets[ID - FirstIdentID] = Offset;
4559 }
4560 
4561 /// Note that the selector Sel occurs at the given offset
4562 /// within the method pool/selector table.
4564  unsigned ID = SelectorIDs[Sel];
4565  assert(ID && "Unknown selector");
4566  // Don't record offsets for selectors that are also available in a different
4567  // file.
4568  if (ID < FirstSelectorID)
4569  return;
4570  SelectorOffsets[ID - FirstSelectorID] = Offset;
4571 }
4572 
4573 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
4574  SmallVectorImpl<char> &Buffer, MemoryBufferCache &PCMCache,
4575  ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
4576  bool IncludeTimestamps)
4577  : Stream(Stream), Buffer(Buffer), PCMCache(PCMCache),
4578  IncludeTimestamps(IncludeTimestamps) {
4579  for (const auto &Ext : Extensions) {
4580  if (auto Writer = Ext->createExtensionWriter(*this))
4581  ModuleFileExtensionWriters.push_back(std::move(Writer));
4582  }
4583 }
4584 
4586  llvm::DeleteContainerSeconds(FileDeclIDs);
4587 }
4588 
4590  assert(WritingAST && "can't determine lang opts when not writing AST");
4591  return Context->getLangOpts();
4592 }
4593 
4595  return IncludeTimestamps ? E->getModificationTime() : 0;
4596 }
4597 
4599  const std::string &OutputFile,
4600  Module *WritingModule, StringRef isysroot,
4601  bool hasErrors) {
4602  WritingAST = true;
4603 
4604  ASTHasCompilerErrors = hasErrors;
4605 
4606  // Emit the file header.
4607  Stream.Emit((unsigned)'C', 8);
4608  Stream.Emit((unsigned)'P', 8);
4609  Stream.Emit((unsigned)'C', 8);
4610  Stream.Emit((unsigned)'H', 8);
4611 
4612  WriteBlockInfoBlock();
4613 
4614  Context = &SemaRef.Context;
4615  PP = &SemaRef.PP;
4616  this->WritingModule = WritingModule;
4617  ASTFileSignature Signature =
4618  WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
4619  Context = nullptr;
4620  PP = nullptr;
4621  this->WritingModule = nullptr;
4622  this->BaseDirectory.clear();
4623 
4624  WritingAST = false;
4625  if (SemaRef.Context.getLangOpts().ImplicitModules && WritingModule) {
4626  // Construct MemoryBuffer and update buffer manager.
4627  PCMCache.addBuffer(OutputFile,
4628  llvm::MemoryBuffer::getMemBufferCopy(
4629  StringRef(Buffer.begin(), Buffer.size())));
4630  }
4631  return Signature;
4632 }
4633 
4634 template<typename Vector>
4635 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4636  ASTWriter::RecordData &Record) {
4637  for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4638  I != E; ++I) {
4639  Writer.AddDeclRef(*I, Record);
4640  }
4641 }
4642 
4643 ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
4644  const std::string &OutputFile,
4645  Module *WritingModule) {
4646  using namespace llvm;
4647 
4648  bool isModule = WritingModule != nullptr;
4649 
4650  // Make sure that the AST reader knows to finalize itself.
4651  if (Chain)
4652  Chain->finalizeForWriting();
4653 
4654  ASTContext &Context = SemaRef.Context;
4655  Preprocessor &PP = SemaRef.PP;
4656 
4657  // Set up predefined declaration IDs.
4658  auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
4659  if (D) {
4660  assert(D->isCanonicalDecl() && "predefined decl is not canonical");
4661  DeclIDs[D] = ID;
4662  }
4663  };
4664  RegisterPredefDecl(Context.getTranslationUnitDecl(),
4666  RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
4667  RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
4668  RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
4669  RegisterPredefDecl(Context.ObjCProtocolClassDecl,
4671  RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
4672  RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
4673  RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
4675  RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
4676  RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
4677  RegisterPredefDecl(Context.BuiltinMSVaListDecl,
4679  RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
4680  RegisterPredefDecl(Context.MakeIntegerSeqDecl,
4682  RegisterPredefDecl(Context.CFConstantStringTypeDecl,
4684  RegisterPredefDecl(Context.CFConstantStringTagDecl,
4686  RegisterPredefDecl(Context.TypePackElementDecl,
4688 
4689  // Build a record containing all of the tentative definitions in this file, in
4690  // TentativeDefinitions order. Generally, this record will be empty for
4691  // headers.
4692  RecordData TentativeDefinitions;
4693  AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4694 
4695  // Build a record containing all of the file scoped decls in this file.
4696  RecordData UnusedFileScopedDecls;
4697  if (!isModule)
4699  UnusedFileScopedDecls);
4700 
4701  // Build a record containing all of the delegating constructors we still need
4702  // to resolve.
4703  RecordData DelegatingCtorDecls;
4704  if (!isModule)
4705  AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4706 
4707  // Write the set of weak, undeclared identifiers. We always write the
4708  // entire table, since later PCH files in a PCH chain are only interested in
4709  // the results at the end of the chain.
4710  RecordData WeakUndeclaredIdentifiers;
4711  for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
4712  IdentifierInfo *II = WeakUndeclaredIdentifier.first;
4713  WeakInfo &WI = WeakUndeclaredIdentifier.second;
4714  AddIdentifierRef(II, WeakUndeclaredIdentifiers);
4715  AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
4716  AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
4717  WeakUndeclaredIdentifiers.push_back(WI.getUsed());
4718  }
4719 
4720  // Build a record containing all of the ext_vector declarations.
4721  RecordData ExtVectorDecls;
4722  AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4723 
4724  // Build a record containing all of the VTable uses information.
4725  RecordData VTableUses;
4726  if (!SemaRef.VTableUses.empty()) {
4727  for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4728  AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4729  AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4730  VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4731  }
4732  }
4733 
4734  // Build a record containing all of the UnusedLocalTypedefNameCandidates.
4735  RecordData UnusedLocalTypedefNameCandidates;
4736  for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
4737  AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
4738 
4739  // Build a record containing all of pending implicit instantiations.
4740  RecordData PendingInstantiations;
4741  for (const auto &I : SemaRef.PendingInstantiations) {
4742  AddDeclRef(I.first, PendingInstantiations);
4743  AddSourceLocation(I.second, PendingInstantiations);
4744  }
4745  assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4746  "There are local ones at end of translation unit!");
4747 
4748  // Build a record containing some declaration references.
4749  RecordData SemaDeclRefs;
4750  if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
4751  AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4752  AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4753  AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
4754  }
4755 
4756  RecordData CUDASpecialDeclRefs;
4757  if (Context.getcudaConfigureCallDecl()) {
4758  AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4759  }
4760 
4761  // Build a record containing all of the known namespaces.
4762  RecordData KnownNamespaces;
4763  for (const auto &I : SemaRef.KnownNamespaces) {
4764  if (!I.second)
4765  AddDeclRef(I.first, KnownNamespaces);
4766  }
4767 
4768  // Build a record of all used, undefined objects that require definitions.
4769  RecordData UndefinedButUsed;
4770 
4772  SemaRef.getUndefinedButUsed(Undefined);
4773  for (const auto &I : Undefined) {
4774  AddDeclRef(I.first, UndefinedButUsed);
4775  AddSourceLocation(I.second, UndefinedButUsed);
4776  }
4777 
4778  // Build a record containing all delete-expressions that we would like to
4779  // analyze later in AST.
4780  RecordData DeleteExprsToAnalyze;
4781 
4782  if (!isModule) {
4783  for (const auto &DeleteExprsInfo :
4784  SemaRef.getMismatchingDeleteExpressions()) {
4785  AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
4786  DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
4787  for (const auto &DeleteLoc : DeleteExprsInfo.second) {
4788  AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
4789  DeleteExprsToAnalyze.push_back(DeleteLoc.second);
4790  }
4791  }
4792  }
4793 
4794  // Write the control block
4795  WriteControlBlock(PP, Context, isysroot, OutputFile);
4796 
4797  // Write the remaining AST contents.
4798  Stream.EnterSubblock(AST_BLOCK_ID, 5);
4799 
4800  // This is so that older clang versions, before the introduction
4801  // of the control block, can read and reject the newer PCH format.
4802  {
4803  RecordData Record = {VERSION_MAJOR};
4804  Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4805  }
4806 
4807  // Create a lexical update block containing all of the declarations in the
4808  // translation unit that do not come from other AST files.
4809  const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4810  SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
4811  for (const auto *D : TU->noload_decls()) {
4812  if (!D->isFromASTFile()) {
4813  NewGlobalKindDeclPairs.push_back(D->getKind());
4814  NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
4815  }
4816  }
4817 
4818  auto Abv = std::make_shared<BitCodeAbbrev>();
4819  Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4820  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4821  unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
4822  {
4823  RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
4824  Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4825  bytes(NewGlobalKindDeclPairs));
4826  }
4827 
4828  // And a visible updates block for the translation unit.
4829  Abv = std::make_shared<BitCodeAbbrev>();
4830  Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4831  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4832  Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4833  UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
4834  WriteDeclContextVisibleUpdate(TU);
4835 
4836  // If we have any extern "C" names, write out a visible update for them.
4837  if (Context.ExternCContext)
4838  WriteDeclContextVisibleUpdate(Context.ExternCContext);
4839 
4840  // If the translation unit has an anonymous namespace, and we don't already
4841  // have an update block for it, write it as an update block.
4842  // FIXME: Why do we not do this if there's already an update block?
4843  if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4844  ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4845  if (Record.empty())
4846  Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4847  }
4848 
4849  // Add update records for all mangling numbers and static local numbers.
4850  // These aren't really update records, but this is a convenient way of
4851  // tagging this rare extra data onto the declarations.
4852  for (const auto &Number : Context.MangleNumbers)
4853  if (!Number.first->isFromASTFile())
4854  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4855  Number.second));
4856  for (const auto &Number : Context.StaticLocalNumbers)
4857  if (!Number.first->isFromASTFile())
4858  DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4859  Number.second));
4860 
4861  // Make sure visible decls, added to DeclContexts previously loaded from
4862  // an AST file, are registered for serialization. Likewise for template
4863  // specializations added to imported templates.
4864  for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
4865  GetDeclRef(I);
4866  }
4867 
4868  // Make sure all decls associated with an identifier are registered for
4869  // serialization, if we're storing decls with identifiers.
4870  if (!WritingModule || !getLangOpts().CPlusPlus) {
4872  for (const auto &ID : PP.getIdentifierTable()) {
4873  const IdentifierInfo *II = ID.second;
4874  if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
4875  IIs.push_back(II);
4876  }
4877  // Sort the identifiers to visit based on their name.
4878  llvm::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
4879  for (const IdentifierInfo *II : IIs) {
4880  for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4881  DEnd = SemaRef.IdResolver.end();
4882  D != DEnd; ++D) {
4883  GetDeclRef(*D);
4884  }
4885  }
4886  }
4887 
4888  // For method pool in the module, if it contains an entry for a selector,
4889  // the entry should be complete, containing everything introduced by that
4890  // module and all modules it imports. It's possible that the entry is out of
4891  // date, so we need to pull in the new content here.
4892 
4893  // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
4894  // safe, we copy all selectors out.
4895  llvm::SmallVector<Selector, 256> AllSelectors;
4896  for (auto &SelectorAndID : SelectorIDs)
4897  AllSelectors.push_back(SelectorAndID.first);
4898  for (auto &Selector : AllSelectors)
4900 
4901  // Form the record of special types.
4902  RecordData SpecialTypes;
4903  AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4904  AddTypeRef(Context.getFILEType(), SpecialTypes);
4905  AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4906  AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4907  AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4908  AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4909  AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4910  AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4911 
4912  if (Chain) {
4913  // Write the mapping information describing our module dependencies and how
4914  // each of those modules were mapped into our own offset/ID space, so that
4915  // the reader can build the appropriate mapping to its own offset/ID space.
4916  // The map consists solely of a blob with the following format:
4917  // *(module-kind:i8
4918  // module-name-len:i16 module-name:len*i8
4919  // source-location-offset:i32
4920  // identifier-id:i32
4921  // preprocessed-entity-id:i32
4922  // macro-definition-id:i32
4923  // submodule-id:i32
4924  // selector-id:i32
4925  // declaration-id:i32
4926  // c++-base-specifiers-id:i32
4927  // type-id:i32)
4928  //
4929  // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
4930  // MK_ExplicitModule, then the module-name is the module name. Otherwise,
4931  // it is the module file name.
4932  auto Abbrev = std::make_shared<BitCodeAbbrev>();
4933  Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4934  Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4935  unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
4936  SmallString<2048> Buffer;
4937  {
4938  llvm::raw_svector_ostream Out(Buffer);
4939  for (ModuleFile &M : Chain->ModuleMgr) {
4940  using namespace llvm::support;
4941 
4942  endian::Writer LE(Out, little);
4943  LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
4944  StringRef Name =
4946  ? M.ModuleName
4947  : M.FileName;
4948  LE.write<uint16_t>(Name.size());
4949  Out.write(Name.data(), Name.size());
4950 
4951  // Note: if a base ID was uint max, it would not be possible to load
4952  // another module after it or have more than one entity inside it.
4954 
4955  auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
4956  assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
4957  if (ShouldWrite)
4958  LE.write<uint32_t>(BaseID);
4959  else
4960  LE.write<uint32_t>(None);
4961  };
4962 
4963  // These values should be unique within a chain, since they will be read
4964  // as keys into ContinuousRangeMaps.
4965  writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
4966  writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
4967  writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
4968  writeBaseIDOrNone(M.BasePreprocessedEntityID,
4970  writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
4971  writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
4972  writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
4973  writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
4974  }
4975  }
4976  RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
4977  Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4978  Buffer.data(), Buffer.size());
4979  }
4980 
4981  RecordData DeclUpdatesOffsetsRecord;
4982 
4983  // Keep writing types, declarations, and declaration update records
4984  // until we've emitted all of them.
4985  Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
4986  WriteTypeAbbrevs();
4987  WriteDeclAbbrevs();
4988  do {
4989  WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4990  while (!DeclTypesToEmit.empty()) {
4991  DeclOrType DOT = DeclTypesToEmit.front();
4992  DeclTypesToEmit.pop();
4993  if (DOT.isType())
4994  WriteType(DOT.getType());
4995  else
4996  WriteDecl(Context, DOT.getDecl());
4997  }
4998  } while (!DeclUpdates.empty());
4999  Stream.ExitBlock();
5000 
5001  DoneWritingDeclsAndTypes = true;
5002 
5003  // These things can only be done once we've written out decls and types.
5004  WriteTypeDeclOffsets();
5005  if (!DeclUpdatesOffsetsRecord.empty())
5006  Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
5007  WriteFileDeclIDsMap();
5008  WriteSourceManagerBlock(Context.getSourceManager(), PP);
5009  WriteComments();
5010  WritePreprocessor(PP, isModule);
5011  WriteHeaderSearch(PP.getHeaderSearchInfo());
5012  WriteSelectors(SemaRef);
5013  WriteReferencedSelectorsPool(SemaRef);
5014  WriteLateParsedTemplates(SemaRef);
5015  WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
5016  WriteFPPragmaOptions(SemaRef.getFPOptions());
5017  WriteOpenCLExtensions(SemaRef);
5018  WriteOpenCLExtensionTypes(SemaRef);
5019  WriteOpenCLExtensionDecls(SemaRef);
5020  WriteCUDAPragmas(SemaRef);
5021 
5022  // If we're emitting a module, write out the submodule information.
5023  if (WritingModule)
5024  WriteSubmodules(WritingModule);
5025 
5026  Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
5027 
5028  // Write the record containing external, unnamed definitions.
5029  if (!EagerlyDeserializedDecls.empty())
5030  Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
5031 
5032  if (!ModularCodegenDecls.empty())
5033  Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
5034 
5035  // Write the record containing tentative definitions.
5036  if (!TentativeDefinitions.empty())
5037  Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
5038 
5039  // Write the record containing unused file scoped decls.
5040  if (!UnusedFileScopedDecls.empty())
5041  Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
5042 
5043  // Write the record containing weak undeclared identifiers.
5044  if (!WeakUndeclaredIdentifiers.empty())
5045  Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
5046  WeakUndeclaredIdentifiers);
5047 
5048  // Write the record containing ext_vector type names.
5049  if (!ExtVectorDecls.empty())
5050  Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
5051 
5052  // Write the record containing VTable uses information.
5053  if (!VTableUses.empty())
5054  Stream.EmitRecord(VTABLE_USES, VTableUses);
5055 
5056  // Write the record containing potentially unused local typedefs.
5057  if (!UnusedLocalTypedefNameCandidates.empty())
5058  Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
5059  UnusedLocalTypedefNameCandidates);
5060 
5061  // Write the record containing pending implicit instantiations.
5062  if (!PendingInstantiations.empty())
5063  Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
5064 
5065  // Write the record containing declaration references of Sema.
5066  if (!SemaDeclRefs.empty())
5067  Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
5068 
5069  // Write the record containing CUDA-specific declaration references.
5070  if (!CUDASpecialDeclRefs.empty())
5071  Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
5072 
5073  // Write the delegating constructors.
5074  if (!DelegatingCtorDecls.empty())
5075  Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
5076 
5077  // Write the known namespaces.
5078  if (!KnownNamespaces.empty())
5079  Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
5080 
5081  // Write the undefined internal functions and variables, and inline functions.
5082  if (!UndefinedButUsed.empty())
5083  Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
5084 
5085  if (!DeleteExprsToAnalyze.empty())
5086  Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
5087 
5088  // Write the visible updates to DeclContexts.
5089  for (auto *DC : UpdatedDeclContexts)
5090  WriteDeclContextVisibleUpdate(DC);
5091 
5092  if (!WritingModule) {
5093  // Write the submodules that were imported, if any.
5094  struct ModuleInfo {
5095  uint64_t ID;
5096  Module *M;
5097  ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
5098  };
5100  for (const auto *I : Context.local_imports()) {
5101  assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
5102  Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
5103  I->getImportedModule()));
5104  }
5105 
5106  if (!Imports.empty()) {
5107  auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
5108  return A.ID < B.ID;
5109  };
5110  auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
5111  return A.ID == B.ID;
5112  };
5113 
5114  // Sort and deduplicate module IDs.
5115  llvm::sort(Imports.begin(), Imports.end(), Cmp);
5116  Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
5117  Imports.end());
5118 
5119  RecordData ImportedModules;
5120  for (const auto &Import : Imports) {
5121  ImportedModules.push_back(Import.ID);
5122  // FIXME: If the module has macros imported then later has declarations
5123  // imported, this location won't be the right one as a location for the
5124  // declaration imports.
5125  AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
5126  }
5127 
5128  Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
5129  }
5130  }
5131 
5132  WriteObjCCategories();
5133  if(!WritingModule) {
5134  WriteOptimizePragmaOptions(SemaRef);
5135  WriteMSStructPragmaOptions(SemaRef);
5136  WriteMSPointersToMembersPragmaOptions(SemaRef);
5137  }
5138  WritePackPragmaOptions(SemaRef);
5139 
5140  // Some simple statistics
5141  RecordData::value_type Record[] = {
5142  NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
5143  Stream.EmitRecord(STATISTICS, Record);
5144  Stream.ExitBlock();
5145 
5146  // Write the module file extension blocks.
5147  for (const auto &ExtWriter : ModuleFileExtensionWriters)
5148  WriteModuleFileExtension(SemaRef, *ExtWriter);
5149 
5150  return writeUnhashedControlBlock(PP, Context);
5151 }
5152 
5153 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
5154  if (DeclUpdates.empty())
5155  return;
5156 
5157  DeclUpdateMap LocalUpdates;
5158  LocalUpdates.swap(DeclUpdates);
5159 
5160  for (auto &DeclUpdate : LocalUpdates) {
5161  const Decl *D = DeclUpdate.first;
5162 
5163  bool HasUpdatedBody = false;
5165  ASTRecordWriter Record(*this, RecordData);
5166  for (auto &Update : DeclUpdate.second) {
5168 
5169  // An updated body is emitted last, so that the reader doesn't need
5170  // to skip over the lazy body to reach statements for other records.
5172  HasUpdatedBody = true;
5173  else
5174  Record.push_back(Kind);
5175 
5176  switch (Kind) {
5180  assert(Update.getDecl() && "no decl to add?");
5181  Record.push_back(GetDeclRef(Update.getDecl()));
5182  break;
5183 
5185  break;
5186 
5188  // FIXME: Do we need to also save the template specialization kind here?
5189  Record.AddSourceLocation(Update.getLoc());
5190  break;
5191 
5193  const VarDecl *VD = cast<VarDecl>(D);
5194  Record.push_back(VD->isInline());
5195  Record.push_back(VD->isInlineSpecified());
5196  if (VD->getInit()) {
5197  Record.push_back(!VD->isInitKnownICE() ? 1
5198  : (VD->isInitICE() ? 3 : 2));
5199  Record.AddStmt(const_cast<Expr*>(VD->getInit()));
5200  } else {
5201  Record.push_back(0);
5202  }
5203  break;
5204  }
5205 
5207  Record.AddStmt(const_cast<Expr *>(
5208  cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
5209  break;
5210 
5212  Record.AddStmt(
5213  cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
5214  break;
5215 
5217  auto *RD = cast<CXXRecordDecl>(D);
5218  UpdatedDeclContexts.insert(RD->getPrimaryContext());
5219  Record.push_back(RD->isParamDestroyedInCallee());
5220  Record.push_back(RD->getArgPassingRestrictions());
5221  Record.AddCXXDefinitionData(RD);
5222  Record.AddOffset(WriteDeclContextLexicalBlock(
5223  *Context, const_cast<CXXRecordDecl *>(RD)));
5224 
5225  // This state is sometimes updated by template instantiation, when we
5226  // switch from the specialization referring to the template declaration
5227  // to it referring to the template definition.
5228  if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
5229  Record.push_back(MSInfo->getTemplateSpecializationKind());
5230  Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
5231  } else {
5232  auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
5233  Record.push_back(Spec->getTemplateSpecializationKind());
5234  Record.AddSourceLocation(Spec->getPointOfInstantiation());
5235 
5236  // The instantiation might have been resolved to a partial
5237  // specialization. If so, record which one.
5238  auto From = Spec->getInstantiatedFrom();
5239  if (auto PartialSpec =
5240  From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
5241  Record.push_back(true);
5242  Record.AddDeclRef(PartialSpec);
5243  Record.AddTemplateArgumentList(
5244  &Spec->getTemplateInstantiationArgs());
5245  } else {
5246  Record.push_back(false);
5247  }
5248  }
5249  Record.push_back(RD->getTagKind());
5250  Record.AddSourceLocation(RD->getLocation());
5251  Record.AddSourceLocation(RD->getBeginLoc());
5252  Record.AddSourceRange(RD->getBraceRange());
5253 
5254  // Instantiation may change attributes; write them all out afresh.
5255  Record.push_back(D->hasAttrs());
5256  if (D->hasAttrs())
5257  Record.AddAttributes(D->getAttrs());
5258 
5259  // FIXME: Ensure we don't get here for explicit instantiations.
5260  break;
5261  }
5262 
5264  Record.AddDeclRef(Update.getDecl());
5265  Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
5266  break;
5267 
5270  cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
5271  Record);
5272  break;
5273 
5275  Record.push_back(GetOrCreateTypeID(Update.getType()));
5276  break;
5277 
5278  case UPD_DECL_MARKED_USED:
5279  break;
5280 
5281  case UPD_MANGLING_NUMBER:
5283  Record.push_back(Update.getNumber());
5284  break;
5285 
5287  Record.AddSourceRange(
5288  D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
5289  break;
5290 
5292  Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
5293  Record.AddSourceRange(
5294  D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
5295  break;
5296 
5297  case UPD_DECL_EXPORTED:
5298  Record.push_back(getSubmoduleID(Update.getModule()));
5299  break;
5300 
5302  Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
5303  break;
5304  }
5305  }
5306 
5307  if (HasUpdatedBody) {
5308  const auto *Def = cast<FunctionDecl>(D);
5310  Record.push_back(Def->isInlined());
5311  Record.AddSourceLocation(Def->getInnerLocStart());
5312  Record.AddFunctionDefinition(Def);
5313  }
5314 
5315  OffsetsRecord.push_back(GetDeclRef(D));
5316  OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
5317  }
5318 }
5319 
5321  uint32_t Raw = Loc.getRawEncoding();
5322  Record.push_back((Raw << 1) | (Raw >> 31));
5323 }
5324 
5326  AddSourceLocation(Range.getBegin(), Record);
5327  AddSourceLocation(Range.getEnd(), Record);
5328 }
5329 
5330 void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
5331  Record->push_back(Value.getBitWidth());
5332  const uint64_t *Words = Value.getRawData();
5333  Record->append(Words, Words + Value.getNumWords());
5334 }
5335 
5336 void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
5337  Record->push_back(Value.isUnsigned());
5338  AddAPInt(Value);
5339 }
5340 
5341 void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
5342  AddAPInt(Value.bitcastToAPInt());
5343 }
5344 
5346  Record.push_back(getIdentifierRef(II));
5347 }
5348 
5350  if (!II)
5351  return 0;
5352 
5353  IdentID &ID = IdentifierIDs[II];
5354  if (ID == 0)
5355  ID = NextIdentID++;
5356  return ID;
5357 }
5358 
5360  // Don't emit builtin macros like __LINE__ to the AST file unless they
5361  // have been redefined by the header (in which case they are not
5362  // isBuiltinMacro).
5363  if (!MI || MI->isBuiltinMacro())
5364  return 0;
5365 
5366  MacroID &ID = MacroIDs[MI];
5367  if (ID == 0) {
5368  ID = NextMacroID++;
5369  MacroInfoToEmitData Info = { Name, MI, ID };
5370  MacroInfosToEmit.push_back(Info);
5371  }
5372  return ID;
5373 }
5374 
5376  if (!MI || MI->isBuiltinMacro())
5377  return 0;
5378 
5379  assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
5380  return MacroIDs[MI];
5381 }
5382 
5384  return IdentMacroDirectivesOffsetMap.lookup(Name);
5385 }
5386 
5388  Record->push_back(Writer->getSelectorRef(SelRef));
5389 }
5390 
5392  if (Sel.getAsOpaquePtr() == nullptr) {
5393  return 0;
5394  }
5395 
5396  SelectorID SID = SelectorIDs[Sel];
5397  if (SID == 0 && Chain) {
5398  // This might trigger a ReadSelector callback, which will set the ID for
5399  // this selector.
5400  Chain->LoadSelector(Sel);
5401  SID = SelectorIDs[Sel];
5402  }
5403  if (SID == 0) {
5404  SID = NextSelectorID++;
5405  SelectorIDs[Sel] = SID;
5406  }
5407  return SID;
5408 }
5409 
5411  AddDeclRef(Temp->getDestructor());
5412 }
5413 
5416  switch (Kind) {
5418  AddStmt(Arg.getAsExpr());
5419  break;
5421  AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
5422  break;
5424  AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5426  break;
5428  AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
5431  break;
5437  // FIXME: Is this right?
5438  break;
5439  }
5440 }
5441 
5443  AddTemplateArgument(Arg.getArgument());
5444 
5446  bool InfoHasSameExpr
5447  = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
5448  Record->push_back(InfoHasSameExpr);
5449  if (InfoHasSameExpr)
5450  return; // Avoid storing the same expr twice.
5451  }
5452  AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
5453 }
5454 
5456  if (!TInfo) {
5457  AddTypeRef(QualType());
5458  return;
5459  }
5460 
5461  AddTypeRef(TInfo->getType());
5462  AddTypeLoc(TInfo->getTypeLoc());
5463 }
5464 
5466  TypeLocWriter TLW(*this);
5467  for (; !TL.isNull(); TL = TL.getNextTypeLoc())
5468  TLW.Visit(TL);
5469 }
5470 
5472  Record.push_back(GetOrCreateTypeID(T));
5473 }
5474 
5476  assert(Context);
5477  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5478  if (T.isNull())
5479  return TypeIdx();
5480  assert(!T.getLocalFastQualifiers());
5481 
5482  TypeIdx &Idx = TypeIdxs[T];
5483  if (Idx.getIndex() == 0) {
5484  if (DoneWritingDeclsAndTypes) {
5485  assert(0 && "New type seen after serializing all the types to emit!");
5486  return TypeIdx();
5487  }
5488 
5489  // We haven't seen this type before. Assign it a new ID and put it
5490  // into the queue of types to emit.
5491  Idx = TypeIdx(NextTypeID++);
5492  DeclTypesToEmit.push(T);
5493  }
5494  return Idx;
5495  });
5496 }
5497 
5499  assert(Context);
5500  return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
5501  if (T.isNull())
5502  return TypeIdx();
5503  assert(!T.getLocalFastQualifiers());
5504 
5505  TypeIdxMap::const_iterator I = TypeIdxs.find(T);
5506  assert(I != TypeIdxs.end() && "Type not emitted!");
5507  return I->second;
5508  });
5509 }
5510 
5511 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
5512  Record.push_back(GetDeclRef(D));
5513 }
5514 
5516  assert(WritingAST && "Cannot request a declaration ID before AST writing");
5517 
5518  if (!D) {
5519  return 0;
5520  }
5521 
5522  // If D comes from an AST file, its declaration ID is already known and
5523  // fixed.
5524  if (D->isFromASTFile())
5525  return D->getGlobalID();
5526 
5527  assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
5528  DeclID &ID = DeclIDs[D];
5529  if (ID == 0) {
5530  if (DoneWritingDeclsAndTypes) {
5531  assert(0 && "New decl seen after serializing all the decls to emit!");
5532  return 0;
5533  }
5534 
5535  // We haven't seen this declaration before. Give it a new ID and
5536  // enqueue it in the list of declarations to emit.
5537  ID = NextDeclID++;
5538  DeclTypesToEmit.push(const_cast<Decl *>(D));
5539  }
5540 
5541  return ID;
5542 }
5543 
5545  if (!D)
5546  return 0;
5547 
5548  // If D comes from an AST file, its declaration ID is already known and
5549  // fixed.
5550  if (D->isFromASTFile())
5551  return D->getGlobalID();
5552 
5553  assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
5554  return DeclIDs[D];
5555 }
5556 
5557 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
5558  assert(ID);
5559  assert(D);
5560 
5561  SourceLocation Loc = D->getLocation();
5562  if (Loc.isInvalid())
5563  return;
5564 
5565  // We only keep track of the file-level declarations of each file.
5566  if (!D->getLexicalDeclContext()->isFileContext())
5567  return;
5568  // FIXME: ParmVarDecls that are part of a function type of a parameter of
5569  // a function/objc method, should not have TU as lexical context.
5570  // TemplateTemplateParmDecls that are part of an alias template, should not
5571  // have TU as lexical context.
5572  if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
5573  return;
5574 
5575  SourceManager &SM = Context->getSourceManager();
5576  SourceLocation FileLoc = SM.getFileLoc(Loc);
5577  assert(SM.isLocalSourceLocation(FileLoc));
5578  FileID FID;
5579  unsigned Offset;
5580  std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
5581  if (FID.isInvalid())
5582  return;
5583  assert(SM.getSLocEntry(FID).isFile());
5584 
5585  DeclIDInFileInfo *&Info = FileDeclIDs[FID];
5586  if (!Info)
5587  Info = new DeclIDInFileInfo();
5588 
5589  std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
5590  LocDeclIDsTy &Decls = Info->DeclIDs;
5591 
5592  if (Decls.empty() || Decls.back().first <= Offset) {
5593  Decls.push_back(LocDecl);
5594  return;
5595  }
5596 
5597  LocDeclIDsTy::iterator I =
5598  std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
5599 
5600  Decls.insert(I, LocDecl);
5601 }
5602 
5604  // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
5605  Record->push_back(Name.getNameKind());
5606  switch (Name.getNameKind()) {
5609  break;
5610 
5614  AddSelectorRef(Name.getObjCSelector());
5615  break;
5616 
5620  AddTypeRef(Name.getCXXNameType());
5621  break;
5622 
5625  break;
5626 
5628  Record->push_back(Name.getCXXOverloadedOperator());
5629  break;
5630 
5633  break;
5634 
5636  // No extra data to emit
5637  break;
5638  }
5639 }
5640 
5642  assert(needsAnonymousDeclarationNumber(D) &&
5643  "expected an anonymous declaration");
5644 
5645  // Number the anonymous declarations within this context, if we've not
5646  // already done so.
5647  auto It = AnonymousDeclarationNumbers.find(D);
5648  if (It == AnonymousDeclarationNumbers.end()) {
5649  auto *DC = D->getLexicalDeclContext();
5650  numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
5651  AnonymousDeclarationNumbers[ND] = Number;
5652  });
5653 
5654  It = AnonymousDeclarationNumbers.find(D);
5655  assert(It != AnonymousDeclarationNumbers.end() &&
5656  "declaration not found within its lexical context");
5657  }
5658 
5659  return It->second;
5660 }
5661 
5663  DeclarationName Name) {
5664  switch (Name.getNameKind()) {
5668  AddTypeSourceInfo(DNLoc.NamedType.TInfo);
5669  break;
5670 
5676  break;
5677 
5681  break;
5682 
5689  break;
5690  }
5691 }
5692 
5694  const DeclarationNameInfo &NameInfo) {
5695  AddDeclarationName(NameInfo.getName());
5696  AddSourceLocation(NameInfo.getLoc());
5697  AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
5698 }
5699 
5701  AddNestedNameSpecifierLoc(Info.QualifierLoc);
5702  Record->push_back(Info.NumTemplParamLists);
5703  for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
5704  AddTemplateParameterList(Info.TemplParamLists[i]);
5705 }
5706 
5708  // Nested name specifiers usually aren't too long. I think that 8 would
5709  // typically accommodate the vast majority.
5711 
5712  // Push each of the NNS's onto a stack for serialization in reverse order.
5713  while (NNS) {
5714  NestedNames.push_back(NNS);
5715  NNS = NNS->getPrefix();
5716  }
5717 
5718  Record->push_back(NestedNames.size());
5719  while(!NestedNames.empty()) {
5720  NNS = NestedNames.pop_back_val();
5722  Record->push_back(Kind);
5723  switch (Kind) {
5726  break;
5727 
5729  AddDeclRef(NNS->getAsNamespace());
5730  break;
5731 
5734  break;
5735 
5738  AddTypeRef(QualType(NNS->getAsType(), 0));
5739  Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5740  break;
5741 
57