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