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