1 //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTWriter class, which writes AST files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Serialization/ASTWriter.h"
15 #include "ASTCommon.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclContextInternals.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclLookups.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/FileSystemStatCache.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/SourceManagerInternals.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Basic/TargetOptions.h"
33 #include "clang/Basic/Version.h"
34 #include "clang/Basic/VersionTuple.h"
35 #include "clang/Lex/HeaderSearch.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/MacroInfo.h"
38 #include "clang/Lex/PreprocessingRecord.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Lex/PreprocessorOptions.h"
41 #include "clang/Sema/IdentifierResolver.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Serialization/ASTReader.h"
44 #include "llvm/ADT/APFloat.h"
45 #include "llvm/ADT/APInt.h"
46 #include "llvm/ADT/Hashing.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Bitcode/BitstreamWriter.h"
49 #include "llvm/Support/EndianStream.h"
50 #include "llvm/Support/FileSystem.h"
51 #include "llvm/Support/MemoryBuffer.h"
52 #include "llvm/Support/OnDiskHashTable.h"
53 #include "llvm/Support/Path.h"
54 #include <algorithm>
55 #include <cstdio>
56 #include <string.h>
57 #include <utility>
58 using namespace clang;
59 using namespace clang::serialization;
60 
61 template <typename T, typename Allocator>
62 static StringRef data(const std::vector<T, Allocator> &v) {
63   if (v.empty()) return StringRef();
64   return StringRef(reinterpret_cast<const char*>(&v[0]),
65                          sizeof(T) * v.size());
66 }
67 
68 template <typename T>
69 static StringRef data(const SmallVectorImpl<T> &v) {
70   return StringRef(reinterpret_cast<const char*>(v.data()),
71                          sizeof(T) * v.size());
72 }
73 
74 //===----------------------------------------------------------------------===//
75 // Type serialization
76 //===----------------------------------------------------------------------===//
77 
78 namespace {
79   class ASTTypeWriter {
80     ASTWriter &Writer;
81     ASTWriter::RecordDataImpl &Record;
82 
83   public:
84     /// \brief Type code that corresponds to the record generated.
85     TypeCode Code;
86 
87     ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
88       : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
89 
90     void VisitArrayType(const ArrayType *T);
91     void VisitFunctionType(const FunctionType *T);
92     void VisitTagType(const TagType *T);
93 
94 #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
95 #define ABSTRACT_TYPE(Class, Base)
96 #include "clang/AST/TypeNodes.def"
97   };
98 }
99 
100 void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
101   llvm_unreachable("Built-in types are never serialized");
102 }
103 
104 void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
105   Writer.AddTypeRef(T->getElementType(), Record);
106   Code = TYPE_COMPLEX;
107 }
108 
109 void ASTTypeWriter::VisitPointerType(const PointerType *T) {
110   Writer.AddTypeRef(T->getPointeeType(), Record);
111   Code = TYPE_POINTER;
112 }
113 
114 void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
115   Writer.AddTypeRef(T->getOriginalType(), Record);
116   Code = TYPE_DECAYED;
117 }
118 
119 void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
120   Writer.AddTypeRef(T->getOriginalType(), Record);
121   Writer.AddTypeRef(T->getAdjustedType(), Record);
122   Code = TYPE_ADJUSTED;
123 }
124 
125 void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
126   Writer.AddTypeRef(T->getPointeeType(), Record);
127   Code = TYPE_BLOCK_POINTER;
128 }
129 
130 void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
131   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
132   Record.push_back(T->isSpelledAsLValue());
133   Code = TYPE_LVALUE_REFERENCE;
134 }
135 
136 void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
137   Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
138   Code = TYPE_RVALUE_REFERENCE;
139 }
140 
141 void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
142   Writer.AddTypeRef(T->getPointeeType(), Record);
143   Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
144   Code = TYPE_MEMBER_POINTER;
145 }
146 
147 void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
148   Writer.AddTypeRef(T->getElementType(), Record);
149   Record.push_back(T->getSizeModifier()); // FIXME: stable values
150   Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
151 }
152 
153 void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
154   VisitArrayType(T);
155   Writer.AddAPInt(T->getSize(), Record);
156   Code = TYPE_CONSTANT_ARRAY;
157 }
158 
159 void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
160   VisitArrayType(T);
161   Code = TYPE_INCOMPLETE_ARRAY;
162 }
163 
164 void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
165   VisitArrayType(T);
166   Writer.AddSourceLocation(T->getLBracketLoc(), Record);
167   Writer.AddSourceLocation(T->getRBracketLoc(), Record);
168   Writer.AddStmt(T->getSizeExpr());
169   Code = TYPE_VARIABLE_ARRAY;
170 }
171 
172 void ASTTypeWriter::VisitVectorType(const VectorType *T) {
173   Writer.AddTypeRef(T->getElementType(), Record);
174   Record.push_back(T->getNumElements());
175   Record.push_back(T->getVectorKind());
176   Code = TYPE_VECTOR;
177 }
178 
179 void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
180   VisitVectorType(T);
181   Code = TYPE_EXT_VECTOR;
182 }
183 
184 void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
185   Writer.AddTypeRef(T->getReturnType(), Record);
186   FunctionType::ExtInfo C = T->getExtInfo();
187   Record.push_back(C.getNoReturn());
188   Record.push_back(C.getHasRegParm());
189   Record.push_back(C.getRegParm());
190   // FIXME: need to stabilize encoding of calling convention...
191   Record.push_back(C.getCC());
192   Record.push_back(C.getProducesResult());
193 }
194 
195 void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
196   VisitFunctionType(T);
197   Code = TYPE_FUNCTION_NO_PROTO;
198 }
199 
200 static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
201                              ASTWriter::RecordDataImpl &Record) {
202   Record.push_back(T->getExceptionSpecType());
203   if (T->getExceptionSpecType() == EST_Dynamic) {
204     Record.push_back(T->getNumExceptions());
205     for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
206       Writer.AddTypeRef(T->getExceptionType(I), Record);
207   } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
208     Writer.AddStmt(T->getNoexceptExpr());
209   } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
210     Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
211     Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
212   } else if (T->getExceptionSpecType() == EST_Unevaluated) {
213     Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
214   }
215 }
216 
217 void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
218   VisitFunctionType(T);
219   Record.push_back(T->getNumParams());
220   for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
221     Writer.AddTypeRef(T->getParamType(I), Record);
222   Record.push_back(T->isVariadic());
223   Record.push_back(T->hasTrailingReturn());
224   Record.push_back(T->getTypeQuals());
225   Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
226   addExceptionSpec(Writer, T, Record);
227   Code = TYPE_FUNCTION_PROTO;
228 }
229 
230 void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
231   Writer.AddDeclRef(T->getDecl(), Record);
232   Code = TYPE_UNRESOLVED_USING;
233 }
234 
235 void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
236   Writer.AddDeclRef(T->getDecl(), Record);
237   assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
238   Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
239   Code = TYPE_TYPEDEF;
240 }
241 
242 void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
243   Writer.AddStmt(T->getUnderlyingExpr());
244   Code = TYPE_TYPEOF_EXPR;
245 }
246 
247 void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
248   Writer.AddTypeRef(T->getUnderlyingType(), Record);
249   Code = TYPE_TYPEOF;
250 }
251 
252 void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
253   Writer.AddTypeRef(T->getUnderlyingType(), Record);
254   Writer.AddStmt(T->getUnderlyingExpr());
255   Code = TYPE_DECLTYPE;
256 }
257 
258 void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
259   Writer.AddTypeRef(T->getBaseType(), Record);
260   Writer.AddTypeRef(T->getUnderlyingType(), Record);
261   Record.push_back(T->getUTTKind());
262   Code = TYPE_UNARY_TRANSFORM;
263 }
264 
265 void ASTTypeWriter::VisitAutoType(const AutoType *T) {
266   Writer.AddTypeRef(T->getDeducedType(), Record);
267   Record.push_back(T->isDecltypeAuto());
268   if (T->getDeducedType().isNull())
269     Record.push_back(T->isDependentType());
270   Code = TYPE_AUTO;
271 }
272 
273 void ASTTypeWriter::VisitTagType(const TagType *T) {
274   Record.push_back(T->isDependentType());
275   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
276   assert(!T->isBeingDefined() &&
277          "Cannot serialize in the middle of a type definition");
278 }
279 
280 void ASTTypeWriter::VisitRecordType(const RecordType *T) {
281   VisitTagType(T);
282   Code = TYPE_RECORD;
283 }
284 
285 void ASTTypeWriter::VisitEnumType(const EnumType *T) {
286   VisitTagType(T);
287   Code = TYPE_ENUM;
288 }
289 
290 void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
291   Writer.AddTypeRef(T->getModifiedType(), Record);
292   Writer.AddTypeRef(T->getEquivalentType(), Record);
293   Record.push_back(T->getAttrKind());
294   Code = TYPE_ATTRIBUTED;
295 }
296 
297 void
298 ASTTypeWriter::VisitSubstTemplateTypeParmType(
299                                         const SubstTemplateTypeParmType *T) {
300   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
301   Writer.AddTypeRef(T->getReplacementType(), Record);
302   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
303 }
304 
305 void
306 ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
307                                       const SubstTemplateTypeParmPackType *T) {
308   Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
309   Writer.AddTemplateArgument(T->getArgumentPack(), Record);
310   Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
311 }
312 
313 void
314 ASTTypeWriter::VisitTemplateSpecializationType(
315                                        const TemplateSpecializationType *T) {
316   Record.push_back(T->isDependentType());
317   Writer.AddTemplateName(T->getTemplateName(), Record);
318   Record.push_back(T->getNumArgs());
319   for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
320          ArgI != ArgE; ++ArgI)
321     Writer.AddTemplateArgument(*ArgI, Record);
322   Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
323                     T->isCanonicalUnqualified() ? QualType()
324                                                 : T->getCanonicalTypeInternal(),
325                     Record);
326   Code = TYPE_TEMPLATE_SPECIALIZATION;
327 }
328 
329 void
330 ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
331   VisitArrayType(T);
332   Writer.AddStmt(T->getSizeExpr());
333   Writer.AddSourceRange(T->getBracketsRange(), Record);
334   Code = TYPE_DEPENDENT_SIZED_ARRAY;
335 }
336 
337 void
338 ASTTypeWriter::VisitDependentSizedExtVectorType(
339                                         const DependentSizedExtVectorType *T) {
340   // FIXME: Serialize this type (C++ only)
341   llvm_unreachable("Cannot serialize dependent sized extended vector types");
342 }
343 
344 void
345 ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
346   Record.push_back(T->getDepth());
347   Record.push_back(T->getIndex());
348   Record.push_back(T->isParameterPack());
349   Writer.AddDeclRef(T->getDecl(), Record);
350   Code = TYPE_TEMPLATE_TYPE_PARM;
351 }
352 
353 void
354 ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
355   Record.push_back(T->getKeyword());
356   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
357   Writer.AddIdentifierRef(T->getIdentifier(), Record);
358   Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
359                                                 : T->getCanonicalTypeInternal(),
360                     Record);
361   Code = TYPE_DEPENDENT_NAME;
362 }
363 
364 void
365 ASTTypeWriter::VisitDependentTemplateSpecializationType(
366                                 const DependentTemplateSpecializationType *T) {
367   Record.push_back(T->getKeyword());
368   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
369   Writer.AddIdentifierRef(T->getIdentifier(), Record);
370   Record.push_back(T->getNumArgs());
371   for (DependentTemplateSpecializationType::iterator
372          I = T->begin(), E = T->end(); I != E; ++I)
373     Writer.AddTemplateArgument(*I, Record);
374   Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
375 }
376 
377 void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
378   Writer.AddTypeRef(T->getPattern(), Record);
379   if (Optional<unsigned> NumExpansions = T->getNumExpansions())
380     Record.push_back(*NumExpansions + 1);
381   else
382     Record.push_back(0);
383   Code = TYPE_PACK_EXPANSION;
384 }
385 
386 void ASTTypeWriter::VisitParenType(const ParenType *T) {
387   Writer.AddTypeRef(T->getInnerType(), Record);
388   Code = TYPE_PAREN;
389 }
390 
391 void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
392   Record.push_back(T->getKeyword());
393   Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
394   Writer.AddTypeRef(T->getNamedType(), Record);
395   Code = TYPE_ELABORATED;
396 }
397 
398 void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
399   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
400   Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
401   Code = TYPE_INJECTED_CLASS_NAME;
402 }
403 
404 void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
405   Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
406   Code = TYPE_OBJC_INTERFACE;
407 }
408 
409 void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
410   Writer.AddTypeRef(T->getBaseType(), Record);
411   Record.push_back(T->getNumProtocols());
412   for (const auto *I : T->quals())
413     Writer.AddDeclRef(I, Record);
414   Code = TYPE_OBJC_OBJECT;
415 }
416 
417 void
418 ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
419   Writer.AddTypeRef(T->getPointeeType(), Record);
420   Code = TYPE_OBJC_OBJECT_POINTER;
421 }
422 
423 void
424 ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
425   Writer.AddTypeRef(T->getValueType(), Record);
426   Code = TYPE_ATOMIC;
427 }
428 
429 namespace {
430 
431 class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
432   ASTWriter &Writer;
433   ASTWriter::RecordDataImpl &Record;
434 
435 public:
436   TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
437     : Writer(Writer), Record(Record) { }
438 
439 #define ABSTRACT_TYPELOC(CLASS, PARENT)
440 #define TYPELOC(CLASS, PARENT) \
441     void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
442 #include "clang/AST/TypeLocNodes.def"
443 
444   void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
445   void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
446 };
447 
448 }
449 
450 void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
451   // nothing to do
452 }
453 void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
454   Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
455   if (TL.needsExtraLocalData()) {
456     Record.push_back(TL.getWrittenTypeSpec());
457     Record.push_back(TL.getWrittenSignSpec());
458     Record.push_back(TL.getWrittenWidthSpec());
459     Record.push_back(TL.hasModeAttr());
460   }
461 }
462 void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
463   Writer.AddSourceLocation(TL.getNameLoc(), Record);
464 }
465 void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
466   Writer.AddSourceLocation(TL.getStarLoc(), Record);
467 }
468 void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
469   // nothing to do
470 }
471 void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
472   // nothing to do
473 }
474 void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
475   Writer.AddSourceLocation(TL.getCaretLoc(), Record);
476 }
477 void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
478   Writer.AddSourceLocation(TL.getAmpLoc(), Record);
479 }
480 void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
481   Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
482 }
483 void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
484   Writer.AddSourceLocation(TL.getStarLoc(), Record);
485   Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
486 }
487 void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
488   Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
489   Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
490   Record.push_back(TL.getSizeExpr() ? 1 : 0);
491   if (TL.getSizeExpr())
492     Writer.AddStmt(TL.getSizeExpr());
493 }
494 void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
495   VisitArrayTypeLoc(TL);
496 }
497 void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
498   VisitArrayTypeLoc(TL);
499 }
500 void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
501   VisitArrayTypeLoc(TL);
502 }
503 void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
504                                             DependentSizedArrayTypeLoc TL) {
505   VisitArrayTypeLoc(TL);
506 }
507 void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
508                                         DependentSizedExtVectorTypeLoc TL) {
509   Writer.AddSourceLocation(TL.getNameLoc(), Record);
510 }
511 void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
512   Writer.AddSourceLocation(TL.getNameLoc(), Record);
513 }
514 void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
515   Writer.AddSourceLocation(TL.getNameLoc(), Record);
516 }
517 void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
518   Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
519   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
520   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
521   Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
522   for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
523     Writer.AddDeclRef(TL.getParam(i), Record);
524 }
525 void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
526   VisitFunctionTypeLoc(TL);
527 }
528 void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
529   VisitFunctionTypeLoc(TL);
530 }
531 void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
532   Writer.AddSourceLocation(TL.getNameLoc(), Record);
533 }
534 void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
535   Writer.AddSourceLocation(TL.getNameLoc(), Record);
536 }
537 void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
538   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
539   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
540   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
541 }
542 void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
543   Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
544   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
545   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
546   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
547 }
548 void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
549   Writer.AddSourceLocation(TL.getNameLoc(), Record);
550 }
551 void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
552   Writer.AddSourceLocation(TL.getKWLoc(), Record);
553   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
554   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
555   Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
556 }
557 void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
558   Writer.AddSourceLocation(TL.getNameLoc(), Record);
559 }
560 void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
561   Writer.AddSourceLocation(TL.getNameLoc(), Record);
562 }
563 void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
564   Writer.AddSourceLocation(TL.getNameLoc(), Record);
565 }
566 void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
567   Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
568   if (TL.hasAttrOperand()) {
569     SourceRange range = TL.getAttrOperandParensRange();
570     Writer.AddSourceLocation(range.getBegin(), Record);
571     Writer.AddSourceLocation(range.getEnd(), Record);
572   }
573   if (TL.hasAttrExprOperand()) {
574     Expr *operand = TL.getAttrExprOperand();
575     Record.push_back(operand ? 1 : 0);
576     if (operand) Writer.AddStmt(operand);
577   } else if (TL.hasAttrEnumOperand()) {
578     Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
579   }
580 }
581 void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
582   Writer.AddSourceLocation(TL.getNameLoc(), Record);
583 }
584 void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
585                                             SubstTemplateTypeParmTypeLoc TL) {
586   Writer.AddSourceLocation(TL.getNameLoc(), Record);
587 }
588 void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
589                                           SubstTemplateTypeParmPackTypeLoc TL) {
590   Writer.AddSourceLocation(TL.getNameLoc(), Record);
591 }
592 void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
593                                            TemplateSpecializationTypeLoc TL) {
594   Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
595   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
596   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
597   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
598   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
599     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
600                                       TL.getArgLoc(i).getLocInfo(), Record);
601 }
602 void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
603   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
604   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
605 }
606 void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
607   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
608   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
609 }
610 void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
611   Writer.AddSourceLocation(TL.getNameLoc(), Record);
612 }
613 void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
614   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
615   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
616   Writer.AddSourceLocation(TL.getNameLoc(), Record);
617 }
618 void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
619        DependentTemplateSpecializationTypeLoc TL) {
620   Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
621   Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
622   Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
623   Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
624   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
625   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
626   for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
627     Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
628                                       TL.getArgLoc(I).getLocInfo(), Record);
629 }
630 void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
631   Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
632 }
633 void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
634   Writer.AddSourceLocation(TL.getNameLoc(), Record);
635 }
636 void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
637   Record.push_back(TL.hasBaseTypeAsWritten());
638   Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
639   Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
640   for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
641     Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
642 }
643 void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
644   Writer.AddSourceLocation(TL.getStarLoc(), Record);
645 }
646 void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
647   Writer.AddSourceLocation(TL.getKWLoc(), Record);
648   Writer.AddSourceLocation(TL.getLParenLoc(), Record);
649   Writer.AddSourceLocation(TL.getRParenLoc(), Record);
650 }
651 
652 //===----------------------------------------------------------------------===//
653 // ASTWriter Implementation
654 //===----------------------------------------------------------------------===//
655 
656 static void EmitBlockID(unsigned ID, const char *Name,
657                         llvm::BitstreamWriter &Stream,
658                         ASTWriter::RecordDataImpl &Record) {
659   Record.clear();
660   Record.push_back(ID);
661   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
662 
663   // Emit the block name if present.
664   if (!Name || Name[0] == 0)
665     return;
666   Record.clear();
667   while (*Name)
668     Record.push_back(*Name++);
669   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
670 }
671 
672 static void EmitRecordID(unsigned ID, const char *Name,
673                          llvm::BitstreamWriter &Stream,
674                          ASTWriter::RecordDataImpl &Record) {
675   Record.clear();
676   Record.push_back(ID);
677   while (*Name)
678     Record.push_back(*Name++);
679   Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
680 }
681 
682 static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
683                           ASTWriter::RecordDataImpl &Record) {
684 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
685   RECORD(STMT_STOP);
686   RECORD(STMT_NULL_PTR);
687   RECORD(STMT_NULL);
688   RECORD(STMT_COMPOUND);
689   RECORD(STMT_CASE);
690   RECORD(STMT_DEFAULT);
691   RECORD(STMT_LABEL);
692   RECORD(STMT_ATTRIBUTED);
693   RECORD(STMT_IF);
694   RECORD(STMT_SWITCH);
695   RECORD(STMT_WHILE);
696   RECORD(STMT_DO);
697   RECORD(STMT_FOR);
698   RECORD(STMT_GOTO);
699   RECORD(STMT_INDIRECT_GOTO);
700   RECORD(STMT_CONTINUE);
701   RECORD(STMT_BREAK);
702   RECORD(STMT_RETURN);
703   RECORD(STMT_DECL);
704   RECORD(STMT_GCCASM);
705   RECORD(STMT_MSASM);
706   RECORD(EXPR_PREDEFINED);
707   RECORD(EXPR_DECL_REF);
708   RECORD(EXPR_INTEGER_LITERAL);
709   RECORD(EXPR_FLOATING_LITERAL);
710   RECORD(EXPR_IMAGINARY_LITERAL);
711   RECORD(EXPR_STRING_LITERAL);
712   RECORD(EXPR_CHARACTER_LITERAL);
713   RECORD(EXPR_PAREN);
714   RECORD(EXPR_UNARY_OPERATOR);
715   RECORD(EXPR_SIZEOF_ALIGN_OF);
716   RECORD(EXPR_ARRAY_SUBSCRIPT);
717   RECORD(EXPR_CALL);
718   RECORD(EXPR_MEMBER);
719   RECORD(EXPR_BINARY_OPERATOR);
720   RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
721   RECORD(EXPR_CONDITIONAL_OPERATOR);
722   RECORD(EXPR_IMPLICIT_CAST);
723   RECORD(EXPR_CSTYLE_CAST);
724   RECORD(EXPR_COMPOUND_LITERAL);
725   RECORD(EXPR_EXT_VECTOR_ELEMENT);
726   RECORD(EXPR_INIT_LIST);
727   RECORD(EXPR_DESIGNATED_INIT);
728   RECORD(EXPR_IMPLICIT_VALUE_INIT);
729   RECORD(EXPR_VA_ARG);
730   RECORD(EXPR_ADDR_LABEL);
731   RECORD(EXPR_STMT);
732   RECORD(EXPR_CHOOSE);
733   RECORD(EXPR_GNU_NULL);
734   RECORD(EXPR_SHUFFLE_VECTOR);
735   RECORD(EXPR_BLOCK);
736   RECORD(EXPR_GENERIC_SELECTION);
737   RECORD(EXPR_OBJC_STRING_LITERAL);
738   RECORD(EXPR_OBJC_BOXED_EXPRESSION);
739   RECORD(EXPR_OBJC_ARRAY_LITERAL);
740   RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
741   RECORD(EXPR_OBJC_ENCODE);
742   RECORD(EXPR_OBJC_SELECTOR_EXPR);
743   RECORD(EXPR_OBJC_PROTOCOL_EXPR);
744   RECORD(EXPR_OBJC_IVAR_REF_EXPR);
745   RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
746   RECORD(EXPR_OBJC_KVC_REF_EXPR);
747   RECORD(EXPR_OBJC_MESSAGE_EXPR);
748   RECORD(STMT_OBJC_FOR_COLLECTION);
749   RECORD(STMT_OBJC_CATCH);
750   RECORD(STMT_OBJC_FINALLY);
751   RECORD(STMT_OBJC_AT_TRY);
752   RECORD(STMT_OBJC_AT_SYNCHRONIZED);
753   RECORD(STMT_OBJC_AT_THROW);
754   RECORD(EXPR_OBJC_BOOL_LITERAL);
755   RECORD(EXPR_CXX_OPERATOR_CALL);
756   RECORD(EXPR_CXX_CONSTRUCT);
757   RECORD(EXPR_CXX_STATIC_CAST);
758   RECORD(EXPR_CXX_DYNAMIC_CAST);
759   RECORD(EXPR_CXX_REINTERPRET_CAST);
760   RECORD(EXPR_CXX_CONST_CAST);
761   RECORD(EXPR_CXX_FUNCTIONAL_CAST);
762   RECORD(EXPR_USER_DEFINED_LITERAL);
763   RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
764   RECORD(EXPR_CXX_BOOL_LITERAL);
765   RECORD(EXPR_CXX_NULL_PTR_LITERAL);
766   RECORD(EXPR_CXX_TYPEID_EXPR);
767   RECORD(EXPR_CXX_TYPEID_TYPE);
768   RECORD(EXPR_CXX_UUIDOF_EXPR);
769   RECORD(EXPR_CXX_UUIDOF_TYPE);
770   RECORD(EXPR_CXX_THIS);
771   RECORD(EXPR_CXX_THROW);
772   RECORD(EXPR_CXX_DEFAULT_ARG);
773   RECORD(EXPR_CXX_BIND_TEMPORARY);
774   RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
775   RECORD(EXPR_CXX_NEW);
776   RECORD(EXPR_CXX_DELETE);
777   RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
778   RECORD(EXPR_EXPR_WITH_CLEANUPS);
779   RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
780   RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
781   RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
782   RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
783   RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
784   RECORD(EXPR_CXX_NOEXCEPT);
785   RECORD(EXPR_OPAQUE_VALUE);
786   RECORD(EXPR_PACK_EXPANSION);
787   RECORD(EXPR_SIZEOF_PACK);
788   RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
789   RECORD(EXPR_CUDA_KERNEL_CALL);
790 #undef RECORD
791 }
792 
793 void ASTWriter::WriteBlockInfoBlock() {
794   RecordData Record;
795   Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
796 
797 #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
798 #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
799 
800   // Control Block.
801   BLOCK(CONTROL_BLOCK);
802   RECORD(METADATA);
803   RECORD(MODULE_NAME);
804   RECORD(MODULE_MAP_FILE);
805   RECORD(IMPORTS);
806   RECORD(LANGUAGE_OPTIONS);
807   RECORD(TARGET_OPTIONS);
808   RECORD(ORIGINAL_FILE);
809   RECORD(ORIGINAL_PCH_DIR);
810   RECORD(ORIGINAL_FILE_ID);
811   RECORD(INPUT_FILE_OFFSETS);
812   RECORD(DIAGNOSTIC_OPTIONS);
813   RECORD(FILE_SYSTEM_OPTIONS);
814   RECORD(HEADER_SEARCH_OPTIONS);
815   RECORD(PREPROCESSOR_OPTIONS);
816 
817   BLOCK(INPUT_FILES_BLOCK);
818   RECORD(INPUT_FILE);
819 
820   // AST Top-Level Block.
821   BLOCK(AST_BLOCK);
822   RECORD(TYPE_OFFSET);
823   RECORD(DECL_OFFSET);
824   RECORD(IDENTIFIER_OFFSET);
825   RECORD(IDENTIFIER_TABLE);
826   RECORD(EAGERLY_DESERIALIZED_DECLS);
827   RECORD(SPECIAL_TYPES);
828   RECORD(STATISTICS);
829   RECORD(TENTATIVE_DEFINITIONS);
830   RECORD(UNUSED_FILESCOPED_DECLS);
831   RECORD(LOCALLY_SCOPED_EXTERN_C_DECLS);
832   RECORD(SELECTOR_OFFSETS);
833   RECORD(METHOD_POOL);
834   RECORD(PP_COUNTER_VALUE);
835   RECORD(SOURCE_LOCATION_OFFSETS);
836   RECORD(SOURCE_LOCATION_PRELOADS);
837   RECORD(EXT_VECTOR_DECLS);
838   RECORD(PPD_ENTITIES_OFFSETS);
839   RECORD(REFERENCED_SELECTOR_POOL);
840   RECORD(TU_UPDATE_LEXICAL);
841   RECORD(LOCAL_REDECLARATIONS_MAP);
842   RECORD(SEMA_DECL_REFS);
843   RECORD(WEAK_UNDECLARED_IDENTIFIERS);
844   RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
845   RECORD(DECL_REPLACEMENTS);
846   RECORD(UPDATE_VISIBLE);
847   RECORD(DECL_UPDATE_OFFSETS);
848   RECORD(DECL_UPDATES);
849   RECORD(CXX_BASE_SPECIFIER_OFFSETS);
850   RECORD(DIAG_PRAGMA_MAPPINGS);
851   RECORD(CUDA_SPECIAL_DECL_REFS);
852   RECORD(HEADER_SEARCH_TABLE);
853   RECORD(FP_PRAGMA_OPTIONS);
854   RECORD(OPENCL_EXTENSIONS);
855   RECORD(DELEGATING_CTORS);
856   RECORD(KNOWN_NAMESPACES);
857   RECORD(UNDEFINED_BUT_USED);
858   RECORD(MODULE_OFFSET_MAP);
859   RECORD(SOURCE_MANAGER_LINE_TABLE);
860   RECORD(OBJC_CATEGORIES_MAP);
861   RECORD(FILE_SORTED_DECLS);
862   RECORD(IMPORTED_MODULES);
863   RECORD(MERGED_DECLARATIONS);
864   RECORD(LOCAL_REDECLARATIONS);
865   RECORD(OBJC_CATEGORIES);
866   RECORD(MACRO_OFFSET);
867   RECORD(MACRO_TABLE);
868   RECORD(LATE_PARSED_TEMPLATE);
869   RECORD(OPTIMIZE_PRAGMA_OPTIONS);
870 
871   // SourceManager Block.
872   BLOCK(SOURCE_MANAGER_BLOCK);
873   RECORD(SM_SLOC_FILE_ENTRY);
874   RECORD(SM_SLOC_BUFFER_ENTRY);
875   RECORD(SM_SLOC_BUFFER_BLOB);
876   RECORD(SM_SLOC_EXPANSION_ENTRY);
877 
878   // Preprocessor Block.
879   BLOCK(PREPROCESSOR_BLOCK);
880   RECORD(PP_MACRO_OBJECT_LIKE);
881   RECORD(PP_MACRO_FUNCTION_LIKE);
882   RECORD(PP_TOKEN);
883 
884   // Decls and Types block.
885   BLOCK(DECLTYPES_BLOCK);
886   RECORD(TYPE_EXT_QUAL);
887   RECORD(TYPE_COMPLEX);
888   RECORD(TYPE_POINTER);
889   RECORD(TYPE_BLOCK_POINTER);
890   RECORD(TYPE_LVALUE_REFERENCE);
891   RECORD(TYPE_RVALUE_REFERENCE);
892   RECORD(TYPE_MEMBER_POINTER);
893   RECORD(TYPE_CONSTANT_ARRAY);
894   RECORD(TYPE_INCOMPLETE_ARRAY);
895   RECORD(TYPE_VARIABLE_ARRAY);
896   RECORD(TYPE_VECTOR);
897   RECORD(TYPE_EXT_VECTOR);
898   RECORD(TYPE_FUNCTION_PROTO);
899   RECORD(TYPE_FUNCTION_NO_PROTO);
900   RECORD(TYPE_TYPEDEF);
901   RECORD(TYPE_TYPEOF_EXPR);
902   RECORD(TYPE_TYPEOF);
903   RECORD(TYPE_RECORD);
904   RECORD(TYPE_ENUM);
905   RECORD(TYPE_OBJC_INTERFACE);
906   RECORD(TYPE_OBJC_OBJECT);
907   RECORD(TYPE_OBJC_OBJECT_POINTER);
908   RECORD(TYPE_DECLTYPE);
909   RECORD(TYPE_ELABORATED);
910   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
911   RECORD(TYPE_UNRESOLVED_USING);
912   RECORD(TYPE_INJECTED_CLASS_NAME);
913   RECORD(TYPE_OBJC_OBJECT);
914   RECORD(TYPE_TEMPLATE_TYPE_PARM);
915   RECORD(TYPE_TEMPLATE_SPECIALIZATION);
916   RECORD(TYPE_DEPENDENT_NAME);
917   RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
918   RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
919   RECORD(TYPE_PAREN);
920   RECORD(TYPE_PACK_EXPANSION);
921   RECORD(TYPE_ATTRIBUTED);
922   RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
923   RECORD(TYPE_ATOMIC);
924   RECORD(DECL_TYPEDEF);
925   RECORD(DECL_ENUM);
926   RECORD(DECL_RECORD);
927   RECORD(DECL_ENUM_CONSTANT);
928   RECORD(DECL_FUNCTION);
929   RECORD(DECL_OBJC_METHOD);
930   RECORD(DECL_OBJC_INTERFACE);
931   RECORD(DECL_OBJC_PROTOCOL);
932   RECORD(DECL_OBJC_IVAR);
933   RECORD(DECL_OBJC_AT_DEFS_FIELD);
934   RECORD(DECL_OBJC_CATEGORY);
935   RECORD(DECL_OBJC_CATEGORY_IMPL);
936   RECORD(DECL_OBJC_IMPLEMENTATION);
937   RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
938   RECORD(DECL_OBJC_PROPERTY);
939   RECORD(DECL_OBJC_PROPERTY_IMPL);
940   RECORD(DECL_FIELD);
941   RECORD(DECL_MS_PROPERTY);
942   RECORD(DECL_VAR);
943   RECORD(DECL_IMPLICIT_PARAM);
944   RECORD(DECL_PARM_VAR);
945   RECORD(DECL_FILE_SCOPE_ASM);
946   RECORD(DECL_BLOCK);
947   RECORD(DECL_CONTEXT_LEXICAL);
948   RECORD(DECL_CONTEXT_VISIBLE);
949   RECORD(DECL_NAMESPACE);
950   RECORD(DECL_NAMESPACE_ALIAS);
951   RECORD(DECL_USING);
952   RECORD(DECL_USING_SHADOW);
953   RECORD(DECL_USING_DIRECTIVE);
954   RECORD(DECL_UNRESOLVED_USING_VALUE);
955   RECORD(DECL_UNRESOLVED_USING_TYPENAME);
956   RECORD(DECL_LINKAGE_SPEC);
957   RECORD(DECL_CXX_RECORD);
958   RECORD(DECL_CXX_METHOD);
959   RECORD(DECL_CXX_CONSTRUCTOR);
960   RECORD(DECL_CXX_DESTRUCTOR);
961   RECORD(DECL_CXX_CONVERSION);
962   RECORD(DECL_ACCESS_SPEC);
963   RECORD(DECL_FRIEND);
964   RECORD(DECL_FRIEND_TEMPLATE);
965   RECORD(DECL_CLASS_TEMPLATE);
966   RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
967   RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
968   RECORD(DECL_VAR_TEMPLATE);
969   RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
970   RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
971   RECORD(DECL_FUNCTION_TEMPLATE);
972   RECORD(DECL_TEMPLATE_TYPE_PARM);
973   RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
974   RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
975   RECORD(DECL_STATIC_ASSERT);
976   RECORD(DECL_CXX_BASE_SPECIFIERS);
977   RECORD(DECL_INDIRECTFIELD);
978   RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
979 
980   // Statements and Exprs can occur in the Decls and Types block.
981   AddStmtsExprs(Stream, Record);
982 
983   BLOCK(PREPROCESSOR_DETAIL_BLOCK);
984   RECORD(PPD_MACRO_EXPANSION);
985   RECORD(PPD_MACRO_DEFINITION);
986   RECORD(PPD_INCLUSION_DIRECTIVE);
987 
988 #undef RECORD
989 #undef BLOCK
990   Stream.ExitBlock();
991 }
992 
993 /// \brief Adjusts the given filename to only write out the portion of the
994 /// filename that is not part of the system root directory.
995 ///
996 /// \param Filename the file name to adjust.
997 ///
998 /// \param isysroot When non-NULL, the PCH file is a relocatable PCH file and
999 /// the returned filename will be adjusted by this system root.
1000 ///
1001 /// \returns either the original filename (if it needs no adjustment) or the
1002 /// adjusted filename (which points into the @p Filename parameter).
1003 static const char *
1004 adjustFilenameForRelocatablePCH(const char *Filename, StringRef isysroot) {
1005   assert(Filename && "No file name to adjust?");
1006 
1007   if (isysroot.empty())
1008     return Filename;
1009 
1010   // Verify that the filename and the system root have the same prefix.
1011   unsigned Pos = 0;
1012   for (; Filename[Pos] && Pos < isysroot.size(); ++Pos)
1013     if (Filename[Pos] != isysroot[Pos])
1014       return Filename; // Prefixes don't match.
1015 
1016   // We hit the end of the filename before we hit the end of the system root.
1017   if (!Filename[Pos])
1018     return Filename;
1019 
1020   // If the file name has a '/' at the current position, skip over the '/'.
1021   // We distinguish sysroot-based includes from absolute includes by the
1022   // absence of '/' at the beginning of sysroot-based includes.
1023   if (Filename[Pos] == '/')
1024     ++Pos;
1025 
1026   return Filename + Pos;
1027 }
1028 
1029 /// \brief Write the control block.
1030 void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
1031                                   StringRef isysroot,
1032                                   const std::string &OutputFile) {
1033   using namespace llvm;
1034   Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
1035   RecordData Record;
1036 
1037   // Metadata
1038   BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
1039   MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
1040   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
1041   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
1042   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
1043   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
1044   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
1045   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
1046   MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
1047   unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
1048   Record.push_back(METADATA);
1049   Record.push_back(VERSION_MAJOR);
1050   Record.push_back(VERSION_MINOR);
1051   Record.push_back(CLANG_VERSION_MAJOR);
1052   Record.push_back(CLANG_VERSION_MINOR);
1053   Record.push_back(!isysroot.empty());
1054   Record.push_back(ASTHasCompilerErrors);
1055   Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
1056                             getClangFullRepositoryVersion());
1057 
1058   // Module name
1059   if (WritingModule) {
1060     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1061     Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
1062     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
1063     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1064     RecordData Record;
1065     Record.push_back(MODULE_NAME);
1066     Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
1067   }
1068 
1069   // Module map file
1070   if (WritingModule) {
1071     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1072     Abbrev->Add(BitCodeAbbrevOp(MODULE_MAP_FILE));
1073     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Filename
1074     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1075 
1076     assert(WritingModule->ModuleMap && "missing module map");
1077     SmallString<128> ModuleMap(WritingModule->ModuleMap->getName());
1078     llvm::sys::fs::make_absolute(ModuleMap);
1079     RecordData Record;
1080     Record.push_back(MODULE_MAP_FILE);
1081     Stream.EmitRecordWithBlob(AbbrevCode, Record, ModuleMap.str());
1082   }
1083 
1084   // Imports
1085   if (Chain) {
1086     serialization::ModuleManager &Mgr = Chain->getModuleManager();
1087     Record.clear();
1088 
1089     for (ModuleManager::ModuleIterator M = Mgr.begin(), MEnd = Mgr.end();
1090          M != MEnd; ++M) {
1091       // Skip modules that weren't directly imported.
1092       if (!(*M)->isDirectlyImported())
1093         continue;
1094 
1095       Record.push_back((unsigned)(*M)->Kind); // FIXME: Stable encoding
1096       AddSourceLocation((*M)->ImportLoc, Record);
1097       Record.push_back((*M)->File->getSize());
1098       Record.push_back((*M)->File->getModificationTime());
1099       const std::string &FileName = (*M)->FileName;
1100       Record.push_back(FileName.size());
1101       Record.append(FileName.begin(), FileName.end());
1102     }
1103     Stream.EmitRecord(IMPORTS, Record);
1104   }
1105 
1106   // Language options.
1107   Record.clear();
1108   const LangOptions &LangOpts = Context.getLangOpts();
1109 #define LANGOPT(Name, Bits, Default, Description) \
1110   Record.push_back(LangOpts.Name);
1111 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1112   Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
1113 #include "clang/Basic/LangOptions.def"
1114 #define SANITIZER(NAME, ID) Record.push_back(LangOpts.Sanitize.ID);
1115 #include "clang/Basic/Sanitizers.def"
1116 
1117   Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
1118   AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
1119 
1120   Record.push_back(LangOpts.CurrentModule.size());
1121   Record.append(LangOpts.CurrentModule.begin(), LangOpts.CurrentModule.end());
1122 
1123   // Comment options.
1124   Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
1125   for (CommentOptions::BlockCommandNamesTy::const_iterator
1126            I = LangOpts.CommentOpts.BlockCommandNames.begin(),
1127            IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
1128        I != IEnd; ++I) {
1129     AddString(*I, Record);
1130   }
1131   Record.push_back(LangOpts.CommentOpts.ParseAllComments);
1132 
1133   Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
1134 
1135   // Target options.
1136   Record.clear();
1137   const TargetInfo &Target = Context.getTargetInfo();
1138   const TargetOptions &TargetOpts = Target.getTargetOpts();
1139   AddString(TargetOpts.Triple, Record);
1140   AddString(TargetOpts.CPU, Record);
1141   AddString(TargetOpts.ABI, Record);
1142   Record.push_back(TargetOpts.FeaturesAsWritten.size());
1143   for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
1144     AddString(TargetOpts.FeaturesAsWritten[I], Record);
1145   }
1146   Record.push_back(TargetOpts.Features.size());
1147   for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
1148     AddString(TargetOpts.Features[I], Record);
1149   }
1150   Stream.EmitRecord(TARGET_OPTIONS, Record);
1151 
1152   // Diagnostic options.
1153   Record.clear();
1154   const DiagnosticOptions &DiagOpts
1155     = Context.getDiagnostics().getDiagnosticOptions();
1156 #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
1157 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
1158   Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
1159 #include "clang/Basic/DiagnosticOptions.def"
1160   Record.push_back(DiagOpts.Warnings.size());
1161   for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
1162     AddString(DiagOpts.Warnings[I], Record);
1163   // Note: we don't serialize the log or serialization file names, because they
1164   // are generally transient files and will almost always be overridden.
1165   Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
1166 
1167   // File system options.
1168   Record.clear();
1169   const FileSystemOptions &FSOpts
1170     = Context.getSourceManager().getFileManager().getFileSystemOptions();
1171   AddString(FSOpts.WorkingDir, Record);
1172   Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
1173 
1174   // Header search options.
1175   Record.clear();
1176   const HeaderSearchOptions &HSOpts
1177     = PP.getHeaderSearchInfo().getHeaderSearchOpts();
1178   AddString(HSOpts.Sysroot, Record);
1179 
1180   // Include entries.
1181   Record.push_back(HSOpts.UserEntries.size());
1182   for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
1183     const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
1184     AddString(Entry.Path, Record);
1185     Record.push_back(static_cast<unsigned>(Entry.Group));
1186     Record.push_back(Entry.IsFramework);
1187     Record.push_back(Entry.IgnoreSysRoot);
1188   }
1189 
1190   // System header prefixes.
1191   Record.push_back(HSOpts.SystemHeaderPrefixes.size());
1192   for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
1193     AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
1194     Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
1195   }
1196 
1197   AddString(HSOpts.ResourceDir, Record);
1198   AddString(HSOpts.ModuleCachePath, Record);
1199   AddString(HSOpts.ModuleUserBuildPath, Record);
1200   Record.push_back(HSOpts.DisableModuleHash);
1201   Record.push_back(HSOpts.UseBuiltinIncludes);
1202   Record.push_back(HSOpts.UseStandardSystemIncludes);
1203   Record.push_back(HSOpts.UseStandardCXXIncludes);
1204   Record.push_back(HSOpts.UseLibcxx);
1205   Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
1206 
1207   // Preprocessor options.
1208   Record.clear();
1209   const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
1210 
1211   // Macro definitions.
1212   Record.push_back(PPOpts.Macros.size());
1213   for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
1214     AddString(PPOpts.Macros[I].first, Record);
1215     Record.push_back(PPOpts.Macros[I].second);
1216   }
1217 
1218   // Includes
1219   Record.push_back(PPOpts.Includes.size());
1220   for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
1221     AddString(PPOpts.Includes[I], Record);
1222 
1223   // Macro includes
1224   Record.push_back(PPOpts.MacroIncludes.size());
1225   for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
1226     AddString(PPOpts.MacroIncludes[I], Record);
1227 
1228   Record.push_back(PPOpts.UsePredefines);
1229   // Detailed record is important since it is used for the module cache hash.
1230   Record.push_back(PPOpts.DetailedRecord);
1231   AddString(PPOpts.ImplicitPCHInclude, Record);
1232   AddString(PPOpts.ImplicitPTHInclude, Record);
1233   Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
1234   Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
1235 
1236   // Original file name and file ID
1237   SourceManager &SM = Context.getSourceManager();
1238   if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1239     BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
1240     FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
1241     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
1242     FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1243     unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
1244 
1245     SmallString<128> MainFilePath(MainFile->getName());
1246 
1247     llvm::sys::fs::make_absolute(MainFilePath);
1248 
1249     const char *MainFileNameStr = MainFilePath.c_str();
1250     MainFileNameStr = adjustFilenameForRelocatablePCH(MainFileNameStr,
1251                                                       isysroot);
1252     Record.clear();
1253     Record.push_back(ORIGINAL_FILE);
1254     Record.push_back(SM.getMainFileID().getOpaqueValue());
1255     Stream.EmitRecordWithBlob(FileAbbrevCode, Record, MainFileNameStr);
1256   }
1257 
1258   Record.clear();
1259   Record.push_back(SM.getMainFileID().getOpaqueValue());
1260   Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
1261 
1262   // Original PCH directory
1263   if (!OutputFile.empty() && OutputFile != "-") {
1264     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1265     Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
1266     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1267     unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
1268 
1269     SmallString<128> OutputPath(OutputFile);
1270 
1271     llvm::sys::fs::make_absolute(OutputPath);
1272     StringRef origDir = llvm::sys::path::parent_path(OutputPath);
1273 
1274     RecordData Record;
1275     Record.push_back(ORIGINAL_PCH_DIR);
1276     Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
1277   }
1278 
1279   WriteInputFiles(Context.SourceMgr,
1280                   PP.getHeaderSearchInfo().getHeaderSearchOpts(),
1281                   isysroot,
1282                   PP.getLangOpts().Modules);
1283   Stream.ExitBlock();
1284 }
1285 
1286 namespace  {
1287   /// \brief An input file.
1288   struct InputFileEntry {
1289     const FileEntry *File;
1290     bool IsSystemFile;
1291     bool BufferOverridden;
1292   };
1293 }
1294 
1295 void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
1296                                 HeaderSearchOptions &HSOpts,
1297                                 StringRef isysroot,
1298                                 bool Modules) {
1299   using namespace llvm;
1300   Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
1301   RecordData Record;
1302 
1303   // Create input-file abbreviation.
1304   BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
1305   IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
1306   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
1307   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
1308   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
1309   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
1310   IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
1311   unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
1312 
1313   // Get all ContentCache objects for files, sorted by whether the file is a
1314   // system one or not. System files go at the back, users files at the front.
1315   std::deque<InputFileEntry> SortedFiles;
1316   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
1317     // Get this source location entry.
1318     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1319     assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
1320 
1321     // We only care about file entries that were not overridden.
1322     if (!SLoc->isFile())
1323       continue;
1324     const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1325     if (!Cache->OrigEntry)
1326       continue;
1327 
1328     InputFileEntry Entry;
1329     Entry.File = Cache->OrigEntry;
1330     Entry.IsSystemFile = Cache->IsSystemFile;
1331     Entry.BufferOverridden = Cache->BufferOverridden;
1332     if (Cache->IsSystemFile)
1333       SortedFiles.push_back(Entry);
1334     else
1335       SortedFiles.push_front(Entry);
1336   }
1337 
1338   unsigned UserFilesNum = 0;
1339   // Write out all of the input files.
1340   std::vector<uint32_t> InputFileOffsets;
1341   for (std::deque<InputFileEntry>::iterator
1342          I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
1343     const InputFileEntry &Entry = *I;
1344 
1345     uint32_t &InputFileID = InputFileIDs[Entry.File];
1346     if (InputFileID != 0)
1347       continue; // already recorded this file.
1348 
1349     // Record this entry's offset.
1350     InputFileOffsets.push_back(Stream.GetCurrentBitNo());
1351 
1352     InputFileID = InputFileOffsets.size();
1353 
1354     if (!Entry.IsSystemFile)
1355       ++UserFilesNum;
1356 
1357     Record.clear();
1358     Record.push_back(INPUT_FILE);
1359     Record.push_back(InputFileOffsets.size());
1360 
1361     // Emit size/modification time for this file.
1362     Record.push_back(Entry.File->getSize());
1363     Record.push_back(Entry.File->getModificationTime());
1364 
1365     // Whether this file was overridden.
1366     Record.push_back(Entry.BufferOverridden);
1367 
1368     // Turn the file name into an absolute path, if it isn't already.
1369     const char *Filename = Entry.File->getName();
1370     SmallString<128> FilePath(Filename);
1371 
1372     // Ask the file manager to fixup the relative path for us. This will
1373     // honor the working directory.
1374     SourceMgr.getFileManager().FixupRelativePath(FilePath);
1375 
1376     // FIXME: This call to make_absolute shouldn't be necessary, the
1377     // call to FixupRelativePath should always return an absolute path.
1378     llvm::sys::fs::make_absolute(FilePath);
1379     Filename = FilePath.c_str();
1380 
1381     Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1382 
1383     Stream.EmitRecordWithBlob(IFAbbrevCode, Record, Filename);
1384   }
1385 
1386   Stream.ExitBlock();
1387 
1388   // Create input file offsets abbreviation.
1389   BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
1390   OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
1391   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
1392   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
1393                                                                 //   input files
1394   OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));   // Array
1395   unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
1396 
1397   // Write input file offsets.
1398   Record.clear();
1399   Record.push_back(INPUT_FILE_OFFSETS);
1400   Record.push_back(InputFileOffsets.size());
1401   Record.push_back(UserFilesNum);
1402   Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, data(InputFileOffsets));
1403 }
1404 
1405 //===----------------------------------------------------------------------===//
1406 // Source Manager Serialization
1407 //===----------------------------------------------------------------------===//
1408 
1409 /// \brief Create an abbreviation for the SLocEntry that refers to a
1410 /// file.
1411 static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
1412   using namespace llvm;
1413   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1414   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
1415   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1416   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1417   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1418   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1419   // FileEntry fields.
1420   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
1421   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
1422   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
1423   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
1424   return Stream.EmitAbbrev(Abbrev);
1425 }
1426 
1427 /// \brief Create an abbreviation for the SLocEntry that refers to a
1428 /// buffer.
1429 static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
1430   using namespace llvm;
1431   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1432   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
1433   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1434   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
1435   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
1436   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
1437   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
1438   return Stream.EmitAbbrev(Abbrev);
1439 }
1440 
1441 /// \brief Create an abbreviation for the SLocEntry that refers to a
1442 /// buffer's blob.
1443 static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
1444   using namespace llvm;
1445   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1446   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
1447   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
1448   return Stream.EmitAbbrev(Abbrev);
1449 }
1450 
1451 /// \brief Create an abbreviation for the SLocEntry that refers to a macro
1452 /// expansion.
1453 static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
1454   using namespace llvm;
1455   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1456   Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
1457   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
1458   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
1459   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
1460   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
1461   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
1462   return Stream.EmitAbbrev(Abbrev);
1463 }
1464 
1465 namespace {
1466   // Trait used for the on-disk hash table of header search information.
1467   class HeaderFileInfoTrait {
1468     ASTWriter &Writer;
1469     const HeaderSearch &HS;
1470 
1471     // Keep track of the framework names we've used during serialization.
1472     SmallVector<char, 128> FrameworkStringData;
1473     llvm::StringMap<unsigned> FrameworkNameOffset;
1474 
1475   public:
1476     HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
1477       : Writer(Writer), HS(HS) { }
1478 
1479     struct key_type {
1480       const FileEntry *FE;
1481       const char *Filename;
1482     };
1483     typedef const key_type &key_type_ref;
1484 
1485     typedef HeaderFileInfo data_type;
1486     typedef const data_type &data_type_ref;
1487     typedef unsigned hash_value_type;
1488     typedef unsigned offset_type;
1489 
1490     static hash_value_type ComputeHash(key_type_ref key) {
1491       // The hash is based only on size/time of the file, so that the reader can
1492       // match even when symlinking or excess path elements ("foo/../", "../")
1493       // change the form of the name. However, complete path is still the key.
1494       return llvm::hash_combine(key.FE->getSize(),
1495                                 key.FE->getModificationTime());
1496     }
1497 
1498     std::pair<unsigned,unsigned>
1499     EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
1500       using namespace llvm::support;
1501       endian::Writer<little> Writer(Out);
1502       unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
1503       Writer.write<uint16_t>(KeyLen);
1504       unsigned DataLen = 1 + 2 + 4 + 4;
1505       if (Data.isModuleHeader)
1506         DataLen += 4;
1507       Writer.write<uint8_t>(DataLen);
1508       return std::make_pair(KeyLen, DataLen);
1509     }
1510 
1511     void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
1512       using namespace llvm::support;
1513       endian::Writer<little> LE(Out);
1514       LE.write<uint64_t>(key.FE->getSize());
1515       KeyLen -= 8;
1516       LE.write<uint64_t>(key.FE->getModificationTime());
1517       KeyLen -= 8;
1518       Out.write(key.Filename, KeyLen);
1519     }
1520 
1521     void EmitData(raw_ostream &Out, key_type_ref key,
1522                   data_type_ref Data, unsigned DataLen) {
1523       using namespace llvm::support;
1524       endian::Writer<little> LE(Out);
1525       uint64_t Start = Out.tell(); (void)Start;
1526 
1527       unsigned char Flags = (Data.HeaderRole << 6)
1528                           | (Data.isImport << 5)
1529                           | (Data.isPragmaOnce << 4)
1530                           | (Data.DirInfo << 2)
1531                           | (Data.Resolved << 1)
1532                           | Data.IndexHeaderMapHeader;
1533       LE.write<uint8_t>(Flags);
1534       LE.write<uint16_t>(Data.NumIncludes);
1535 
1536       if (!Data.ControllingMacro)
1537         LE.write<uint32_t>(Data.ControllingMacroID);
1538       else
1539         LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
1540 
1541       unsigned Offset = 0;
1542       if (!Data.Framework.empty()) {
1543         // If this header refers into a framework, save the framework name.
1544         llvm::StringMap<unsigned>::iterator Pos
1545           = FrameworkNameOffset.find(Data.Framework);
1546         if (Pos == FrameworkNameOffset.end()) {
1547           Offset = FrameworkStringData.size() + 1;
1548           FrameworkStringData.append(Data.Framework.begin(),
1549                                      Data.Framework.end());
1550           FrameworkStringData.push_back(0);
1551 
1552           FrameworkNameOffset[Data.Framework] = Offset;
1553         } else
1554           Offset = Pos->second;
1555       }
1556       LE.write<uint32_t>(Offset);
1557 
1558       if (Data.isModuleHeader) {
1559         Module *Mod = HS.findModuleForHeader(key.FE).getModule();
1560         LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod));
1561       }
1562 
1563       assert(Out.tell() - Start == DataLen && "Wrong data length");
1564     }
1565 
1566     const char *strings_begin() const { return FrameworkStringData.begin(); }
1567     const char *strings_end() const { return FrameworkStringData.end(); }
1568   };
1569 } // end anonymous namespace
1570 
1571 /// \brief Write the header search block for the list of files that
1572 ///
1573 /// \param HS The header search structure to save.
1574 void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS, StringRef isysroot) {
1575   SmallVector<const FileEntry *, 16> FilesByUID;
1576   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
1577 
1578   if (FilesByUID.size() > HS.header_file_size())
1579     FilesByUID.resize(HS.header_file_size());
1580 
1581   HeaderFileInfoTrait GeneratorTrait(*this, HS);
1582   llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
1583   SmallVector<const char *, 4> SavedStrings;
1584   unsigned NumHeaderSearchEntries = 0;
1585   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
1586     const FileEntry *File = FilesByUID[UID];
1587     if (!File)
1588       continue;
1589 
1590     // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
1591     // from the external source if it was not provided already.
1592     HeaderFileInfo HFI;
1593     if (!HS.tryGetFileInfo(File, HFI) ||
1594         (HFI.External && Chain) ||
1595         (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
1596       continue;
1597 
1598     // Turn the file name into an absolute path, if it isn't already.
1599     const char *Filename = File->getName();
1600     Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1601 
1602     // If we performed any translation on the file name at all, we need to
1603     // save this string, since the generator will refer to it later.
1604     if (Filename != File->getName()) {
1605       Filename = strdup(Filename);
1606       SavedStrings.push_back(Filename);
1607     }
1608 
1609     HeaderFileInfoTrait::key_type key = { File, Filename };
1610     Generator.insert(key, HFI, GeneratorTrait);
1611     ++NumHeaderSearchEntries;
1612   }
1613 
1614   // Create the on-disk hash table in a buffer.
1615   SmallString<4096> TableData;
1616   uint32_t BucketOffset;
1617   {
1618     using namespace llvm::support;
1619     llvm::raw_svector_ostream Out(TableData);
1620     // Make sure that no bucket is at offset 0
1621     endian::Writer<little>(Out).write<uint32_t>(0);
1622     BucketOffset = Generator.Emit(Out, GeneratorTrait);
1623   }
1624 
1625   // Create a blob abbreviation
1626   using namespace llvm;
1627   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1628   Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
1629   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1630   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1631   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1632   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1633   unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
1634 
1635   // Write the header search table
1636   RecordData Record;
1637   Record.push_back(HEADER_SEARCH_TABLE);
1638   Record.push_back(BucketOffset);
1639   Record.push_back(NumHeaderSearchEntries);
1640   Record.push_back(TableData.size());
1641   TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
1642   Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData.str());
1643 
1644   // Free all of the strings we had to duplicate.
1645   for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
1646     free(const_cast<char *>(SavedStrings[I]));
1647 }
1648 
1649 /// \brief Writes the block containing the serialized form of the
1650 /// source manager.
1651 ///
1652 /// TODO: We should probably use an on-disk hash table (stored in a
1653 /// blob), indexed based on the file name, so that we only create
1654 /// entries for files that we actually need. In the common case (no
1655 /// errors), we probably won't have to create file entries for any of
1656 /// the files in the AST.
1657 void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
1658                                         const Preprocessor &PP,
1659                                         StringRef isysroot) {
1660   RecordData Record;
1661 
1662   // Enter the source manager block.
1663   Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
1664 
1665   // Abbreviations for the various kinds of source-location entries.
1666   unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
1667   unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
1668   unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
1669   unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
1670 
1671   // Write out the source location entry table. We skip the first
1672   // entry, which is always the same dummy entry.
1673   std::vector<uint32_t> SLocEntryOffsets;
1674   RecordData PreloadSLocs;
1675   SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
1676   for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
1677        I != N; ++I) {
1678     // Get this source location entry.
1679     const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
1680     FileID FID = FileID::get(I);
1681     assert(&SourceMgr.getSLocEntry(FID) == SLoc);
1682 
1683     // Record the offset of this source-location entry.
1684     SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
1685 
1686     // Figure out which record code to use.
1687     unsigned Code;
1688     if (SLoc->isFile()) {
1689       const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
1690       if (Cache->OrigEntry) {
1691         Code = SM_SLOC_FILE_ENTRY;
1692       } else
1693         Code = SM_SLOC_BUFFER_ENTRY;
1694     } else
1695       Code = SM_SLOC_EXPANSION_ENTRY;
1696     Record.clear();
1697     Record.push_back(Code);
1698 
1699     // Starting offset of this entry within this module, so skip the dummy.
1700     Record.push_back(SLoc->getOffset() - 2);
1701     if (SLoc->isFile()) {
1702       const SrcMgr::FileInfo &File = SLoc->getFile();
1703       Record.push_back(File.getIncludeLoc().getRawEncoding());
1704       Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
1705       Record.push_back(File.hasLineDirectives());
1706 
1707       const SrcMgr::ContentCache *Content = File.getContentCache();
1708       if (Content->OrigEntry) {
1709         assert(Content->OrigEntry == Content->ContentsEntry &&
1710                "Writing to AST an overridden file is not supported");
1711 
1712         // The source location entry is a file. Emit input file ID.
1713         assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
1714         Record.push_back(InputFileIDs[Content->OrigEntry]);
1715 
1716         Record.push_back(File.NumCreatedFIDs);
1717 
1718         FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
1719         if (FDI != FileDeclIDs.end()) {
1720           Record.push_back(FDI->second->FirstDeclIndex);
1721           Record.push_back(FDI->second->DeclIDs.size());
1722         } else {
1723           Record.push_back(0);
1724           Record.push_back(0);
1725         }
1726 
1727         Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
1728 
1729         if (Content->BufferOverridden) {
1730           Record.clear();
1731           Record.push_back(SM_SLOC_BUFFER_BLOB);
1732           const llvm::MemoryBuffer *Buffer
1733             = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1734           Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1735                                     StringRef(Buffer->getBufferStart(),
1736                                               Buffer->getBufferSize() + 1));
1737         }
1738       } else {
1739         // The source location entry is a buffer. The blob associated
1740         // with this entry contains the contents of the buffer.
1741 
1742         // We add one to the size so that we capture the trailing NULL
1743         // that is required by llvm::MemoryBuffer::getMemBuffer (on
1744         // the reader side).
1745         const llvm::MemoryBuffer *Buffer
1746           = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
1747         const char *Name = Buffer->getBufferIdentifier();
1748         Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
1749                                   StringRef(Name, strlen(Name) + 1));
1750         Record.clear();
1751         Record.push_back(SM_SLOC_BUFFER_BLOB);
1752         Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
1753                                   StringRef(Buffer->getBufferStart(),
1754                                                   Buffer->getBufferSize() + 1));
1755 
1756         if (strcmp(Name, "<built-in>") == 0) {
1757           PreloadSLocs.push_back(SLocEntryOffsets.size());
1758         }
1759       }
1760     } else {
1761       // The source location entry is a macro expansion.
1762       const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
1763       Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
1764       Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
1765       Record.push_back(Expansion.isMacroArgExpansion() ? 0
1766                              : Expansion.getExpansionLocEnd().getRawEncoding());
1767 
1768       // Compute the token length for this macro expansion.
1769       unsigned NextOffset = SourceMgr.getNextLocalOffset();
1770       if (I + 1 != N)
1771         NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
1772       Record.push_back(NextOffset - SLoc->getOffset() - 1);
1773       Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
1774     }
1775   }
1776 
1777   Stream.ExitBlock();
1778 
1779   if (SLocEntryOffsets.empty())
1780     return;
1781 
1782   // Write the source-location offsets table into the AST block. This
1783   // table is used for lazily loading source-location information.
1784   using namespace llvm;
1785   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
1786   Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
1787   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
1788   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
1789   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
1790   unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
1791 
1792   Record.clear();
1793   Record.push_back(SOURCE_LOCATION_OFFSETS);
1794   Record.push_back(SLocEntryOffsets.size());
1795   Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
1796   Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, data(SLocEntryOffsets));
1797 
1798   // Write the source location entry preloads array, telling the AST
1799   // reader which source locations entries it should load eagerly.
1800   Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
1801 
1802   // Write the line table. It depends on remapping working, so it must come
1803   // after the source location offsets.
1804   if (SourceMgr.hasLineTable()) {
1805     LineTableInfo &LineTable = SourceMgr.getLineTable();
1806 
1807     Record.clear();
1808     // Emit the file names
1809     Record.push_back(LineTable.getNumFilenames());
1810     for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I) {
1811       // Emit the file name
1812       const char *Filename = LineTable.getFilename(I);
1813       Filename = adjustFilenameForRelocatablePCH(Filename, isysroot);
1814       unsigned FilenameLen = Filename? strlen(Filename) : 0;
1815       Record.push_back(FilenameLen);
1816       if (FilenameLen)
1817         Record.insert(Record.end(), Filename, Filename + FilenameLen);
1818     }
1819 
1820     // Emit the line entries
1821     for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
1822          L != LEnd; ++L) {
1823       // Only emit entries for local files.
1824       if (L->first.ID < 0)
1825         continue;
1826 
1827       // Emit the file ID
1828       Record.push_back(L->first.ID);
1829 
1830       // Emit the line entries
1831       Record.push_back(L->second.size());
1832       for (std::vector<LineEntry>::iterator LE = L->second.begin(),
1833                                          LEEnd = L->second.end();
1834            LE != LEEnd; ++LE) {
1835         Record.push_back(LE->FileOffset);
1836         Record.push_back(LE->LineNo);
1837         Record.push_back(LE->FilenameID);
1838         Record.push_back((unsigned)LE->FileKind);
1839         Record.push_back(LE->IncludeOffset);
1840       }
1841     }
1842     Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
1843   }
1844 }
1845 
1846 //===----------------------------------------------------------------------===//
1847 // Preprocessor Serialization
1848 //===----------------------------------------------------------------------===//
1849 
1850 namespace {
1851 class ASTMacroTableTrait {
1852 public:
1853   typedef IdentID key_type;
1854   typedef key_type key_type_ref;
1855 
1856   struct Data {
1857     uint32_t MacroDirectivesOffset;
1858   };
1859 
1860   typedef Data data_type;
1861   typedef const data_type &data_type_ref;
1862   typedef unsigned hash_value_type;
1863   typedef unsigned offset_type;
1864 
1865   static hash_value_type ComputeHash(IdentID IdID) {
1866     return llvm::hash_value(IdID);
1867   }
1868 
1869   std::pair<unsigned,unsigned>
1870   static EmitKeyDataLength(raw_ostream& Out,
1871                            key_type_ref Key, data_type_ref Data) {
1872     unsigned KeyLen = 4; // IdentID.
1873     unsigned DataLen = 4; // MacroDirectivesOffset.
1874     return std::make_pair(KeyLen, DataLen);
1875   }
1876 
1877   static void EmitKey(raw_ostream& Out, key_type_ref Key, unsigned KeyLen) {
1878     using namespace llvm::support;
1879     endian::Writer<little>(Out).write<uint32_t>(Key);
1880   }
1881 
1882   static void EmitData(raw_ostream& Out, key_type_ref Key, data_type_ref Data,
1883                        unsigned) {
1884     using namespace llvm::support;
1885     endian::Writer<little>(Out).write<uint32_t>(Data.MacroDirectivesOffset);
1886   }
1887 };
1888 } // end anonymous namespace
1889 
1890 static int compareMacroDirectives(
1891     const std::pair<const IdentifierInfo *, MacroDirective *> *X,
1892     const std::pair<const IdentifierInfo *, MacroDirective *> *Y) {
1893   return X->first->getName().compare(Y->first->getName());
1894 }
1895 
1896 static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
1897                               const Preprocessor &PP) {
1898   if (MacroInfo *MI = MD->getMacroInfo())
1899     if (MI->isBuiltinMacro())
1900       return true;
1901 
1902   if (IsModule) {
1903     // Re-export any imported directives.
1904     // FIXME: Also ensure we re-export imported #undef directives.
1905     if (auto *DMD = dyn_cast<DefMacroDirective>(MD))
1906       if (DMD->isImported())
1907         return false;
1908 
1909     SourceLocation Loc = MD->getLocation();
1910     if (Loc.isInvalid())
1911       return true;
1912     if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
1913       return true;
1914   }
1915 
1916   return false;
1917 }
1918 
1919 /// \brief Writes the block containing the serialized form of the
1920 /// preprocessor.
1921 ///
1922 void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
1923   PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
1924   if (PPRec)
1925     WritePreprocessorDetail(*PPRec);
1926 
1927   RecordData Record;
1928 
1929   // If the preprocessor __COUNTER__ value has been bumped, remember it.
1930   if (PP.getCounterValue() != 0) {
1931     Record.push_back(PP.getCounterValue());
1932     Stream.EmitRecord(PP_COUNTER_VALUE, Record);
1933     Record.clear();
1934   }
1935 
1936   // Enter the preprocessor block.
1937   Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
1938 
1939   // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
1940   // FIXME: use diagnostics subsystem for localization etc.
1941   if (PP.SawDateOrTime())
1942     fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
1943 
1944 
1945   // Loop over all the macro directives that are live at the end of the file,
1946   // emitting each to the PP section.
1947 
1948   // Construct the list of macro directives that need to be serialized.
1949   SmallVector<std::pair<const IdentifierInfo *, MacroDirective *>, 2>
1950     MacroDirectives;
1951   for (Preprocessor::macro_iterator
1952          I = PP.macro_begin(/*IncludeExternalMacros=*/false),
1953          E = PP.macro_end(/*IncludeExternalMacros=*/false);
1954        I != E; ++I) {
1955     MacroDirectives.push_back(std::make_pair(I->first, I->second));
1956   }
1957 
1958   // Sort the set of macro definitions that need to be serialized by the
1959   // name of the macro, to provide a stable ordering.
1960   llvm::array_pod_sort(MacroDirectives.begin(), MacroDirectives.end(),
1961                        &compareMacroDirectives);
1962 
1963   llvm::OnDiskChainedHashTableGenerator<ASTMacroTableTrait> Generator;
1964 
1965   // Emit the macro directives as a list and associate the offset with the
1966   // identifier they belong to.
1967   for (unsigned I = 0, N = MacroDirectives.size(); I != N; ++I) {
1968     const IdentifierInfo *Name = MacroDirectives[I].first;
1969     uint64_t MacroDirectiveOffset = Stream.GetCurrentBitNo();
1970     MacroDirective *MD = MacroDirectives[I].second;
1971 
1972     // If the macro or identifier need no updates, don't write the macro history
1973     // for this one.
1974     // FIXME: Chain the macro history instead of re-writing it.
1975     if (MD->isFromPCH() &&
1976         Name->isFromAST() && !Name->hasChangedSinceDeserialization())
1977       continue;
1978 
1979     // Emit the macro directives in reverse source order.
1980     for (; MD; MD = MD->getPrevious()) {
1981       if (shouldIgnoreMacro(MD, IsModule, PP))
1982         continue;
1983 
1984       AddSourceLocation(MD->getLocation(), Record);
1985       Record.push_back(MD->getKind());
1986       if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
1987         MacroID InfoID = getMacroRef(DefMD->getInfo(), Name);
1988         Record.push_back(InfoID);
1989         Record.push_back(DefMD->isImported());
1990         Record.push_back(DefMD->isAmbiguous());
1991 
1992       } else if (VisibilityMacroDirective *
1993                    VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
1994         Record.push_back(VisMD->isPublic());
1995       }
1996     }
1997     if (Record.empty())
1998       continue;
1999 
2000     Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
2001     Record.clear();
2002 
2003     IdentMacroDirectivesOffsetMap[Name] = MacroDirectiveOffset;
2004 
2005     IdentID NameID = getIdentifierRef(Name);
2006     ASTMacroTableTrait::Data data;
2007     data.MacroDirectivesOffset = MacroDirectiveOffset;
2008     Generator.insert(NameID, data);
2009   }
2010 
2011   /// \brief Offsets of each of the macros into the bitstream, indexed by
2012   /// the local macro ID
2013   ///
2014   /// For each identifier that is associated with a macro, this map
2015   /// provides the offset into the bitstream where that macro is
2016   /// defined.
2017   std::vector<uint32_t> MacroOffsets;
2018 
2019   for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
2020     const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
2021     MacroInfo *MI = MacroInfosToEmit[I].MI;
2022     MacroID ID = MacroInfosToEmit[I].ID;
2023 
2024     if (ID < FirstMacroID) {
2025       assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
2026       continue;
2027     }
2028 
2029     // Record the local offset of this macro.
2030     unsigned Index = ID - FirstMacroID;
2031     if (Index == MacroOffsets.size())
2032       MacroOffsets.push_back(Stream.GetCurrentBitNo());
2033     else {
2034       if (Index > MacroOffsets.size())
2035         MacroOffsets.resize(Index + 1);
2036 
2037       MacroOffsets[Index] = Stream.GetCurrentBitNo();
2038     }
2039 
2040     AddIdentifierRef(Name, Record);
2041     Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
2042     AddSourceLocation(MI->getDefinitionLoc(), Record);
2043     AddSourceLocation(MI->getDefinitionEndLoc(), Record);
2044     Record.push_back(MI->isUsed());
2045     Record.push_back(MI->isUsedForHeaderGuard());
2046     unsigned Code;
2047     if (MI->isObjectLike()) {
2048       Code = PP_MACRO_OBJECT_LIKE;
2049     } else {
2050       Code = PP_MACRO_FUNCTION_LIKE;
2051 
2052       Record.push_back(MI->isC99Varargs());
2053       Record.push_back(MI->isGNUVarargs());
2054       Record.push_back(MI->hasCommaPasting());
2055       Record.push_back(MI->getNumArgs());
2056       for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
2057            I != E; ++I)
2058         AddIdentifierRef(*I, Record);
2059     }
2060 
2061     // If we have a detailed preprocessing record, record the macro definition
2062     // ID that corresponds to this macro.
2063     if (PPRec)
2064       Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
2065 
2066     Stream.EmitRecord(Code, Record);
2067     Record.clear();
2068 
2069     // Emit the tokens array.
2070     for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
2071       // Note that we know that the preprocessor does not have any annotation
2072       // tokens in it because they are created by the parser, and thus can't
2073       // be in a macro definition.
2074       const Token &Tok = MI->getReplacementToken(TokNo);
2075       AddToken(Tok, Record);
2076       Stream.EmitRecord(PP_TOKEN, Record);
2077       Record.clear();
2078     }
2079     ++NumMacros;
2080   }
2081 
2082   Stream.ExitBlock();
2083 
2084   // Create the on-disk hash table in a buffer.
2085   SmallString<4096> MacroTable;
2086   uint32_t BucketOffset;
2087   {
2088     using namespace llvm::support;
2089     llvm::raw_svector_ostream Out(MacroTable);
2090     // Make sure that no bucket is at offset 0
2091     endian::Writer<little>(Out).write<uint32_t>(0);
2092     BucketOffset = Generator.Emit(Out);
2093   }
2094 
2095   // Write the macro table
2096   using namespace llvm;
2097   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2098   Abbrev->Add(BitCodeAbbrevOp(MACRO_TABLE));
2099   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2100   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2101   unsigned MacroTableAbbrev = Stream.EmitAbbrev(Abbrev);
2102 
2103   Record.push_back(MACRO_TABLE);
2104   Record.push_back(BucketOffset);
2105   Stream.EmitRecordWithBlob(MacroTableAbbrev, Record, MacroTable.str());
2106   Record.clear();
2107 
2108   // Write the offsets table for macro IDs.
2109   using namespace llvm;
2110   Abbrev = new BitCodeAbbrev();
2111   Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
2112   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
2113   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2114   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2115 
2116   unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2117   Record.clear();
2118   Record.push_back(MACRO_OFFSET);
2119   Record.push_back(MacroOffsets.size());
2120   Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
2121   Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
2122                             data(MacroOffsets));
2123 }
2124 
2125 void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
2126   if (PPRec.local_begin() == PPRec.local_end())
2127     return;
2128 
2129   SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
2130 
2131   // Enter the preprocessor block.
2132   Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
2133 
2134   // If the preprocessor has a preprocessing record, emit it.
2135   unsigned NumPreprocessingRecords = 0;
2136   using namespace llvm;
2137 
2138   // Set up the abbreviation for
2139   unsigned InclusionAbbrev = 0;
2140   {
2141     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2142     Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
2143     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
2144     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
2145     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
2146     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
2147     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2148     InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
2149   }
2150 
2151   unsigned FirstPreprocessorEntityID
2152     = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
2153     + NUM_PREDEF_PP_ENTITY_IDS;
2154   unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
2155   RecordData Record;
2156   for (PreprocessingRecord::iterator E = PPRec.local_begin(),
2157                                   EEnd = PPRec.local_end();
2158        E != EEnd;
2159        (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
2160     Record.clear();
2161 
2162     PreprocessedEntityOffsets.push_back(PPEntityOffset((*E)->getSourceRange(),
2163                                                      Stream.GetCurrentBitNo()));
2164 
2165     if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
2166       // Record this macro definition's ID.
2167       MacroDefinitions[MD] = NextPreprocessorEntityID;
2168 
2169       AddIdentifierRef(MD->getName(), Record);
2170       Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
2171       continue;
2172     }
2173 
2174     if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
2175       Record.push_back(ME->isBuiltinMacro());
2176       if (ME->isBuiltinMacro())
2177         AddIdentifierRef(ME->getName(), Record);
2178       else
2179         Record.push_back(MacroDefinitions[ME->getDefinition()]);
2180       Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
2181       continue;
2182     }
2183 
2184     if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
2185       Record.push_back(PPD_INCLUSION_DIRECTIVE);
2186       Record.push_back(ID->getFileName().size());
2187       Record.push_back(ID->wasInQuotes());
2188       Record.push_back(static_cast<unsigned>(ID->getKind()));
2189       Record.push_back(ID->importedModule());
2190       SmallString<64> Buffer;
2191       Buffer += ID->getFileName();
2192       // Check that the FileEntry is not null because it was not resolved and
2193       // we create a PCH even with compiler errors.
2194       if (ID->getFile())
2195         Buffer += ID->getFile()->getName();
2196       Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
2197       continue;
2198     }
2199 
2200     llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
2201   }
2202   Stream.ExitBlock();
2203 
2204   // Write the offsets table for the preprocessing record.
2205   if (NumPreprocessingRecords > 0) {
2206     assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
2207 
2208     // Write the offsets table for identifier IDs.
2209     using namespace llvm;
2210     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2211     Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
2212     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
2213     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2214     unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2215 
2216     Record.clear();
2217     Record.push_back(PPD_ENTITIES_OFFSETS);
2218     Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
2219     Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
2220                               data(PreprocessedEntityOffsets));
2221   }
2222 }
2223 
2224 unsigned ASTWriter::getSubmoduleID(Module *Mod) {
2225   llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
2226   if (Known != SubmoduleIDs.end())
2227     return Known->second;
2228 
2229   return SubmoduleIDs[Mod] = NextSubmoduleID++;
2230 }
2231 
2232 unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
2233   if (!Mod)
2234     return 0;
2235 
2236   llvm::DenseMap<Module *, unsigned>::const_iterator
2237     Known = SubmoduleIDs.find(Mod);
2238   if (Known != SubmoduleIDs.end())
2239     return Known->second;
2240 
2241   return 0;
2242 }
2243 
2244 /// \brief Compute the number of modules within the given tree (including the
2245 /// given module).
2246 static unsigned getNumberOfModules(Module *Mod) {
2247   unsigned ChildModules = 0;
2248   for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2249                                SubEnd = Mod->submodule_end();
2250        Sub != SubEnd; ++Sub)
2251     ChildModules += getNumberOfModules(*Sub);
2252 
2253   return ChildModules + 1;
2254 }
2255 
2256 void ASTWriter::WriteSubmodules(Module *WritingModule) {
2257   // Determine the dependencies of our module and each of it's submodules.
2258   // FIXME: This feels like it belongs somewhere else, but there are no
2259   // other consumers of this information.
2260   SourceManager &SrcMgr = PP->getSourceManager();
2261   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2262   for (const auto *I : Context->local_imports()) {
2263     if (Module *ImportedFrom
2264           = ModMap.inferModuleFromLocation(FullSourceLoc(I->getLocation(),
2265                                                          SrcMgr))) {
2266       ImportedFrom->Imports.push_back(I->getImportedModule());
2267     }
2268   }
2269 
2270   // Enter the submodule description block.
2271   Stream.EnterSubblock(SUBMODULE_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
2272 
2273   // Write the abbreviations needed for the submodules block.
2274   using namespace llvm;
2275   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2276   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
2277   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
2278   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
2279   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2280   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
2281   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
2282   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
2283   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
2284   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
2285   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
2286   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
2287   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2288   unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
2289 
2290   Abbrev = new BitCodeAbbrev();
2291   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
2292   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2293   unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
2294 
2295   Abbrev = new BitCodeAbbrev();
2296   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
2297   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2298   unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2299 
2300   Abbrev = new BitCodeAbbrev();
2301   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
2302   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2303   unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2304 
2305   Abbrev = new BitCodeAbbrev();
2306   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
2307   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2308   unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
2309 
2310   Abbrev = new BitCodeAbbrev();
2311   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
2312   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
2313   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Feature
2314   unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
2315 
2316   Abbrev = new BitCodeAbbrev();
2317   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
2318   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2319   unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2320 
2321   Abbrev = new BitCodeAbbrev();
2322   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
2323   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
2324   unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
2325 
2326   Abbrev = new BitCodeAbbrev();
2327   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
2328   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
2329   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));     // Name
2330   unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
2331 
2332   Abbrev = new BitCodeAbbrev();
2333   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
2334   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Macro name
2335   unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
2336 
2337   Abbrev = new BitCodeAbbrev();
2338   Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
2339   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));  // Other module
2340   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));    // Message
2341   unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
2342 
2343   // Write the submodule metadata block.
2344   RecordData Record;
2345   Record.push_back(getNumberOfModules(WritingModule));
2346   Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
2347   Stream.EmitRecord(SUBMODULE_METADATA, Record);
2348 
2349   // Write all of the submodules.
2350   std::queue<Module *> Q;
2351   Q.push(WritingModule);
2352   while (!Q.empty()) {
2353     Module *Mod = Q.front();
2354     Q.pop();
2355     unsigned ID = getSubmoduleID(Mod);
2356 
2357     // Emit the definition of the block.
2358     Record.clear();
2359     Record.push_back(SUBMODULE_DEFINITION);
2360     Record.push_back(ID);
2361     if (Mod->Parent) {
2362       assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
2363       Record.push_back(SubmoduleIDs[Mod->Parent]);
2364     } else {
2365       Record.push_back(0);
2366     }
2367     Record.push_back(Mod->IsFramework);
2368     Record.push_back(Mod->IsExplicit);
2369     Record.push_back(Mod->IsSystem);
2370     Record.push_back(Mod->IsExternC);
2371     Record.push_back(Mod->InferSubmodules);
2372     Record.push_back(Mod->InferExplicitSubmodules);
2373     Record.push_back(Mod->InferExportWildcard);
2374     Record.push_back(Mod->ConfigMacrosExhaustive);
2375     Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
2376 
2377     // Emit the requirements.
2378     for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
2379       Record.clear();
2380       Record.push_back(SUBMODULE_REQUIRES);
2381       Record.push_back(Mod->Requirements[I].second);
2382       Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
2383                                 Mod->Requirements[I].first);
2384     }
2385 
2386     // Emit the umbrella header, if there is one.
2387     if (const FileEntry *UmbrellaHeader = Mod->getUmbrellaHeader()) {
2388       Record.clear();
2389       Record.push_back(SUBMODULE_UMBRELLA_HEADER);
2390       Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
2391                                 UmbrellaHeader->getName());
2392     } else if (const DirectoryEntry *UmbrellaDir = Mod->getUmbrellaDir()) {
2393       Record.clear();
2394       Record.push_back(SUBMODULE_UMBRELLA_DIR);
2395       Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
2396                                 UmbrellaDir->getName());
2397     }
2398 
2399     // Emit the headers.
2400     for (unsigned I = 0, N = Mod->NormalHeaders.size(); I != N; ++I) {
2401       Record.clear();
2402       Record.push_back(SUBMODULE_HEADER);
2403       Stream.EmitRecordWithBlob(HeaderAbbrev, Record,
2404                                 Mod->NormalHeaders[I]->getName());
2405     }
2406     // Emit the excluded headers.
2407     for (unsigned I = 0, N = Mod->ExcludedHeaders.size(); I != N; ++I) {
2408       Record.clear();
2409       Record.push_back(SUBMODULE_EXCLUDED_HEADER);
2410       Stream.EmitRecordWithBlob(ExcludedHeaderAbbrev, Record,
2411                                 Mod->ExcludedHeaders[I]->getName());
2412     }
2413     // Emit the private headers.
2414     for (unsigned I = 0, N = Mod->PrivateHeaders.size(); I != N; ++I) {
2415       Record.clear();
2416       Record.push_back(SUBMODULE_PRIVATE_HEADER);
2417       Stream.EmitRecordWithBlob(PrivateHeaderAbbrev, Record,
2418                                 Mod->PrivateHeaders[I]->getName());
2419     }
2420     ArrayRef<const FileEntry *>
2421       TopHeaders = Mod->getTopHeaders(PP->getFileManager());
2422     for (unsigned I = 0, N = TopHeaders.size(); I != N; ++I) {
2423       Record.clear();
2424       Record.push_back(SUBMODULE_TOPHEADER);
2425       Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record,
2426                                 TopHeaders[I]->getName());
2427     }
2428 
2429     // Emit the imports.
2430     if (!Mod->Imports.empty()) {
2431       Record.clear();
2432       for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
2433         unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
2434         assert(ImportedID && "Unknown submodule!");
2435         Record.push_back(ImportedID);
2436       }
2437       Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
2438     }
2439 
2440     // Emit the exports.
2441     if (!Mod->Exports.empty()) {
2442       Record.clear();
2443       for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
2444         if (Module *Exported = Mod->Exports[I].getPointer()) {
2445           unsigned ExportedID = SubmoduleIDs[Exported];
2446           assert(ExportedID > 0 && "Unknown submodule ID?");
2447           Record.push_back(ExportedID);
2448         } else {
2449           Record.push_back(0);
2450         }
2451 
2452         Record.push_back(Mod->Exports[I].getInt());
2453       }
2454       Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
2455     }
2456 
2457     //FIXME: How do we emit the 'use'd modules?  They may not be submodules.
2458     // Might be unnecessary as use declarations are only used to build the
2459     // module itself.
2460 
2461     // Emit the link libraries.
2462     for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2463       Record.clear();
2464       Record.push_back(SUBMODULE_LINK_LIBRARY);
2465       Record.push_back(Mod->LinkLibraries[I].IsFramework);
2466       Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
2467                                 Mod->LinkLibraries[I].Library);
2468     }
2469 
2470     // Emit the conflicts.
2471     for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
2472       Record.clear();
2473       Record.push_back(SUBMODULE_CONFLICT);
2474       unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
2475       assert(OtherID && "Unknown submodule!");
2476       Record.push_back(OtherID);
2477       Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
2478                                 Mod->Conflicts[I].Message);
2479     }
2480 
2481     // Emit the configuration macros.
2482     for (unsigned I = 0, N =  Mod->ConfigMacros.size(); I != N; ++I) {
2483       Record.clear();
2484       Record.push_back(SUBMODULE_CONFIG_MACRO);
2485       Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
2486                                 Mod->ConfigMacros[I]);
2487     }
2488 
2489     // Queue up the submodules of this module.
2490     for (Module::submodule_iterator Sub = Mod->submodule_begin(),
2491                                  SubEnd = Mod->submodule_end();
2492          Sub != SubEnd; ++Sub)
2493       Q.push(*Sub);
2494   }
2495 
2496   Stream.ExitBlock();
2497 
2498   assert((NextSubmoduleID - FirstSubmoduleID
2499             == getNumberOfModules(WritingModule)) && "Wrong # of submodules");
2500 }
2501 
2502 serialization::SubmoduleID
2503 ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
2504   if (Loc.isInvalid() || !WritingModule)
2505     return 0; // No submodule
2506 
2507   // Find the module that owns this location.
2508   ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
2509   Module *OwningMod
2510     = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
2511   if (!OwningMod)
2512     return 0;
2513 
2514   // Check whether this submodule is part of our own module.
2515   if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
2516     return 0;
2517 
2518   return getSubmoduleID(OwningMod);
2519 }
2520 
2521 void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
2522                                               bool isModule) {
2523   // Make sure set diagnostic pragmas don't affect the translation unit that
2524   // imports the module.
2525   // FIXME: Make diagnostic pragma sections work properly with modules.
2526   if (isModule)
2527     return;
2528 
2529   llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
2530       DiagStateIDMap;
2531   unsigned CurrID = 0;
2532   DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
2533   RecordData Record;
2534   for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
2535          I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
2536          I != E; ++I) {
2537     const DiagnosticsEngine::DiagStatePoint &point = *I;
2538     if (point.Loc.isInvalid())
2539       continue;
2540 
2541     Record.push_back(point.Loc.getRawEncoding());
2542     unsigned &DiagStateID = DiagStateIDMap[point.State];
2543     Record.push_back(DiagStateID);
2544 
2545     if (DiagStateID == 0) {
2546       DiagStateID = ++CurrID;
2547       for (DiagnosticsEngine::DiagState::const_iterator
2548              I = point.State->begin(), E = point.State->end(); I != E; ++I) {
2549         if (I->second.isPragma()) {
2550           Record.push_back(I->first);
2551           Record.push_back((unsigned)I->second.getSeverity());
2552         }
2553       }
2554       Record.push_back(-1); // mark the end of the diag/map pairs for this
2555                             // location.
2556     }
2557   }
2558 
2559   if (!Record.empty())
2560     Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
2561 }
2562 
2563 void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
2564   if (CXXBaseSpecifiersOffsets.empty())
2565     return;
2566 
2567   RecordData Record;
2568 
2569   // Create a blob abbreviation for the C++ base specifiers offsets.
2570   using namespace llvm;
2571 
2572   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2573   Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
2574   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2575   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2576   unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2577 
2578   // Write the base specifier offsets table.
2579   Record.clear();
2580   Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
2581   Record.push_back(CXXBaseSpecifiersOffsets.size());
2582   Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
2583                             data(CXXBaseSpecifiersOffsets));
2584 }
2585 
2586 //===----------------------------------------------------------------------===//
2587 // Type Serialization
2588 //===----------------------------------------------------------------------===//
2589 
2590 /// \brief Write the representation of a type to the AST stream.
2591 void ASTWriter::WriteType(QualType T) {
2592   TypeIdx &Idx = TypeIdxs[T];
2593   if (Idx.getIndex() == 0) // we haven't seen this type before.
2594     Idx = TypeIdx(NextTypeID++);
2595 
2596   assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
2597 
2598   // Record the offset for this type.
2599   unsigned Index = Idx.getIndex() - FirstTypeID;
2600   if (TypeOffsets.size() == Index)
2601     TypeOffsets.push_back(Stream.GetCurrentBitNo());
2602   else if (TypeOffsets.size() < Index) {
2603     TypeOffsets.resize(Index + 1);
2604     TypeOffsets[Index] = Stream.GetCurrentBitNo();
2605   }
2606 
2607   RecordData Record;
2608 
2609   // Emit the type's representation.
2610   ASTTypeWriter W(*this, Record);
2611 
2612   if (T.hasLocalNonFastQualifiers()) {
2613     Qualifiers Qs = T.getLocalQualifiers();
2614     AddTypeRef(T.getLocalUnqualifiedType(), Record);
2615     Record.push_back(Qs.getAsOpaqueValue());
2616     W.Code = TYPE_EXT_QUAL;
2617   } else {
2618     switch (T->getTypeClass()) {
2619       // For all of the concrete, non-dependent types, call the
2620       // appropriate visitor function.
2621 #define TYPE(Class, Base) \
2622     case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
2623 #define ABSTRACT_TYPE(Class, Base)
2624 #include "clang/AST/TypeNodes.def"
2625     }
2626   }
2627 
2628   // Emit the serialized record.
2629   Stream.EmitRecord(W.Code, Record);
2630 
2631   // Flush any expressions that were written as part of this type.
2632   FlushStmts();
2633 }
2634 
2635 //===----------------------------------------------------------------------===//
2636 // Declaration Serialization
2637 //===----------------------------------------------------------------------===//
2638 
2639 /// \brief Write the block containing all of the declaration IDs
2640 /// lexically declared within the given DeclContext.
2641 ///
2642 /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
2643 /// bistream, or 0 if no block was written.
2644 uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
2645                                                  DeclContext *DC) {
2646   if (DC->decls_empty())
2647     return 0;
2648 
2649   uint64_t Offset = Stream.GetCurrentBitNo();
2650   RecordData Record;
2651   Record.push_back(DECL_CONTEXT_LEXICAL);
2652   SmallVector<KindDeclIDPair, 64> Decls;
2653   for (const auto *D : DC->decls())
2654     Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D)));
2655 
2656   ++NumLexicalDeclContexts;
2657   Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, data(Decls));
2658   return Offset;
2659 }
2660 
2661 void ASTWriter::WriteTypeDeclOffsets() {
2662   using namespace llvm;
2663   RecordData Record;
2664 
2665   // Write the type offsets array
2666   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2667   Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
2668   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
2669   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
2670   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
2671   unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2672   Record.clear();
2673   Record.push_back(TYPE_OFFSET);
2674   Record.push_back(TypeOffsets.size());
2675   Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
2676   Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, data(TypeOffsets));
2677 
2678   // Write the declaration offsets array
2679   Abbrev = new BitCodeAbbrev();
2680   Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
2681   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
2682   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
2683   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
2684   unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2685   Record.clear();
2686   Record.push_back(DECL_OFFSET);
2687   Record.push_back(DeclOffsets.size());
2688   Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
2689   Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, data(DeclOffsets));
2690 }
2691 
2692 void ASTWriter::WriteFileDeclIDsMap() {
2693   using namespace llvm;
2694   RecordData Record;
2695 
2696   // Join the vectors of DeclIDs from all files.
2697   SmallVector<DeclID, 256> FileSortedIDs;
2698   for (FileDeclIDsTy::iterator
2699          FI = FileDeclIDs.begin(), FE = FileDeclIDs.end(); FI != FE; ++FI) {
2700     DeclIDInFileInfo &Info = *FI->second;
2701     Info.FirstDeclIndex = FileSortedIDs.size();
2702     for (LocDeclIDsTy::iterator
2703            DI = Info.DeclIDs.begin(), DE = Info.DeclIDs.end(); DI != DE; ++DI)
2704       FileSortedIDs.push_back(DI->second);
2705   }
2706 
2707   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2708   Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
2709   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2710   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2711   unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
2712   Record.push_back(FILE_SORTED_DECLS);
2713   Record.push_back(FileSortedIDs.size());
2714   Stream.EmitRecordWithBlob(AbbrevCode, Record, data(FileSortedIDs));
2715 }
2716 
2717 void ASTWriter::WriteComments() {
2718   Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
2719   ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
2720   RecordData Record;
2721   for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
2722                                         E = RawComments.end();
2723        I != E; ++I) {
2724     Record.clear();
2725     AddSourceRange((*I)->getSourceRange(), Record);
2726     Record.push_back((*I)->getKind());
2727     Record.push_back((*I)->isTrailingComment());
2728     Record.push_back((*I)->isAlmostTrailingComment());
2729     Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
2730   }
2731   Stream.ExitBlock();
2732 }
2733 
2734 //===----------------------------------------------------------------------===//
2735 // Global Method Pool and Selector Serialization
2736 //===----------------------------------------------------------------------===//
2737 
2738 namespace {
2739 // Trait used for the on-disk hash table used in the method pool.
2740 class ASTMethodPoolTrait {
2741   ASTWriter &Writer;
2742 
2743 public:
2744   typedef Selector key_type;
2745   typedef key_type key_type_ref;
2746 
2747   struct data_type {
2748     SelectorID ID;
2749     ObjCMethodList Instance, Factory;
2750   };
2751   typedef const data_type& data_type_ref;
2752 
2753   typedef unsigned hash_value_type;
2754   typedef unsigned offset_type;
2755 
2756   explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
2757 
2758   static hash_value_type ComputeHash(Selector Sel) {
2759     return serialization::ComputeHash(Sel);
2760   }
2761 
2762   std::pair<unsigned,unsigned>
2763     EmitKeyDataLength(raw_ostream& Out, Selector Sel,
2764                       data_type_ref Methods) {
2765     using namespace llvm::support;
2766     endian::Writer<little> LE(Out);
2767     unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
2768     LE.write<uint16_t>(KeyLen);
2769     unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
2770     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2771          Method = Method->getNext())
2772       if (Method->Method)
2773         DataLen += 4;
2774     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2775          Method = Method->getNext())
2776       if (Method->Method)
2777         DataLen += 4;
2778     LE.write<uint16_t>(DataLen);
2779     return std::make_pair(KeyLen, DataLen);
2780   }
2781 
2782   void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
2783     using namespace llvm::support;
2784     endian::Writer<little> LE(Out);
2785     uint64_t Start = Out.tell();
2786     assert((Start >> 32) == 0 && "Selector key offset too large");
2787     Writer.SetSelectorOffset(Sel, Start);
2788     unsigned N = Sel.getNumArgs();
2789     LE.write<uint16_t>(N);
2790     if (N == 0)
2791       N = 1;
2792     for (unsigned I = 0; I != N; ++I)
2793       LE.write<uint32_t>(
2794           Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
2795   }
2796 
2797   void EmitData(raw_ostream& Out, key_type_ref,
2798                 data_type_ref Methods, unsigned DataLen) {
2799     using namespace llvm::support;
2800     endian::Writer<little> LE(Out);
2801     uint64_t Start = Out.tell(); (void)Start;
2802     LE.write<uint32_t>(Methods.ID);
2803     unsigned NumInstanceMethods = 0;
2804     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2805          Method = Method->getNext())
2806       if (Method->Method)
2807         ++NumInstanceMethods;
2808 
2809     unsigned NumFactoryMethods = 0;
2810     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2811          Method = Method->getNext())
2812       if (Method->Method)
2813         ++NumFactoryMethods;
2814 
2815     unsigned InstanceBits = Methods.Instance.getBits();
2816     assert(InstanceBits < 4);
2817     unsigned NumInstanceMethodsAndBits =
2818         (NumInstanceMethods << 2) | InstanceBits;
2819     unsigned FactoryBits = Methods.Factory.getBits();
2820     assert(FactoryBits < 4);
2821     unsigned NumFactoryMethodsAndBits = (NumFactoryMethods << 2) | FactoryBits;
2822     LE.write<uint16_t>(NumInstanceMethodsAndBits);
2823     LE.write<uint16_t>(NumFactoryMethodsAndBits);
2824     for (const ObjCMethodList *Method = &Methods.Instance; Method;
2825          Method = Method->getNext())
2826       if (Method->Method)
2827         LE.write<uint32_t>(Writer.getDeclID(Method->Method));
2828     for (const ObjCMethodList *Method = &Methods.Factory; Method;
2829          Method = Method->getNext())
2830       if (Method->Method)
2831         LE.write<uint32_t>(Writer.getDeclID(Method->Method));
2832 
2833     assert(Out.tell() - Start == DataLen && "Data length is wrong");
2834   }
2835 };
2836 } // end anonymous namespace
2837 
2838 /// \brief Write ObjC data: selectors and the method pool.
2839 ///
2840 /// The method pool contains both instance and factory methods, stored
2841 /// in an on-disk hash table indexed by the selector. The hash table also
2842 /// contains an empty entry for every other selector known to Sema.
2843 void ASTWriter::WriteSelectors(Sema &SemaRef) {
2844   using namespace llvm;
2845 
2846   // Do we have to do anything at all?
2847   if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
2848     return;
2849   unsigned NumTableEntries = 0;
2850   // Create and write out the blob that contains selectors and the method pool.
2851   {
2852     llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
2853     ASTMethodPoolTrait Trait(*this);
2854 
2855     // Create the on-disk hash table representation. We walk through every
2856     // selector we've seen and look it up in the method pool.
2857     SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
2858     for (llvm::DenseMap<Selector, SelectorID>::iterator
2859              I = SelectorIDs.begin(), E = SelectorIDs.end();
2860          I != E; ++I) {
2861       Selector S = I->first;
2862       Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
2863       ASTMethodPoolTrait::data_type Data = {
2864         I->second,
2865         ObjCMethodList(),
2866         ObjCMethodList()
2867       };
2868       if (F != SemaRef.MethodPool.end()) {
2869         Data.Instance = F->second.first;
2870         Data.Factory = F->second.second;
2871       }
2872       // Only write this selector if it's not in an existing AST or something
2873       // changed.
2874       if (Chain && I->second < FirstSelectorID) {
2875         // Selector already exists. Did it change?
2876         bool changed = false;
2877         for (ObjCMethodList *M = &Data.Instance; !changed && M && M->Method;
2878              M = M->getNext()) {
2879           if (!M->Method->isFromASTFile())
2880             changed = true;
2881         }
2882         for (ObjCMethodList *M = &Data.Factory; !changed && M && M->Method;
2883              M = M->getNext()) {
2884           if (!M->Method->isFromASTFile())
2885             changed = true;
2886         }
2887         if (!changed)
2888           continue;
2889       } else if (Data.Instance.Method || Data.Factory.Method) {
2890         // A new method pool entry.
2891         ++NumTableEntries;
2892       }
2893       Generator.insert(S, Data, Trait);
2894     }
2895 
2896     // Create the on-disk hash table in a buffer.
2897     SmallString<4096> MethodPool;
2898     uint32_t BucketOffset;
2899     {
2900       using namespace llvm::support;
2901       ASTMethodPoolTrait Trait(*this);
2902       llvm::raw_svector_ostream Out(MethodPool);
2903       // Make sure that no bucket is at offset 0
2904       endian::Writer<little>(Out).write<uint32_t>(0);
2905       BucketOffset = Generator.Emit(Out, Trait);
2906     }
2907 
2908     // Create a blob abbreviation
2909     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
2910     Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
2911     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2912     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2913     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2914     unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
2915 
2916     // Write the method pool
2917     RecordData Record;
2918     Record.push_back(METHOD_POOL);
2919     Record.push_back(BucketOffset);
2920     Record.push_back(NumTableEntries);
2921     Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool.str());
2922 
2923     // Create a blob abbreviation for the selector table offsets.
2924     Abbrev = new BitCodeAbbrev();
2925     Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
2926     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
2927     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
2928     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
2929     unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
2930 
2931     // Write the selector offsets table.
2932     Record.clear();
2933     Record.push_back(SELECTOR_OFFSETS);
2934     Record.push_back(SelectorOffsets.size());
2935     Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
2936     Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
2937                               data(SelectorOffsets));
2938   }
2939 }
2940 
2941 /// \brief Write the selectors referenced in @selector expression into AST file.
2942 void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
2943   using namespace llvm;
2944   if (SemaRef.ReferencedSelectors.empty())
2945     return;
2946 
2947   RecordData Record;
2948 
2949   // Note: this writes out all references even for a dependent AST. But it is
2950   // very tricky to fix, and given that @selector shouldn't really appear in
2951   // headers, probably not worth it. It's not a correctness issue.
2952   for (DenseMap<Selector, SourceLocation>::iterator S =
2953        SemaRef.ReferencedSelectors.begin(),
2954        E = SemaRef.ReferencedSelectors.end(); S != E; ++S) {
2955     Selector Sel = (*S).first;
2956     SourceLocation Loc = (*S).second;
2957     AddSelectorRef(Sel, Record);
2958     AddSourceLocation(Loc, Record);
2959   }
2960   Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
2961 }
2962 
2963 //===----------------------------------------------------------------------===//
2964 // Identifier Table Serialization
2965 //===----------------------------------------------------------------------===//
2966 
2967 namespace {
2968 class ASTIdentifierTableTrait {
2969   ASTWriter &Writer;
2970   Preprocessor &PP;
2971   IdentifierResolver &IdResolver;
2972   bool IsModule;
2973 
2974   /// \brief Determines whether this is an "interesting" identifier
2975   /// that needs a full IdentifierInfo structure written into the hash
2976   /// table.
2977   bool isInterestingIdentifier(IdentifierInfo *II, MacroDirective *&Macro) {
2978     if (II->isPoisoned() ||
2979         II->isExtensionToken() ||
2980         II->getObjCOrBuiltinID() ||
2981         II->hasRevertedTokenIDToIdentifier() ||
2982         II->getFETokenInfo<void>())
2983       return true;
2984 
2985     return hadMacroDefinition(II, Macro);
2986   }
2987 
2988   bool hadMacroDefinition(IdentifierInfo *II, MacroDirective *&Macro) {
2989     if (!II->hadMacroDefinition())
2990       return false;
2991 
2992     if (Macro || (Macro = PP.getMacroDirectiveHistory(II))) {
2993       if (!IsModule)
2994         return !shouldIgnoreMacro(Macro, IsModule, PP);
2995       SubmoduleID ModID;
2996       if (getFirstPublicSubmoduleMacro(Macro, ModID))
2997         return true;
2998     }
2999 
3000     return false;
3001   }
3002 
3003   typedef llvm::SmallVectorImpl<SubmoduleID> OverriddenList;
3004 
3005   MacroDirective *
3006   getFirstPublicSubmoduleMacro(MacroDirective *MD, SubmoduleID &ModID) {
3007     ModID = 0;
3008     llvm::SmallVector<SubmoduleID, 1> Overridden;
3009     if (MacroDirective *NextMD = getPublicSubmoduleMacro(MD, ModID, Overridden))
3010       if (!shouldIgnoreMacro(NextMD, IsModule, PP))
3011         return NextMD;
3012     return nullptr;
3013   }
3014 
3015   MacroDirective *
3016   getNextPublicSubmoduleMacro(MacroDirective *MD, SubmoduleID &ModID,
3017                               OverriddenList &Overridden) {
3018     if (MacroDirective *NextMD =
3019             getPublicSubmoduleMacro(MD->getPrevious(), ModID, Overridden))
3020       if (!shouldIgnoreMacro(NextMD, IsModule, PP))
3021         return NextMD;
3022     return nullptr;
3023   }
3024 
3025   /// \brief Traverses the macro directives history and returns the latest
3026   /// public macro definition or undefinition that is not in ModID.
3027   /// A macro that is defined in submodule A and undefined in submodule B
3028   /// will still be considered as defined/exported from submodule A.
3029   /// ModID is updated to the module containing the returned directive.
3030   ///
3031   /// FIXME: This process breaks down if a module defines a macro, imports
3032   ///        another submodule that changes the macro, then changes the
3033   ///        macro again itself.
3034   MacroDirective *getPublicSubmoduleMacro(MacroDirective *MD,
3035                                           SubmoduleID &ModID,
3036                                           OverriddenList &Overridden) {
3037     Overridden.clear();
3038     if (!MD)
3039       return nullptr;
3040 
3041     SubmoduleID OrigModID = ModID;
3042     Optional<bool> IsPublic;
3043     for (; MD; MD = MD->getPrevious()) {
3044       SubmoduleID ThisModID = getSubmoduleID(MD);
3045       if (ThisModID == 0) {
3046         IsPublic = Optional<bool>();
3047 
3048         // If we have no directive location, this macro was installed when
3049         // finalizing the ASTReader.
3050         if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
3051           if (DefMD->getInfo()->getOwningModuleID())
3052             return MD;
3053         // Skip imports that only produce #undefs for now.
3054         // FIXME: We should still re-export them!
3055 
3056         continue;
3057       }
3058       if (ThisModID != ModID) {
3059         ModID = ThisModID;
3060         IsPublic = Optional<bool>();
3061       }
3062 
3063       // If this is a definition from a submodule import, that submodule's
3064       // definition is overridden by the definition or undefinition that we
3065       // started with.
3066       // FIXME: This should only apply to macros defined in OrigModID.
3067       // We can't do that currently, because a #include of a different submodule
3068       // of the same module just leaks through macros instead of providing new
3069       // DefMacroDirectives for them.
3070       if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3071         // Figure out which submodule the macro was originally defined within.
3072         SubmoduleID SourceID = DefMD->getInfo()->getOwningModuleID();
3073         if (!SourceID) {
3074           SourceLocation DefLoc = DefMD->getInfo()->getDefinitionLoc();
3075           if (DefLoc == MD->getLocation())
3076             SourceID = ThisModID;
3077           else
3078             SourceID = Writer.inferSubmoduleIDFromLocation(DefLoc);
3079         }
3080         if (OrigModID && SourceID != OrigModID)
3081           Overridden.push_back(SourceID);
3082       }
3083 
3084       // We are looking for a definition in a different submodule than the one
3085       // that we started with. If a submodule has re-definitions of the same
3086       // macro, only the last definition will be used as the "exported" one.
3087       if (ModID == OrigModID)
3088         continue;
3089 
3090       // The latest visibility directive for a name in a submodule affects all
3091       // the directives that come before it.
3092       if (VisibilityMacroDirective *VisMD =
3093               dyn_cast<VisibilityMacroDirective>(MD)) {
3094         if (!IsPublic.hasValue())
3095           IsPublic = VisMD->isPublic();
3096       } else if (!IsPublic.hasValue() || IsPublic.getValue()) {
3097         // FIXME: If we find an imported macro, we should include its list of
3098         // overrides in our export.
3099         return MD;
3100       }
3101     }
3102 
3103     return nullptr;
3104   }
3105 
3106   SubmoduleID getSubmoduleID(MacroDirective *MD) {
3107     return Writer.inferSubmoduleIDFromLocation(MD->getLocation());
3108   }
3109 
3110 public:
3111   typedef IdentifierInfo* key_type;
3112   typedef key_type  key_type_ref;
3113 
3114   typedef IdentID data_type;
3115   typedef data_type data_type_ref;
3116 
3117   typedef unsigned hash_value_type;
3118   typedef unsigned offset_type;
3119 
3120   ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
3121                           IdentifierResolver &IdResolver, bool IsModule)
3122     : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule) { }
3123 
3124   static hash_value_type ComputeHash(const IdentifierInfo* II) {
3125     return llvm::HashString(II->getName());
3126   }
3127 
3128   std::pair<unsigned,unsigned>
3129   EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
3130     unsigned KeyLen = II->getLength() + 1;
3131     unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
3132     MacroDirective *Macro = nullptr;
3133     if (isInterestingIdentifier(II, Macro)) {
3134       DataLen += 2; // 2 bytes for builtin ID
3135       DataLen += 2; // 2 bytes for flags
3136       if (hadMacroDefinition(II, Macro)) {
3137         DataLen += 4; // MacroDirectives offset.
3138         if (IsModule) {
3139           SubmoduleID ModID;
3140           llvm::SmallVector<SubmoduleID, 4> Overridden;
3141           for (MacroDirective *
3142                  MD = getFirstPublicSubmoduleMacro(Macro, ModID);
3143                  MD; MD = getNextPublicSubmoduleMacro(MD, ModID, Overridden)) {
3144             // Previous macro's overrides.
3145             if (!Overridden.empty())
3146               DataLen += 4 * (1 + Overridden.size());
3147             DataLen += 4; // MacroInfo ID or ModuleID.
3148           }
3149           // Previous macro's overrides.
3150           if (!Overridden.empty())
3151             DataLen += 4 * (1 + Overridden.size());
3152           DataLen += 4;
3153         }
3154       }
3155 
3156       for (IdentifierResolver::iterator D = IdResolver.begin(II),
3157                                      DEnd = IdResolver.end();
3158            D != DEnd; ++D)
3159         DataLen += sizeof(DeclID);
3160     }
3161     using namespace llvm::support;
3162     endian::Writer<little> LE(Out);
3163 
3164     LE.write<uint16_t>(DataLen);
3165     // We emit the key length after the data length so that every
3166     // string is preceded by a 16-bit length. This matches the PTH
3167     // format for storing identifiers.
3168     LE.write<uint16_t>(KeyLen);
3169     return std::make_pair(KeyLen, DataLen);
3170   }
3171 
3172   void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
3173                unsigned KeyLen) {
3174     // Record the location of the key data.  This is used when generating
3175     // the mapping from persistent IDs to strings.
3176     Writer.SetIdentifierOffset(II, Out.tell());
3177     Out.write(II->getNameStart(), KeyLen);
3178   }
3179 
3180   static void emitMacroOverrides(raw_ostream &Out,
3181                                  ArrayRef<SubmoduleID> Overridden) {
3182     if (!Overridden.empty()) {
3183       using namespace llvm::support;
3184       endian::Writer<little> LE(Out);
3185       LE.write<uint32_t>(Overridden.size() | 0x80000000U);
3186       for (unsigned I = 0, N = Overridden.size(); I != N; ++I)
3187         LE.write<uint32_t>(Overridden[I]);
3188     }
3189   }
3190 
3191   void EmitData(raw_ostream& Out, IdentifierInfo* II,
3192                 IdentID ID, unsigned) {
3193     using namespace llvm::support;
3194     endian::Writer<little> LE(Out);
3195     MacroDirective *Macro = nullptr;
3196     if (!isInterestingIdentifier(II, Macro)) {
3197       LE.write<uint32_t>(ID << 1);
3198       return;
3199     }
3200 
3201     LE.write<uint32_t>((ID << 1) | 0x01);
3202     uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
3203     assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
3204     LE.write<uint16_t>(Bits);
3205     Bits = 0;
3206     bool HadMacroDefinition = hadMacroDefinition(II, Macro);
3207     Bits = (Bits << 1) | unsigned(HadMacroDefinition);
3208     Bits = (Bits << 1) | unsigned(IsModule);
3209     Bits = (Bits << 1) | unsigned(II->isExtensionToken());
3210     Bits = (Bits << 1) | unsigned(II->isPoisoned());
3211     Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
3212     Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
3213     LE.write<uint16_t>(Bits);
3214 
3215     if (HadMacroDefinition) {
3216       LE.write<uint32_t>(Writer.getMacroDirectivesOffset(II));
3217       if (IsModule) {
3218         // Write the IDs of macros coming from different submodules.
3219         SubmoduleID ModID;
3220         llvm::SmallVector<SubmoduleID, 4> Overridden;
3221         for (MacroDirective *
3222                MD = getFirstPublicSubmoduleMacro(Macro, ModID);
3223                MD; MD = getNextPublicSubmoduleMacro(MD, ModID, Overridden)) {
3224           MacroID InfoID = 0;
3225           emitMacroOverrides(Out, Overridden);
3226           if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) {
3227             InfoID = Writer.getMacroID(DefMD->getInfo());
3228             assert(InfoID);
3229             LE.write<uint32_t>(InfoID << 1);
3230           } else {
3231             assert(isa<UndefMacroDirective>(MD));
3232             LE.write<uint32_t>((ModID << 1) | 1);
3233           }
3234         }
3235         emitMacroOverrides(Out, Overridden);
3236         LE.write<uint32_t>(0);
3237       }
3238     }
3239 
3240     // Emit the declaration IDs in reverse order, because the
3241     // IdentifierResolver provides the declarations as they would be
3242     // visible (e.g., the function "stat" would come before the struct
3243     // "stat"), but the ASTReader adds declarations to the end of the list
3244     // (so we need to see the struct "status" before the function "status").
3245     // Only emit declarations that aren't from a chained PCH, though.
3246     SmallVector<Decl *, 16> Decls(IdResolver.begin(II),
3247                                   IdResolver.end());
3248     for (SmallVectorImpl<Decl *>::reverse_iterator D = Decls.rbegin(),
3249                                                 DEnd = Decls.rend();
3250          D != DEnd; ++D)
3251       LE.write<uint32_t>(Writer.getDeclID(getMostRecentLocalDecl(*D)));
3252   }
3253 
3254   /// \brief Returns the most recent local decl or the given decl if there are
3255   /// no local ones. The given decl is assumed to be the most recent one.
3256   Decl *getMostRecentLocalDecl(Decl *Orig) {
3257     // The only way a "from AST file" decl would be more recent from a local one
3258     // is if it came from a module.
3259     if (!PP.getLangOpts().Modules)
3260       return Orig;
3261 
3262     // Look for a local in the decl chain.
3263     for (Decl *D = Orig; D; D = D->getPreviousDecl()) {
3264       if (!D->isFromASTFile())
3265         return D;
3266       // If we come up a decl from a (chained-)PCH stop since we won't find a
3267       // local one.
3268       if (D->getOwningModuleID() == 0)
3269         break;
3270     }
3271 
3272     return Orig;
3273   }
3274 };
3275 } // end anonymous namespace
3276 
3277 /// \brief Write the identifier table into the AST file.
3278 ///
3279 /// The identifier table consists of a blob containing string data
3280 /// (the actual identifiers themselves) and a separate "offsets" index
3281 /// that maps identifier IDs to locations within the blob.
3282 void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
3283                                      IdentifierResolver &IdResolver,
3284                                      bool IsModule) {
3285   using namespace llvm;
3286 
3287   // Create and write out the blob that contains the identifier
3288   // strings.
3289   {
3290     llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
3291     ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3292 
3293     // Look for any identifiers that were named while processing the
3294     // headers, but are otherwise not needed. We add these to the hash
3295     // table to enable checking of the predefines buffer in the case
3296     // where the user adds new macro definitions when building the AST
3297     // file.
3298     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
3299                                 IDEnd = PP.getIdentifierTable().end();
3300          ID != IDEnd; ++ID)
3301       getIdentifierRef(ID->second);
3302 
3303     // Create the on-disk hash table representation. We only store offsets
3304     // for identifiers that appear here for the first time.
3305     IdentifierOffsets.resize(NextIdentID - FirstIdentID);
3306     for (llvm::DenseMap<const IdentifierInfo *, IdentID>::iterator
3307            ID = IdentifierIDs.begin(), IDEnd = IdentifierIDs.end();
3308          ID != IDEnd; ++ID) {
3309       assert(ID->first && "NULL identifier in identifier table");
3310       if (!Chain || !ID->first->isFromAST() ||
3311           ID->first->hasChangedSinceDeserialization())
3312         Generator.insert(const_cast<IdentifierInfo *>(ID->first), ID->second,
3313                          Trait);
3314     }
3315 
3316     // Create the on-disk hash table in a buffer.
3317     SmallString<4096> IdentifierTable;
3318     uint32_t BucketOffset;
3319     {
3320       using namespace llvm::support;
3321       ASTIdentifierTableTrait Trait(*this, PP, IdResolver, IsModule);
3322       llvm::raw_svector_ostream Out(IdentifierTable);
3323       // Make sure that no bucket is at offset 0
3324       endian::Writer<little>(Out).write<uint32_t>(0);
3325       BucketOffset = Generator.Emit(Out, Trait);
3326     }
3327 
3328     // Create a blob abbreviation
3329     BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3330     Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
3331     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3332     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3333     unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
3334 
3335     // Write the identifier table
3336     RecordData Record;
3337     Record.push_back(IDENTIFIER_TABLE);
3338     Record.push_back(BucketOffset);
3339     Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable.str());
3340   }
3341 
3342   // Write the offsets table for identifier IDs.
3343   BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3344   Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
3345   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
3346   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
3347   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3348   unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
3349 
3350 #ifndef NDEBUG
3351   for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
3352     assert(IdentifierOffsets[I] && "Missing identifier offset?");
3353 #endif
3354 
3355   RecordData Record;
3356   Record.push_back(IDENTIFIER_OFFSET);
3357   Record.push_back(IdentifierOffsets.size());
3358   Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
3359   Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
3360                             data(IdentifierOffsets));
3361 }
3362 
3363 //===----------------------------------------------------------------------===//
3364 // DeclContext's Name Lookup Table Serialization
3365 //===----------------------------------------------------------------------===//
3366 
3367 namespace {
3368 // Trait used for the on-disk hash table used in the method pool.
3369 class ASTDeclContextNameLookupTrait {
3370   ASTWriter &Writer;
3371 
3372 public:
3373   typedef DeclarationName key_type;
3374   typedef key_type key_type_ref;
3375 
3376   typedef DeclContext::lookup_result data_type;
3377   typedef const data_type& data_type_ref;
3378 
3379   typedef unsigned hash_value_type;
3380   typedef unsigned offset_type;
3381 
3382   explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
3383 
3384   hash_value_type ComputeHash(DeclarationName Name) {
3385     llvm::FoldingSetNodeID ID;
3386     ID.AddInteger(Name.getNameKind());
3387 
3388     switch (Name.getNameKind()) {
3389     case DeclarationName::Identifier:
3390       ID.AddString(Name.getAsIdentifierInfo()->getName());
3391       break;
3392     case DeclarationName::ObjCZeroArgSelector:
3393     case DeclarationName::ObjCOneArgSelector:
3394     case DeclarationName::ObjCMultiArgSelector:
3395       ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
3396       break;
3397     case DeclarationName::CXXConstructorName:
3398     case DeclarationName::CXXDestructorName:
3399     case DeclarationName::CXXConversionFunctionName:
3400       break;
3401     case DeclarationName::CXXOperatorName:
3402       ID.AddInteger(Name.getCXXOverloadedOperator());
3403       break;
3404     case DeclarationName::CXXLiteralOperatorName:
3405       ID.AddString(Name.getCXXLiteralIdentifier()->getName());
3406     case DeclarationName::CXXUsingDirective:
3407       break;
3408     }
3409 
3410     return ID.ComputeHash();
3411   }
3412 
3413   std::pair<unsigned,unsigned>
3414     EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
3415                       data_type_ref Lookup) {
3416     using namespace llvm::support;
3417     endian::Writer<little> LE(Out);
3418     unsigned KeyLen = 1;
3419     switch (Name.getNameKind()) {
3420     case DeclarationName::Identifier:
3421     case DeclarationName::ObjCZeroArgSelector:
3422     case DeclarationName::ObjCOneArgSelector:
3423     case DeclarationName::ObjCMultiArgSelector:
3424     case DeclarationName::CXXLiteralOperatorName:
3425       KeyLen += 4;
3426       break;
3427     case DeclarationName::CXXOperatorName:
3428       KeyLen += 1;
3429       break;
3430     case DeclarationName::CXXConstructorName:
3431     case DeclarationName::CXXDestructorName:
3432     case DeclarationName::CXXConversionFunctionName:
3433     case DeclarationName::CXXUsingDirective:
3434       break;
3435     }
3436     LE.write<uint16_t>(KeyLen);
3437 
3438     // 2 bytes for num of decls and 4 for each DeclID.
3439     unsigned DataLen = 2 + 4 * Lookup.size();
3440     LE.write<uint16_t>(DataLen);
3441 
3442     return std::make_pair(KeyLen, DataLen);
3443   }
3444 
3445   void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
3446     using namespace llvm::support;
3447     endian::Writer<little> LE(Out);
3448     LE.write<uint8_t>(Name.getNameKind());
3449     switch (Name.getNameKind()) {
3450     case DeclarationName::Identifier:
3451       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
3452       return;
3453     case DeclarationName::ObjCZeroArgSelector:
3454     case DeclarationName::ObjCOneArgSelector:
3455     case DeclarationName::ObjCMultiArgSelector:
3456       LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
3457       return;
3458     case DeclarationName::CXXOperatorName:
3459       assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
3460              "Invalid operator?");
3461       LE.write<uint8_t>(Name.getCXXOverloadedOperator());
3462       return;
3463     case DeclarationName::CXXLiteralOperatorName:
3464       LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
3465       return;
3466     case DeclarationName::CXXConstructorName:
3467     case DeclarationName::CXXDestructorName:
3468     case DeclarationName::CXXConversionFunctionName:
3469     case DeclarationName::CXXUsingDirective:
3470       return;
3471     }
3472 
3473     llvm_unreachable("Invalid name kind?");
3474   }
3475 
3476   void EmitData(raw_ostream& Out, key_type_ref,
3477                 data_type Lookup, unsigned DataLen) {
3478     using namespace llvm::support;
3479     endian::Writer<little> LE(Out);
3480     uint64_t Start = Out.tell(); (void)Start;
3481     LE.write<uint16_t>(Lookup.size());
3482     for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
3483          I != E; ++I)
3484       LE.write<uint32_t>(Writer.GetDeclRef(*I));
3485 
3486     assert(Out.tell() - Start == DataLen && "Data length is wrong");
3487   }
3488 };
3489 } // end anonymous namespace
3490 
3491 template<typename Visitor>
3492 static void visitLocalLookupResults(const DeclContext *ConstDC,
3493                                     bool NeedToReconcileExternalVisibleStorage,
3494                                     Visitor AddLookupResult) {
3495   // FIXME: We need to build the lookups table, which is logically const.
3496   DeclContext *DC = const_cast<DeclContext*>(ConstDC);
3497   assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
3498 
3499   SmallVector<DeclarationName, 16> ExternalNames;
3500   for (auto &Lookup : *DC->buildLookup()) {
3501     if (Lookup.second.hasExternalDecls() ||
3502         NeedToReconcileExternalVisibleStorage) {
3503       // We don't know for sure what declarations are found by this name,
3504       // because the external source might have a different set from the set
3505       // that are in the lookup map, and we can't update it now without
3506       // risking invalidating our lookup iterator. So add it to a queue to
3507       // deal with later.
3508       ExternalNames.push_back(Lookup.first);
3509       continue;
3510     }
3511 
3512     AddLookupResult(Lookup.first, Lookup.second.getLookupResult());
3513   }
3514 
3515   // Add the names we needed to defer. Note, this shouldn't add any new decls
3516   // to the list we need to serialize: any new declarations we find here should
3517   // be imported from an external source.
3518   // FIXME: What if the external source isn't an ASTReader?
3519   for (const auto &Name : ExternalNames)
3520     AddLookupResult(Name, DC->lookup(Name));
3521 }
3522 
3523 void ASTWriter::AddUpdatedDeclContext(const DeclContext *DC) {
3524   if (UpdatedDeclContexts.insert(DC) && WritingAST) {
3525     // Ensure we emit all the visible declarations.
3526     visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3527                             [&](DeclarationName Name,
3528                                 DeclContext::lookup_const_result Result) {
3529       for (auto *Decl : Result)
3530         GetDeclRef(Decl);
3531     });
3532   }
3533 }
3534 
3535 uint32_t
3536 ASTWriter::GenerateNameLookupTable(const DeclContext *DC,
3537                                    llvm::SmallVectorImpl<char> &LookupTable) {
3538   assert(!DC->LookupPtr.getInt() && "must call buildLookups first");
3539 
3540   llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
3541       Generator;
3542   ASTDeclContextNameLookupTrait Trait(*this);
3543 
3544   // Create the on-disk hash table representation.
3545   DeclarationName ConstructorName;
3546   DeclarationName ConversionName;
3547   SmallVector<NamedDecl *, 8> ConstructorDecls;
3548   SmallVector<NamedDecl *, 4> ConversionDecls;
3549 
3550   visitLocalLookupResults(DC, DC->NeedToReconcileExternalVisibleStorage,
3551                           [&](DeclarationName Name,
3552                               DeclContext::lookup_result Result) {
3553     if (Result.empty())
3554       return;
3555 
3556     // Different DeclarationName values of certain kinds are mapped to
3557     // identical serialized keys, because we don't want to use type
3558     // identifiers in the keys (since type ids are local to the module).
3559     switch (Name.getNameKind()) {
3560     case DeclarationName::CXXConstructorName:
3561       // There may be different CXXConstructorName DeclarationName values
3562       // in a DeclContext because a UsingDecl that inherits constructors
3563       // has the DeclarationName of the inherited constructors.
3564       if (!ConstructorName)
3565         ConstructorName = Name;
3566       ConstructorDecls.append(Result.begin(), Result.end());
3567       return;
3568 
3569     case DeclarationName::CXXConversionFunctionName:
3570       if (!ConversionName)
3571         ConversionName = Name;
3572       ConversionDecls.append(Result.begin(), Result.end());
3573       return;
3574 
3575     default:
3576       break;
3577     }
3578 
3579     Generator.insert(Name, Result, Trait);
3580   });
3581 
3582   // Add the constructors.
3583   if (!ConstructorDecls.empty()) {
3584     Generator.insert(ConstructorName,
3585                      DeclContext::lookup_result(ConstructorDecls.begin(),
3586                                                 ConstructorDecls.end()),
3587                      Trait);
3588   }
3589 
3590   // Add the conversion functions.
3591   if (!ConversionDecls.empty()) {
3592     Generator.insert(ConversionName,
3593                      DeclContext::lookup_result(ConversionDecls.begin(),
3594                                                 ConversionDecls.end()),
3595                      Trait);
3596   }
3597 
3598   // Create the on-disk hash table in a buffer.
3599   llvm::raw_svector_ostream Out(LookupTable);
3600   // Make sure that no bucket is at offset 0
3601   using namespace llvm::support;
3602   endian::Writer<little>(Out).write<uint32_t>(0);
3603   return Generator.Emit(Out, Trait);
3604 }
3605 
3606 /// \brief Write the block containing all of the declaration IDs
3607 /// visible from the given DeclContext.
3608 ///
3609 /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
3610 /// bitstream, or 0 if no block was written.
3611 uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
3612                                                  DeclContext *DC) {
3613   if (DC->getPrimaryContext() != DC)
3614     return 0;
3615 
3616   // Since there is no name lookup into functions or methods, don't bother to
3617   // build a visible-declarations table for these entities.
3618   if (DC->isFunctionOrMethod())
3619     return 0;
3620 
3621   // If not in C++, we perform name lookup for the translation unit via the
3622   // IdentifierInfo chains, don't bother to build a visible-declarations table.
3623   if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
3624     return 0;
3625 
3626   // Serialize the contents of the mapping used for lookup. Note that,
3627   // although we have two very different code paths, the serialized
3628   // representation is the same for both cases: a declaration name,
3629   // followed by a size, followed by references to the visible
3630   // declarations that have that name.
3631   uint64_t Offset = Stream.GetCurrentBitNo();
3632   StoredDeclsMap *Map = DC->buildLookup();
3633   if (!Map || Map->empty())
3634     return 0;
3635 
3636   // Create the on-disk hash table in a buffer.
3637   SmallString<4096> LookupTable;
3638   uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3639 
3640   // Write the lookup table
3641   RecordData Record;
3642   Record.push_back(DECL_CONTEXT_VISIBLE);
3643   Record.push_back(BucketOffset);
3644   Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
3645                             LookupTable.str());
3646 
3647   Stream.EmitRecord(DECL_CONTEXT_VISIBLE, Record);
3648   ++NumVisibleDeclContexts;
3649   return Offset;
3650 }
3651 
3652 /// \brief Write an UPDATE_VISIBLE block for the given context.
3653 ///
3654 /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
3655 /// DeclContext in a dependent AST file. As such, they only exist for the TU
3656 /// (in C++), for namespaces, and for classes with forward-declared unscoped
3657 /// enumeration members (in C++11).
3658 void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
3659   StoredDeclsMap *Map = DC->getLookupPtr();
3660   if (!Map || Map->empty())
3661     return;
3662 
3663   // Create the on-disk hash table in a buffer.
3664   SmallString<4096> LookupTable;
3665   uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
3666 
3667   // Write the lookup table
3668   RecordData Record;
3669   Record.push_back(UPDATE_VISIBLE);
3670   Record.push_back(getDeclID(cast<Decl>(DC)));
3671   Record.push_back(BucketOffset);
3672   Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable.str());
3673 }
3674 
3675 /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
3676 void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
3677   RecordData Record;
3678   Record.push_back(Opts.fp_contract);
3679   Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
3680 }
3681 
3682 /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
3683 void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
3684   if (!SemaRef.Context.getLangOpts().OpenCL)
3685     return;
3686 
3687   const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
3688   RecordData Record;
3689 #define OPENCLEXT(nm)  Record.push_back(Opts.nm);
3690 #include "clang/Basic/OpenCLExtensions.def"
3691   Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
3692 }
3693 
3694 void ASTWriter::WriteRedeclarations() {
3695   RecordData LocalRedeclChains;
3696   SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
3697 
3698   for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
3699     Decl *First = Redeclarations[I];
3700     assert(First->isFirstDecl() && "Not the first declaration?");
3701 
3702     Decl *MostRecent = First->getMostRecentDecl();
3703 
3704     // If we only have a single declaration, there is no point in storing
3705     // a redeclaration chain.
3706     if (First == MostRecent)
3707       continue;
3708 
3709     unsigned Offset = LocalRedeclChains.size();
3710     unsigned Size = 0;
3711     LocalRedeclChains.push_back(0); // Placeholder for the size.
3712 
3713     // Collect the set of local redeclarations of this declaration.
3714     for (Decl *Prev = MostRecent; Prev != First;
3715          Prev = Prev->getPreviousDecl()) {
3716       if (!Prev->isFromASTFile()) {
3717         AddDeclRef(Prev, LocalRedeclChains);
3718         ++Size;
3719       }
3720     }
3721 
3722     if (!First->isFromASTFile() && Chain) {
3723       Decl *FirstFromAST = MostRecent;
3724       for (Decl *Prev = MostRecent; Prev; Prev = Prev->getPreviousDecl()) {
3725         if (Prev->isFromASTFile())
3726           FirstFromAST = Prev;
3727       }
3728 
3729       Chain->MergedDecls[FirstFromAST].push_back(getDeclID(First));
3730     }
3731 
3732     LocalRedeclChains[Offset] = Size;
3733 
3734     // Reverse the set of local redeclarations, so that we store them in
3735     // order (since we found them in reverse order).
3736     std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
3737 
3738     // Add the mapping from the first ID from the AST to the set of local
3739     // declarations.
3740     LocalRedeclarationsInfo Info = { getDeclID(First), Offset };
3741     LocalRedeclsMap.push_back(Info);
3742 
3743     assert(N == Redeclarations.size() &&
3744            "Deserialized a declaration we shouldn't have");
3745   }
3746 
3747   if (LocalRedeclChains.empty())
3748     return;
3749 
3750   // Sort the local redeclarations map by the first declaration ID,
3751   // since the reader will be performing binary searches on this information.
3752   llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
3753 
3754   // Emit the local redeclarations map.
3755   using namespace llvm;
3756   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3757   Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
3758   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3759   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3760   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3761 
3762   RecordData Record;
3763   Record.push_back(LOCAL_REDECLARATIONS_MAP);
3764   Record.push_back(LocalRedeclsMap.size());
3765   Stream.EmitRecordWithBlob(AbbrevID, Record,
3766     reinterpret_cast<char*>(LocalRedeclsMap.data()),
3767     LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
3768 
3769   // Emit the redeclaration chains.
3770   Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
3771 }
3772 
3773 void ASTWriter::WriteObjCCategories() {
3774   SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
3775   RecordData Categories;
3776 
3777   for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
3778     unsigned Size = 0;
3779     unsigned StartIndex = Categories.size();
3780 
3781     ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
3782 
3783     // Allocate space for the size.
3784     Categories.push_back(0);
3785 
3786     // Add the categories.
3787     for (ObjCInterfaceDecl::known_categories_iterator
3788            Cat = Class->known_categories_begin(),
3789            CatEnd = Class->known_categories_end();
3790          Cat != CatEnd; ++Cat, ++Size) {
3791       assert(getDeclID(*Cat) != 0 && "Bogus category");
3792       AddDeclRef(*Cat, Categories);
3793     }
3794 
3795     // Update the size.
3796     Categories[StartIndex] = Size;
3797 
3798     // Record this interface -> category map.
3799     ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
3800     CategoriesMap.push_back(CatInfo);
3801   }
3802 
3803   // Sort the categories map by the definition ID, since the reader will be
3804   // performing binary searches on this information.
3805   llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
3806 
3807   // Emit the categories map.
3808   using namespace llvm;
3809   llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
3810   Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
3811   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
3812   Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
3813   unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
3814 
3815   RecordData Record;
3816   Record.push_back(OBJC_CATEGORIES_MAP);
3817   Record.push_back(CategoriesMap.size());
3818   Stream.EmitRecordWithBlob(AbbrevID, Record,
3819                             reinterpret_cast<char*>(CategoriesMap.data()),
3820                             CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
3821 
3822   // Emit the category lists.
3823   Stream.EmitRecord(OBJC_CATEGORIES, Categories);
3824 }
3825 
3826 void ASTWriter::WriteMergedDecls() {
3827   if (!Chain || Chain->MergedDecls.empty())
3828     return;
3829 
3830   RecordData Record;
3831   for (ASTReader::MergedDeclsMap::iterator I = Chain->MergedDecls.begin(),
3832                                         IEnd = Chain->MergedDecls.end();
3833        I != IEnd; ++I) {
3834     DeclID CanonID = I->first->isFromASTFile()? I->first->getGlobalID()
3835                                               : GetDeclRef(I->first);
3836     assert(CanonID && "Merged declaration not known?");
3837 
3838     Record.push_back(CanonID);
3839     Record.push_back(I->second.size());
3840     Record.append(I->second.begin(), I->second.end());
3841   }
3842   Stream.EmitRecord(MERGED_DECLARATIONS, Record);
3843 }
3844 
3845 void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
3846   Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
3847 
3848   if (LPTMap.empty())
3849     return;
3850 
3851   RecordData Record;
3852   for (Sema::LateParsedTemplateMapT::iterator It = LPTMap.begin(),
3853                                               ItEnd = LPTMap.end();
3854        It != ItEnd; ++It) {
3855     LateParsedTemplate *LPT = It->second;
3856     AddDeclRef(It->first, Record);
3857     AddDeclRef(LPT->D, Record);
3858     Record.push_back(LPT->Toks.size());
3859 
3860     for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
3861                                 TokEnd = LPT->Toks.end();
3862          TokIt != TokEnd; ++TokIt) {
3863       AddToken(*TokIt, Record);
3864     }
3865   }
3866   Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
3867 }
3868 
3869 /// \brief Write the state of 'pragma clang optimize' at the end of the module.
3870 void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
3871   RecordData Record;
3872   SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
3873   AddSourceLocation(PragmaLoc, Record);
3874   Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
3875 }
3876 
3877 //===----------------------------------------------------------------------===//
3878 // General Serialization Routines
3879 //===----------------------------------------------------------------------===//
3880 
3881 /// \brief Write a record containing the given attributes.
3882 void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
3883                                 RecordDataImpl &Record) {
3884   Record.push_back(Attrs.size());
3885   for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
3886                                         e = Attrs.end(); i != e; ++i){
3887     const Attr *A = *i;
3888     Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
3889     AddSourceRange(A->getRange(), Record);
3890 
3891 #include "clang/Serialization/AttrPCHWrite.inc"
3892 
3893   }
3894 }
3895 
3896 void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
3897   AddSourceLocation(Tok.getLocation(), Record);
3898   Record.push_back(Tok.getLength());
3899 
3900   // FIXME: When reading literal tokens, reconstruct the literal pointer
3901   // if it is needed.
3902   AddIdentifierRef(Tok.getIdentifierInfo(), Record);
3903   // FIXME: Should translate token kind to a stable encoding.
3904   Record.push_back(Tok.getKind());
3905   // FIXME: Should translate token flags to a stable encoding.
3906   Record.push_back(Tok.getFlags());
3907 }
3908 
3909 void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
3910   Record.push_back(Str.size());
3911   Record.insert(Record.end(), Str.begin(), Str.end());
3912 }
3913 
3914 void ASTWriter::AddVersionTuple(const VersionTuple &Version,
3915                                 RecordDataImpl &Record) {
3916   Record.push_back(Version.getMajor());
3917   if (Optional<unsigned> Minor = Version.getMinor())
3918     Record.push_back(*Minor + 1);
3919   else
3920     Record.push_back(0);
3921   if (Optional<unsigned> Subminor = Version.getSubminor())
3922     Record.push_back(*Subminor + 1);
3923   else
3924     Record.push_back(0);
3925 }
3926 
3927 /// \brief Note that the identifier II occurs at the given offset
3928 /// within the identifier table.
3929 void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
3930   IdentID ID = IdentifierIDs[II];
3931   // Only store offsets new to this AST file. Other identifier names are looked
3932   // up earlier in the chain and thus don't need an offset.
3933   if (ID >= FirstIdentID)
3934     IdentifierOffsets[ID - FirstIdentID] = Offset;
3935 }
3936 
3937 /// \brief Note that the selector Sel occurs at the given offset
3938 /// within the method pool/selector table.
3939 void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
3940   unsigned ID = SelectorIDs[Sel];
3941   assert(ID && "Unknown selector");
3942   // Don't record offsets for selectors that are also available in a different
3943   // file.
3944   if (ID < FirstSelectorID)
3945     return;
3946   SelectorOffsets[ID - FirstSelectorID] = Offset;
3947 }
3948 
3949 ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
3950   : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
3951     WritingModule(nullptr), WritingAST(false), DoneWritingDeclsAndTypes(false),
3952     ASTHasCompilerErrors(false),
3953     FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
3954     FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
3955     FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
3956     FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
3957     FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
3958     NextSubmoduleID(FirstSubmoduleID),
3959     FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
3960     CollectedStmts(&StmtsToEmit),
3961     NumStatements(0), NumMacros(0), NumLexicalDeclContexts(0),
3962     NumVisibleDeclContexts(0),
3963     NextCXXBaseSpecifiersID(1),
3964     DeclParmVarAbbrev(0), DeclContextLexicalAbbrev(0),
3965     DeclContextVisibleLookupAbbrev(0), UpdateVisibleAbbrev(0),
3966     DeclRefExprAbbrev(0), CharacterLiteralAbbrev(0),
3967     DeclRecordAbbrev(0), IntegerLiteralAbbrev(0),
3968     DeclTypedefAbbrev(0),
3969     DeclVarAbbrev(0), DeclFieldAbbrev(0),
3970     DeclEnumAbbrev(0), DeclObjCIvarAbbrev(0)
3971 {
3972 }
3973 
3974 ASTWriter::~ASTWriter() {
3975   llvm::DeleteContainerSeconds(FileDeclIDs);
3976 }
3977 
3978 void ASTWriter::WriteAST(Sema &SemaRef,
3979                          const std::string &OutputFile,
3980                          Module *WritingModule, StringRef isysroot,
3981                          bool hasErrors) {
3982   WritingAST = true;
3983 
3984   ASTHasCompilerErrors = hasErrors;
3985 
3986   // Emit the file header.
3987   Stream.Emit((unsigned)'C', 8);
3988   Stream.Emit((unsigned)'P', 8);
3989   Stream.Emit((unsigned)'C', 8);
3990   Stream.Emit((unsigned)'H', 8);
3991 
3992   WriteBlockInfoBlock();
3993 
3994   Context = &SemaRef.Context;
3995   PP = &SemaRef.PP;
3996   this->WritingModule = WritingModule;
3997   WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
3998   Context = nullptr;
3999   PP = nullptr;
4000   this->WritingModule = nullptr;
4001 
4002   WritingAST = false;
4003 }
4004 
4005 template<typename Vector>
4006 static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
4007                                ASTWriter::RecordData &Record) {
4008   for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
4009        I != E; ++I) {
4010     Writer.AddDeclRef(*I, Record);
4011   }
4012 }
4013 
4014 void ASTWriter::WriteASTCore(Sema &SemaRef,
4015                              StringRef isysroot,
4016                              const std::string &OutputFile,
4017                              Module *WritingModule) {
4018   using namespace llvm;
4019 
4020   bool isModule = WritingModule != nullptr;
4021 
4022   // Make sure that the AST reader knows to finalize itself.
4023   if (Chain)
4024     Chain->finalizeForWriting();
4025 
4026   ASTContext &Context = SemaRef.Context;
4027   Preprocessor &PP = SemaRef.PP;
4028 
4029   // Set up predefined declaration IDs.
4030   DeclIDs[Context.getTranslationUnitDecl()] = PREDEF_DECL_TRANSLATION_UNIT_ID;
4031   if (Context.ObjCIdDecl)
4032     DeclIDs[Context.ObjCIdDecl] = PREDEF_DECL_OBJC_ID_ID;
4033   if (Context.ObjCSelDecl)
4034     DeclIDs[Context.ObjCSelDecl] = PREDEF_DECL_OBJC_SEL_ID;
4035   if (Context.ObjCClassDecl)
4036     DeclIDs[Context.ObjCClassDecl] = PREDEF_DECL_OBJC_CLASS_ID;
4037   if (Context.ObjCProtocolClassDecl)
4038     DeclIDs[Context.ObjCProtocolClassDecl] = PREDEF_DECL_OBJC_PROTOCOL_ID;
4039   if (Context.Int128Decl)
4040     DeclIDs[Context.Int128Decl] = PREDEF_DECL_INT_128_ID;
4041   if (Context.UInt128Decl)
4042     DeclIDs[Context.UInt128Decl] = PREDEF_DECL_UNSIGNED_INT_128_ID;
4043   if (Context.ObjCInstanceTypeDecl)
4044     DeclIDs[Context.ObjCInstanceTypeDecl] = PREDEF_DECL_OBJC_INSTANCETYPE_ID;
4045   if (Context.BuiltinVaListDecl)
4046     DeclIDs[Context.getBuiltinVaListDecl()] = PREDEF_DECL_BUILTIN_VA_LIST_ID;
4047 
4048   if (!Chain) {
4049     // Make sure that we emit IdentifierInfos (and any attached
4050     // declarations) for builtins. We don't need to do this when we're
4051     // emitting chained PCH files, because all of the builtins will be
4052     // in the original PCH file.
4053     // FIXME: Modules won't like this at all.
4054     IdentifierTable &Table = PP.getIdentifierTable();
4055     SmallVector<const char *, 32> BuiltinNames;
4056     if (!Context.getLangOpts().NoBuiltin) {
4057       Context.BuiltinInfo.GetBuiltinNames(BuiltinNames);
4058     }
4059     for (unsigned I = 0, N = BuiltinNames.size(); I != N; ++I)
4060       getIdentifierRef(&Table.get(BuiltinNames[I]));
4061   }
4062 
4063   // If there are any out-of-date identifiers, bring them up to date.
4064   if (ExternalPreprocessorSource *ExtSource = PP.getExternalSource()) {
4065     // Find out-of-date identifiers.
4066     SmallVector<IdentifierInfo *, 4> OutOfDate;
4067     for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4068                                 IDEnd = PP.getIdentifierTable().end();
4069          ID != IDEnd; ++ID) {
4070       if (ID->second->isOutOfDate())
4071         OutOfDate.push_back(ID->second);
4072     }
4073 
4074     // Update the out-of-date identifiers.
4075     for (unsigned I = 0, N = OutOfDate.size(); I != N; ++I) {
4076       ExtSource->updateOutOfDateIdentifier(*OutOfDate[I]);
4077     }
4078   }
4079 
4080   // If we saw any DeclContext updates before we started writing the AST file,
4081   // make sure all visible decls in those DeclContexts are written out.
4082   if (!UpdatedDeclContexts.empty()) {
4083     auto OldUpdatedDeclContexts = std::move(UpdatedDeclContexts);
4084     UpdatedDeclContexts.clear();
4085     for (auto *DC : OldUpdatedDeclContexts)
4086       AddUpdatedDeclContext(DC);
4087   }
4088 
4089   // Build a record containing all of the tentative definitions in this file, in
4090   // TentativeDefinitions order.  Generally, this record will be empty for
4091   // headers.
4092   RecordData TentativeDefinitions;
4093   AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
4094 
4095   // Build a record containing all of the file scoped decls in this file.
4096   RecordData UnusedFileScopedDecls;
4097   if (!isModule)
4098     AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
4099                        UnusedFileScopedDecls);
4100 
4101   // Build a record containing all of the delegating constructors we still need
4102   // to resolve.
4103   RecordData DelegatingCtorDecls;
4104   if (!isModule)
4105     AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
4106 
4107   // Write the set of weak, undeclared identifiers. We always write the
4108   // entire table, since later PCH files in a PCH chain are only interested in
4109   // the results at the end of the chain.
4110   RecordData WeakUndeclaredIdentifiers;
4111   if (!SemaRef.WeakUndeclaredIdentifiers.empty()) {
4112     for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
4113          I = SemaRef.WeakUndeclaredIdentifiers.begin(),
4114          E = SemaRef.WeakUndeclaredIdentifiers.end(); I != E; ++I) {
4115       AddIdentifierRef(I->first, WeakUndeclaredIdentifiers);
4116       AddIdentifierRef(I->second.getAlias(), WeakUndeclaredIdentifiers);
4117       AddSourceLocation(I->second.getLocation(), WeakUndeclaredIdentifiers);
4118       WeakUndeclaredIdentifiers.push_back(I->second.getUsed());
4119     }
4120   }
4121 
4122   // Build a record containing all of the locally-scoped extern "C"
4123   // declarations in this header file. Generally, this record will be
4124   // empty.
4125   RecordData LocallyScopedExternCDecls;
4126   // FIXME: This is filling in the AST file in densemap order which is
4127   // nondeterminstic!
4128   for (llvm::DenseMap<DeclarationName, NamedDecl *>::iterator
4129          TD = SemaRef.LocallyScopedExternCDecls.begin(),
4130          TDEnd = SemaRef.LocallyScopedExternCDecls.end();
4131        TD != TDEnd; ++TD) {
4132     if (!TD->second->isFromASTFile())
4133       AddDeclRef(TD->second, LocallyScopedExternCDecls);
4134   }
4135 
4136   // Build a record containing all of the ext_vector declarations.
4137   RecordData ExtVectorDecls;
4138   AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
4139 
4140   // Build a record containing all of the VTable uses information.
4141   RecordData VTableUses;
4142   if (!SemaRef.VTableUses.empty()) {
4143     for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
4144       AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
4145       AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
4146       VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
4147     }
4148   }
4149 
4150   // Build a record containing all of dynamic classes declarations.
4151   RecordData DynamicClasses;
4152   AddLazyVectorDecls(*this, SemaRef.DynamicClasses, DynamicClasses);
4153 
4154   // Build a record containing all of pending implicit instantiations.
4155   RecordData PendingInstantiations;
4156   for (std::deque<Sema::PendingImplicitInstantiation>::iterator
4157          I = SemaRef.PendingInstantiations.begin(),
4158          N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
4159     AddDeclRef(I->first, PendingInstantiations);
4160     AddSourceLocation(I->second, PendingInstantiations);
4161   }
4162   assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
4163          "There are local ones at end of translation unit!");
4164 
4165   // Build a record containing some declaration references.
4166   RecordData SemaDeclRefs;
4167   if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
4168     AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
4169     AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
4170   }
4171 
4172   RecordData CUDASpecialDeclRefs;
4173   if (Context.getcudaConfigureCallDecl()) {
4174     AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
4175   }
4176 
4177   // Build a record containing all of the known namespaces.
4178   RecordData KnownNamespaces;
4179   for (llvm::MapVector<NamespaceDecl*, bool>::iterator
4180             I = SemaRef.KnownNamespaces.begin(),
4181          IEnd = SemaRef.KnownNamespaces.end();
4182        I != IEnd; ++I) {
4183     if (!I->second)
4184       AddDeclRef(I->first, KnownNamespaces);
4185   }
4186 
4187   // Build a record of all used, undefined objects that require definitions.
4188   RecordData UndefinedButUsed;
4189 
4190   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
4191   SemaRef.getUndefinedButUsed(Undefined);
4192   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
4193          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
4194     AddDeclRef(I->first, UndefinedButUsed);
4195     AddSourceLocation(I->second, UndefinedButUsed);
4196   }
4197 
4198   // Write the control block
4199   WriteControlBlock(PP, Context, isysroot, OutputFile);
4200 
4201   // Write the remaining AST contents.
4202   RecordData Record;
4203   Stream.EnterSubblock(AST_BLOCK_ID, 5);
4204 
4205   // This is so that older clang versions, before the introduction
4206   // of the control block, can read and reject the newer PCH format.
4207   Record.clear();
4208   Record.push_back(VERSION_MAJOR);
4209   Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
4210 
4211   // Create a lexical update block containing all of the declarations in the
4212   // translation unit that do not come from other AST files.
4213   const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
4214   SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
4215   for (const auto *I : TU->noload_decls()) {
4216     if (!I->isFromASTFile())
4217       NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
4218   }
4219 
4220   llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
4221   Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
4222   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4223   unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
4224   Record.clear();
4225   Record.push_back(TU_UPDATE_LEXICAL);
4226   Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
4227                             data(NewGlobalDecls));
4228 
4229   // And a visible updates block for the translation unit.
4230   Abv = new llvm::BitCodeAbbrev();
4231   Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
4232   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
4233   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
4234   Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
4235   UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
4236   WriteDeclContextVisibleUpdate(TU);
4237 
4238   // If the translation unit has an anonymous namespace, and we don't already
4239   // have an update block for it, write it as an update block.
4240   // FIXME: Why do we not do this if there's already an update block?
4241   if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
4242     ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
4243     if (Record.empty())
4244       Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
4245   }
4246 
4247   // Add update records for all mangling numbers and static local numbers.
4248   // These aren't really update records, but this is a convenient way of
4249   // tagging this rare extra data onto the declarations.
4250   for (const auto &Number : Context.MangleNumbers)
4251     if (!Number.first->isFromASTFile())
4252       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
4253                                                      Number.second));
4254   for (const auto &Number : Context.StaticLocalNumbers)
4255     if (!Number.first->isFromASTFile())
4256       DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
4257                                                      Number.second));
4258 
4259   // Make sure visible decls, added to DeclContexts previously loaded from
4260   // an AST file, are registered for serialization.
4261   for (SmallVectorImpl<const Decl *>::iterator
4262          I = UpdatingVisibleDecls.begin(),
4263          E = UpdatingVisibleDecls.end(); I != E; ++I) {
4264     GetDeclRef(*I);
4265   }
4266 
4267   // Make sure all decls associated with an identifier are registered for
4268   // serialization.
4269   for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
4270                               IDEnd = PP.getIdentifierTable().end();
4271        ID != IDEnd; ++ID) {
4272     const IdentifierInfo *II = ID->second;
4273     if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization()) {
4274       for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
4275                                      DEnd = SemaRef.IdResolver.end();
4276            D != DEnd; ++D) {
4277         GetDeclRef(*D);
4278       }
4279     }
4280   }
4281 
4282   // Form the record of special types.
4283   RecordData SpecialTypes;
4284   AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
4285   AddTypeRef(Context.getFILEType(), SpecialTypes);
4286   AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
4287   AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
4288   AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
4289   AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
4290   AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
4291   AddTypeRef(Context.getucontext_tType(), SpecialTypes);
4292 
4293   if (Chain) {
4294     // Write the mapping information describing our module dependencies and how
4295     // each of those modules were mapped into our own offset/ID space, so that
4296     // the reader can build the appropriate mapping to its own offset/ID space.
4297     // The map consists solely of a blob with the following format:
4298     // *(module-name-len:i16 module-name:len*i8
4299     //   source-location-offset:i32
4300     //   identifier-id:i32
4301     //   preprocessed-entity-id:i32
4302     //   macro-definition-id:i32
4303     //   submodule-id:i32
4304     //   selector-id:i32
4305     //   declaration-id:i32
4306     //   c++-base-specifiers-id:i32
4307     //   type-id:i32)
4308     //
4309     llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
4310     Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
4311     Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
4312     unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
4313     SmallString<2048> Buffer;
4314     {
4315       llvm::raw_svector_ostream Out(Buffer);
4316       for (ModuleManager::ModuleConstIterator M = Chain->ModuleMgr.begin(),
4317                                            MEnd = Chain->ModuleMgr.end();
4318            M != MEnd; ++M) {
4319         using namespace llvm::support;
4320         endian::Writer<little> LE(Out);
4321         StringRef FileName = (*M)->FileName;
4322         LE.write<uint16_t>(FileName.size());
4323         Out.write(FileName.data(), FileName.size());
4324         LE.write<uint32_t>((*M)->SLocEntryBaseOffset);
4325         LE.write<uint32_t>((*M)->BaseIdentifierID);
4326         LE.write<uint32_t>((*M)->BaseMacroID);
4327         LE.write<uint32_t>((*M)->BasePreprocessedEntityID);
4328         LE.write<uint32_t>((*M)->BaseSubmoduleID);
4329         LE.write<uint32_t>((*M)->BaseSelectorID);
4330         LE.write<uint32_t>((*M)->BaseDeclID);
4331         LE.write<uint32_t>((*M)->BaseTypeIndex);
4332       }
4333     }
4334     Record.clear();
4335     Record.push_back(MODULE_OFFSET_MAP);
4336     Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
4337                               Buffer.data(), Buffer.size());
4338   }
4339 
4340   RecordData DeclUpdatesOffsetsRecord;
4341 
4342   // Keep writing types, declarations, and declaration update records
4343   // until we've emitted all of them.
4344   Stream.EnterSubblock(DECLTYPES_BLOCK_ID, NUM_ALLOWED_ABBREVS_SIZE);
4345   WriteDeclsBlockAbbrevs();
4346   for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
4347                                   E = DeclsToRewrite.end();
4348        I != E; ++I)
4349     DeclTypesToEmit.push(const_cast<Decl*>(*I));
4350   do {
4351     WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
4352     while (!DeclTypesToEmit.empty()) {
4353       DeclOrType DOT = DeclTypesToEmit.front();
4354       DeclTypesToEmit.pop();
4355       if (DOT.isType())
4356         WriteType(DOT.getType());
4357       else
4358         WriteDecl(Context, DOT.getDecl());
4359     }
4360   } while (!DeclUpdates.empty());
4361   Stream.ExitBlock();
4362 
4363   DoneWritingDeclsAndTypes = true;
4364 
4365   // These things can only be done once we've written out decls and types.
4366   WriteTypeDeclOffsets();
4367   if (!DeclUpdatesOffsetsRecord.empty())
4368     Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
4369   WriteCXXBaseSpecifiersOffsets();
4370   WriteFileDeclIDsMap();
4371   WriteSourceManagerBlock(Context.getSourceManager(), PP, isysroot);
4372 
4373   WriteComments();
4374   WritePreprocessor(PP, isModule);
4375   WriteHeaderSearch(PP.getHeaderSearchInfo(), isysroot);
4376   WriteSelectors(SemaRef);
4377   WriteReferencedSelectorsPool(SemaRef);
4378   WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
4379   WriteFPPragmaOptions(SemaRef.getFPOptions());
4380   WriteOpenCLExtensions(SemaRef);
4381   WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
4382 
4383   // If we're emitting a module, write out the submodule information.
4384   if (WritingModule)
4385     WriteSubmodules(WritingModule);
4386 
4387   Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
4388 
4389   // Write the record containing external, unnamed definitions.
4390   if (!EagerlyDeserializedDecls.empty())
4391     Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
4392 
4393   // Write the record containing tentative definitions.
4394   if (!TentativeDefinitions.empty())
4395     Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
4396 
4397   // Write the record containing unused file scoped decls.
4398   if (!UnusedFileScopedDecls.empty())
4399     Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
4400 
4401   // Write the record containing weak undeclared identifiers.
4402   if (!WeakUndeclaredIdentifiers.empty())
4403     Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
4404                       WeakUndeclaredIdentifiers);
4405 
4406   // Write the record containing locally-scoped extern "C" definitions.
4407   if (!LocallyScopedExternCDecls.empty())
4408     Stream.EmitRecord(LOCALLY_SCOPED_EXTERN_C_DECLS,
4409                       LocallyScopedExternCDecls);
4410 
4411   // Write the record containing ext_vector type names.
4412   if (!ExtVectorDecls.empty())
4413     Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
4414 
4415   // Write the record containing VTable uses information.
4416   if (!VTableUses.empty())
4417     Stream.EmitRecord(VTABLE_USES, VTableUses);
4418 
4419   // Write the record containing dynamic classes declarations.
4420   if (!DynamicClasses.empty())
4421     Stream.EmitRecord(DYNAMIC_CLASSES, DynamicClasses);
4422 
4423   // Write the record containing pending implicit instantiations.
4424   if (!PendingInstantiations.empty())
4425     Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
4426 
4427   // Write the record containing declaration references of Sema.
4428   if (!SemaDeclRefs.empty())
4429     Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
4430 
4431   // Write the record containing CUDA-specific declaration references.
4432   if (!CUDASpecialDeclRefs.empty())
4433     Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
4434 
4435   // Write the delegating constructors.
4436   if (!DelegatingCtorDecls.empty())
4437     Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
4438 
4439   // Write the known namespaces.
4440   if (!KnownNamespaces.empty())
4441     Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
4442 
4443   // Write the undefined internal functions and variables, and inline functions.
4444   if (!UndefinedButUsed.empty())
4445     Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
4446 
4447   // Write the visible updates to DeclContexts.
4448   for (auto *DC : UpdatedDeclContexts)
4449     WriteDeclContextVisibleUpdate(DC);
4450 
4451   if (!WritingModule) {
4452     // Write the submodules that were imported, if any.
4453     struct ModuleInfo {
4454       uint64_t ID;
4455       Module *M;
4456       ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
4457     };
4458     llvm::SmallVector<ModuleInfo, 64> Imports;
4459     for (const auto *I : Context.local_imports()) {
4460       assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
4461       Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
4462                          I->getImportedModule()));
4463     }
4464 
4465     if (!Imports.empty()) {
4466       auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
4467         return A.ID < B.ID;
4468       };
4469 
4470       // Sort and deduplicate module IDs.
4471       std::sort(Imports.begin(), Imports.end(), Cmp);
4472       Imports.erase(std::unique(Imports.begin(), Imports.end(), Cmp),
4473                     Imports.end());
4474 
4475       RecordData ImportedModules;
4476       for (const auto &Import : Imports) {
4477         ImportedModules.push_back(Import.ID);
4478         // FIXME: If the module has macros imported then later has declarations
4479         // imported, this location won't be the right one as a location for the
4480         // declaration imports.
4481         AddSourceLocation(Import.M->MacroVisibilityLoc, ImportedModules);
4482       }
4483 
4484       Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
4485     }
4486   }
4487 
4488   WriteDeclReplacementsBlock();
4489   WriteRedeclarations();
4490   WriteMergedDecls();
4491   WriteObjCCategories();
4492   WriteLateParsedTemplates(SemaRef);
4493   if(!WritingModule)
4494     WriteOptimizePragmaOptions(SemaRef);
4495 
4496   // Some simple statistics
4497   Record.clear();
4498   Record.push_back(NumStatements);
4499   Record.push_back(NumMacros);
4500   Record.push_back(NumLexicalDeclContexts);
4501   Record.push_back(NumVisibleDeclContexts);
4502   Stream.EmitRecord(STATISTICS, Record);
4503   Stream.ExitBlock();
4504 }
4505 
4506 void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
4507   if (DeclUpdates.empty())
4508     return;
4509 
4510   DeclUpdateMap LocalUpdates;
4511   LocalUpdates.swap(DeclUpdates);
4512 
4513   for (auto &DeclUpdate : LocalUpdates) {
4514     const Decl *D = DeclUpdate.first;
4515     if (isRewritten(D))
4516       continue; // The decl will be written completely,no need to store updates.
4517 
4518     bool HasUpdatedBody = false;
4519     RecordData Record;
4520     for (auto &Update : DeclUpdate.second) {
4521       DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
4522 
4523       Record.push_back(Kind);
4524       switch (Kind) {
4525       case UPD_CXX_ADDED_IMPLICIT_MEMBER:
4526       case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4527       case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
4528         assert(Update.getDecl() && "no decl to add?");
4529         Record.push_back(GetDeclRef(Update.getDecl()));
4530         break;
4531 
4532       case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
4533         AddSourceLocation(Update.getLoc(), Record);
4534         break;
4535 
4536       case UPD_CXX_INSTANTIATED_FUNCTION_DEFINITION:
4537         // An updated body is emitted last, so that the reader doesn't need
4538         // to skip over the lazy body to reach statements for other records.
4539         Record.pop_back();
4540         HasUpdatedBody = true;
4541         break;
4542 
4543       case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4544         auto *RD = cast<CXXRecordDecl>(D);
4545         AddUpdatedDeclContext(RD->getPrimaryContext());
4546         AddCXXDefinitionData(RD, Record);
4547         Record.push_back(WriteDeclContextLexicalBlock(
4548             *Context, const_cast<CXXRecordDecl *>(RD)));
4549 
4550         // This state is sometimes updated by template instantiation, when we
4551         // switch from the specialization referring to the template declaration
4552         // to it referring to the template definition.
4553         if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
4554           Record.push_back(MSInfo->getTemplateSpecializationKind());
4555           AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
4556         } else {
4557           auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4558           Record.push_back(Spec->getTemplateSpecializationKind());
4559           AddSourceLocation(Spec->getPointOfInstantiation(), Record);
4560 
4561           // The instantiation might have been resolved to a partial
4562           // specialization. If so, record which one.
4563           auto From = Spec->getInstantiatedFrom();
4564           if (auto PartialSpec =
4565                 From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
4566             Record.push_back(true);
4567             AddDeclRef(PartialSpec, Record);
4568             AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
4569                                     Record);
4570           } else {
4571             Record.push_back(false);
4572           }
4573         }
4574         Record.push_back(RD->getTagKind());
4575         AddSourceLocation(RD->getLocation(), Record);
4576         AddSourceLocation(RD->getLocStart(), Record);
4577         AddSourceLocation(RD->getRBraceLoc(), Record);
4578 
4579         // Instantiation may change attributes; write them all out afresh.
4580         Record.push_back(D->hasAttrs());
4581         if (Record.back())
4582           WriteAttributes(ArrayRef<const Attr*>(D->getAttrs().begin(),
4583                                                 D->getAttrs().size()), Record);
4584 
4585         // FIXME: Ensure we don't get here for explicit instantiations.
4586         break;
4587       }
4588 
4589       case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
4590         addExceptionSpec(
4591             *this,
4592             cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
4593             Record);
4594         break;
4595 
4596       case UPD_CXX_DEDUCED_RETURN_TYPE:
4597         Record.push_back(GetOrCreateTypeID(Update.getType()));
4598         break;
4599 
4600       case UPD_DECL_MARKED_USED:
4601         break;
4602 
4603       case UPD_MANGLING_NUMBER:
4604       case UPD_STATIC_LOCAL_NUMBER:
4605         Record.push_back(Update.getNumber());
4606         break;
4607       }
4608     }
4609 
4610     if (HasUpdatedBody) {
4611       const FunctionDecl *Def = cast<FunctionDecl>(D);
4612       Record.push_back(UPD_CXX_INSTANTIATED_FUNCTION_DEFINITION);
4613       Record.push_back(Def->isInlined());
4614       AddSourceLocation(Def->getInnerLocStart(), Record);
4615       AddFunctionDefinition(Def, Record);
4616     }
4617 
4618     OffsetsRecord.push_back(GetDeclRef(D));
4619     OffsetsRecord.push_back(Stream.GetCurrentBitNo());
4620 
4621     Stream.EmitRecord(DECL_UPDATES, Record);
4622 
4623     // Flush any statements that were written as part of this update record.
4624     FlushStmts();
4625 
4626     // Flush C++ base specifiers, if there are any.
4627     FlushCXXBaseSpecifiers();
4628   }
4629 }
4630 
4631 void ASTWriter::WriteDeclReplacementsBlock() {
4632   if (ReplacedDecls.empty())
4633     return;
4634 
4635   RecordData Record;
4636   for (SmallVectorImpl<ReplacedDeclInfo>::iterator
4637          I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
4638     Record.push_back(I->ID);
4639     Record.push_back(I->Offset);
4640     Record.push_back(I->Loc);
4641   }
4642   Stream.EmitRecord(DECL_REPLACEMENTS, Record);
4643 }
4644 
4645 void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
4646   Record.push_back(Loc.getRawEncoding());
4647 }
4648 
4649 void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
4650   AddSourceLocation(Range.getBegin(), Record);
4651   AddSourceLocation(Range.getEnd(), Record);
4652 }
4653 
4654 void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
4655   Record.push_back(Value.getBitWidth());
4656   const uint64_t *Words = Value.getRawData();
4657   Record.append(Words, Words + Value.getNumWords());
4658 }
4659 
4660 void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
4661   Record.push_back(Value.isUnsigned());
4662   AddAPInt(Value, Record);
4663 }
4664 
4665 void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
4666   AddAPInt(Value.bitcastToAPInt(), Record);
4667 }
4668 
4669 void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
4670   Record.push_back(getIdentifierRef(II));
4671 }
4672 
4673 IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
4674   if (!II)
4675     return 0;
4676 
4677   IdentID &ID = IdentifierIDs[II];
4678   if (ID == 0)
4679     ID = NextIdentID++;
4680   return ID;
4681 }
4682 
4683 MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
4684   // Don't emit builtin macros like __LINE__ to the AST file unless they
4685   // have been redefined by the header (in which case they are not
4686   // isBuiltinMacro).
4687   if (!MI || MI->isBuiltinMacro())
4688     return 0;
4689 
4690   MacroID &ID = MacroIDs[MI];
4691   if (ID == 0) {
4692     ID = NextMacroID++;
4693     MacroInfoToEmitData Info = { Name, MI, ID };
4694     MacroInfosToEmit.push_back(Info);
4695   }
4696   return ID;
4697 }
4698 
4699 MacroID ASTWriter::getMacroID(MacroInfo *MI) {
4700   if (!MI || MI->isBuiltinMacro())
4701     return 0;
4702 
4703   assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
4704   return MacroIDs[MI];
4705 }
4706 
4707 uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
4708   assert(IdentMacroDirectivesOffsetMap[Name] && "not set!");
4709   return IdentMacroDirectivesOffsetMap[Name];
4710 }
4711 
4712 void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
4713   Record.push_back(getSelectorRef(SelRef));
4714 }
4715 
4716 SelectorID ASTWriter::getSelectorRef(Selector Sel) {
4717   if (Sel.getAsOpaquePtr() == nullptr) {
4718     return 0;
4719   }
4720 
4721   SelectorID SID = SelectorIDs[Sel];
4722   if (SID == 0 && Chain) {
4723     // This might trigger a ReadSelector callback, which will set the ID for
4724     // this selector.
4725     Chain->LoadSelector(Sel);
4726     SID = SelectorIDs[Sel];
4727   }
4728   if (SID == 0) {
4729     SID = NextSelectorID++;
4730     SelectorIDs[Sel] = SID;
4731   }
4732   return SID;
4733 }
4734 
4735 void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
4736   AddDeclRef(Temp->getDestructor(), Record);
4737 }
4738 
4739 void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
4740                                       CXXBaseSpecifier const *BasesEnd,
4741                                         RecordDataImpl &Record) {
4742   assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
4743   CXXBaseSpecifiersToWrite.push_back(
4744                                 QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
4745                                                         Bases, BasesEnd));
4746   Record.push_back(NextCXXBaseSpecifiersID++);
4747 }
4748 
4749 void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
4750                                            const TemplateArgumentLocInfo &Arg,
4751                                            RecordDataImpl &Record) {
4752   switch (Kind) {
4753   case TemplateArgument::Expression:
4754     AddStmt(Arg.getAsExpr());
4755     break;
4756   case TemplateArgument::Type:
4757     AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
4758     break;
4759   case TemplateArgument::Template:
4760     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4761     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4762     break;
4763   case TemplateArgument::TemplateExpansion:
4764     AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
4765     AddSourceLocation(Arg.getTemplateNameLoc(), Record);
4766     AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
4767     break;
4768   case TemplateArgument::Null:
4769   case TemplateArgument::Integral:
4770   case TemplateArgument::Declaration:
4771   case TemplateArgument::NullPtr:
4772   case TemplateArgument::Pack:
4773     // FIXME: Is this right?
4774     break;
4775   }
4776 }
4777 
4778 void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
4779                                        RecordDataImpl &Record) {
4780   AddTemplateArgument(Arg.getArgument(), Record);
4781 
4782   if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
4783     bool InfoHasSameExpr
4784       = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
4785     Record.push_back(InfoHasSameExpr);
4786     if (InfoHasSameExpr)
4787       return; // Avoid storing the same expr twice.
4788   }
4789   AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
4790                              Record);
4791 }
4792 
4793 void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
4794                                   RecordDataImpl &Record) {
4795   if (!TInfo) {
4796     AddTypeRef(QualType(), Record);
4797     return;
4798   }
4799 
4800   AddTypeLoc(TInfo->getTypeLoc(), Record);
4801 }
4802 
4803 void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
4804   AddTypeRef(TL.getType(), Record);
4805 
4806   TypeLocWriter TLW(*this, Record);
4807   for (; !TL.isNull(); TL = TL.getNextTypeLoc())
4808     TLW.Visit(TL);
4809 }
4810 
4811 void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
4812   Record.push_back(GetOrCreateTypeID(T));
4813 }
4814 
4815 TypeID ASTWriter::GetOrCreateTypeID( QualType T) {
4816   assert(Context);
4817   return MakeTypeID(*Context, T,
4818               std::bind1st(std::mem_fun(&ASTWriter::GetOrCreateTypeIdx), this));
4819 }
4820 
4821 TypeID ASTWriter::getTypeID(QualType T) const {
4822   assert(Context);
4823   return MakeTypeID(*Context, T,
4824               std::bind1st(std::mem_fun(&ASTWriter::getTypeIdx), this));
4825 }
4826 
4827 TypeIdx ASTWriter::GetOrCreateTypeIdx(QualType T) {
4828   if (T.isNull())
4829     return TypeIdx();
4830   assert(!T.getLocalFastQualifiers());
4831 
4832   TypeIdx &Idx = TypeIdxs[T];
4833   if (Idx.getIndex() == 0) {
4834     if (DoneWritingDeclsAndTypes) {
4835       assert(0 && "New type seen after serializing all the types to emit!");
4836       return TypeIdx();
4837     }
4838 
4839     // We haven't seen this type before. Assign it a new ID and put it
4840     // into the queue of types to emit.
4841     Idx = TypeIdx(NextTypeID++);
4842     DeclTypesToEmit.push(T);
4843   }
4844   return Idx;
4845 }
4846 
4847 TypeIdx ASTWriter::getTypeIdx(QualType T) const {
4848   if (T.isNull())
4849     return TypeIdx();
4850   assert(!T.getLocalFastQualifiers());
4851 
4852   TypeIdxMap::const_iterator I = TypeIdxs.find(T);
4853   assert(I != TypeIdxs.end() && "Type not emitted!");
4854   return I->second;
4855 }
4856 
4857 void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
4858   Record.push_back(GetDeclRef(D));
4859 }
4860 
4861 DeclID ASTWriter::GetDeclRef(const Decl *D) {
4862   assert(WritingAST && "Cannot request a declaration ID before AST writing");
4863 
4864   if (!D) {
4865     return 0;
4866   }
4867 
4868   // If D comes from an AST file, its declaration ID is already known and
4869   // fixed.
4870   if (D->isFromASTFile())
4871     return D->getGlobalID();
4872 
4873   assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
4874   DeclID &ID = DeclIDs[D];
4875   if (ID == 0) {
4876     if (DoneWritingDeclsAndTypes) {
4877       assert(0 && "New decl seen after serializing all the decls to emit!");
4878       return 0;
4879     }
4880 
4881     // We haven't seen this declaration before. Give it a new ID and
4882     // enqueue it in the list of declarations to emit.
4883     ID = NextDeclID++;
4884     DeclTypesToEmit.push(const_cast<Decl *>(D));
4885   }
4886 
4887   return ID;
4888 }
4889 
4890 DeclID ASTWriter::getDeclID(const Decl *D) {
4891   if (!D)
4892     return 0;
4893 
4894   // If D comes from an AST file, its declaration ID is already known and
4895   // fixed.
4896   if (D->isFromASTFile())
4897     return D->getGlobalID();
4898 
4899   assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
4900   return DeclIDs[D];
4901 }
4902 
4903 void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
4904   assert(ID);
4905   assert(D);
4906 
4907   SourceLocation Loc = D->getLocation();
4908   if (Loc.isInvalid())
4909     return;
4910 
4911   // We only keep track of the file-level declarations of each file.
4912   if (!D->getLexicalDeclContext()->isFileContext())
4913     return;
4914   // FIXME: ParmVarDecls that are part of a function type of a parameter of
4915   // a function/objc method, should not have TU as lexical context.
4916   if (isa<ParmVarDecl>(D))
4917     return;
4918 
4919   SourceManager &SM = Context->getSourceManager();
4920   SourceLocation FileLoc = SM.getFileLoc(Loc);
4921   assert(SM.isLocalSourceLocation(FileLoc));
4922   FileID FID;
4923   unsigned Offset;
4924   std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
4925   if (FID.isInvalid())
4926     return;
4927   assert(SM.getSLocEntry(FID).isFile());
4928 
4929   DeclIDInFileInfo *&Info = FileDeclIDs[FID];
4930   if (!Info)
4931     Info = new DeclIDInFileInfo();
4932 
4933   std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
4934   LocDeclIDsTy &Decls = Info->DeclIDs;
4935 
4936   if (Decls.empty() || Decls.back().first <= Offset) {
4937     Decls.push_back(LocDecl);
4938     return;
4939   }
4940 
4941   LocDeclIDsTy::iterator I =
4942       std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
4943 
4944   Decls.insert(I, LocDecl);
4945 }
4946 
4947 void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
4948   // FIXME: Emit a stable enum for NameKind.  0 = Identifier etc.
4949   Record.push_back(Name.getNameKind());
4950   switch (Name.getNameKind()) {
4951   case DeclarationName::Identifier:
4952     AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
4953     break;
4954 
4955   case DeclarationName::ObjCZeroArgSelector:
4956   case DeclarationName::ObjCOneArgSelector:
4957   case DeclarationName::ObjCMultiArgSelector:
4958     AddSelectorRef(Name.getObjCSelector(), Record);
4959     break;
4960 
4961   case DeclarationName::CXXConstructorName:
4962   case DeclarationName::CXXDestructorName:
4963   case DeclarationName::CXXConversionFunctionName:
4964     AddTypeRef(Name.getCXXNameType(), Record);
4965     break;
4966 
4967   case DeclarationName::CXXOperatorName:
4968     Record.push_back(Name.getCXXOverloadedOperator());
4969     break;
4970 
4971   case DeclarationName::CXXLiteralOperatorName:
4972     AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
4973     break;
4974 
4975   case DeclarationName::CXXUsingDirective:
4976     // No extra data to emit
4977     break;
4978   }
4979 }
4980 
4981 void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
4982                                      DeclarationName Name, RecordDataImpl &Record) {
4983   switch (Name.getNameKind()) {
4984   case DeclarationName::CXXConstructorName:
4985   case DeclarationName::CXXDestructorName:
4986   case DeclarationName::CXXConversionFunctionName:
4987     AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
4988     break;
4989 
4990   case DeclarationName::CXXOperatorName:
4991     AddSourceLocation(
4992        SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
4993        Record);
4994     AddSourceLocation(
4995         SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
4996         Record);
4997     break;
4998 
4999   case DeclarationName::CXXLiteralOperatorName:
5000     AddSourceLocation(
5001      SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
5002      Record);
5003     break;
5004 
5005   case DeclarationName::Identifier:
5006   case DeclarationName::ObjCZeroArgSelector:
5007   case DeclarationName::ObjCOneArgSelector:
5008   case DeclarationName::ObjCMultiArgSelector:
5009   case DeclarationName::CXXUsingDirective:
5010     break;
5011   }
5012 }
5013 
5014 void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
5015                                        RecordDataImpl &Record) {
5016   AddDeclarationName(NameInfo.getName(), Record);
5017   AddSourceLocation(NameInfo.getLoc(), Record);
5018   AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
5019 }
5020 
5021 void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
5022                                  RecordDataImpl &Record) {
5023   AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
5024   Record.push_back(Info.NumTemplParamLists);
5025   for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
5026     AddTemplateParameterList(Info.TemplParamLists[i], Record);
5027 }
5028 
5029 void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
5030                                        RecordDataImpl &Record) {
5031   // Nested name specifiers usually aren't too long. I think that 8 would
5032   // typically accommodate the vast majority.
5033   SmallVector<NestedNameSpecifier *, 8> NestedNames;
5034 
5035   // Push each of the NNS's onto a stack for serialization in reverse order.
5036   while (NNS) {
5037     NestedNames.push_back(NNS);
5038     NNS = NNS->getPrefix();
5039   }
5040 
5041   Record.push_back(NestedNames.size());
5042   while(!NestedNames.empty()) {
5043     NNS = NestedNames.pop_back_val();
5044     NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
5045     Record.push_back(Kind);
5046     switch (Kind) {
5047     case NestedNameSpecifier::Identifier:
5048       AddIdentifierRef(NNS->getAsIdentifier(), Record);
5049       break;
5050 
5051     case NestedNameSpecifier::Namespace:
5052       AddDeclRef(NNS->getAsNamespace(), Record);
5053       break;
5054 
5055     case NestedNameSpecifier::NamespaceAlias:
5056       AddDeclRef(NNS->getAsNamespaceAlias(), Record);
5057       break;
5058 
5059     case NestedNameSpecifier::TypeSpec:
5060     case NestedNameSpecifier::TypeSpecWithTemplate:
5061       AddTypeRef(QualType(NNS->getAsType(), 0), Record);
5062       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5063       break;
5064 
5065     case NestedNameSpecifier::Global:
5066       // Don't need to write an associated value.
5067       break;
5068     }
5069   }
5070 }
5071 
5072 void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
5073                                           RecordDataImpl &Record) {
5074   // Nested name specifiers usually aren't too long. I think that 8 would
5075   // typically accommodate the vast majority.
5076   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5077 
5078   // Push each of the nested-name-specifiers's onto a stack for
5079   // serialization in reverse order.
5080   while (NNS) {
5081     NestedNames.push_back(NNS);
5082     NNS = NNS.getPrefix();
5083   }
5084 
5085   Record.push_back(NestedNames.size());
5086   while(!NestedNames.empty()) {
5087     NNS = NestedNames.pop_back_val();
5088     NestedNameSpecifier::SpecifierKind Kind
5089       = NNS.getNestedNameSpecifier()->getKind();
5090     Record.push_back(Kind);
5091     switch (Kind) {
5092     case NestedNameSpecifier::Identifier:
5093       AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
5094       AddSourceRange(NNS.getLocalSourceRange(), Record);
5095       break;
5096 
5097     case NestedNameSpecifier::Namespace:
5098       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
5099       AddSourceRange(NNS.getLocalSourceRange(), Record);
5100       break;
5101 
5102     case NestedNameSpecifier::NamespaceAlias:
5103       AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
5104       AddSourceRange(NNS.getLocalSourceRange(), Record);
5105       break;
5106 
5107     case NestedNameSpecifier::TypeSpec:
5108     case NestedNameSpecifier::TypeSpecWithTemplate:
5109       Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
5110       AddTypeLoc(NNS.getTypeLoc(), Record);
5111       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5112       break;
5113 
5114     case NestedNameSpecifier::Global:
5115       AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
5116       break;
5117     }
5118   }
5119 }
5120 
5121 void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
5122   TemplateName::NameKind Kind = Name.getKind();
5123   Record.push_back(Kind);
5124   switch (Kind) {
5125   case TemplateName::Template:
5126     AddDeclRef(Name.getAsTemplateDecl(), Record);
5127     break;
5128 
5129   case TemplateName::OverloadedTemplate: {
5130     OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
5131     Record.push_back(OvT->size());
5132     for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
5133            I != E; ++I)
5134       AddDeclRef(*I, Record);
5135     break;
5136   }
5137 
5138   case TemplateName::QualifiedTemplate: {
5139     QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
5140     AddNestedNameSpecifier(QualT->getQualifier(), Record);
5141     Record.push_back(QualT->hasTemplateKeyword());
5142     AddDeclRef(QualT->getTemplateDecl(), Record);
5143     break;
5144   }
5145 
5146   case TemplateName::DependentTemplate: {
5147     DependentTemplateName *DepT = Name.getAsDependentTemplateName();
5148     AddNestedNameSpecifier(DepT->getQualifier(), Record);
5149     Record.push_back(DepT->isIdentifier());
5150     if (DepT->isIdentifier())
5151       AddIdentifierRef(DepT->getIdentifier(), Record);
5152     else
5153       Record.push_back(DepT->getOperator());
5154     break;
5155   }
5156 
5157   case TemplateName::SubstTemplateTemplateParm: {
5158     SubstTemplateTemplateParmStorage *subst
5159       = Name.getAsSubstTemplateTemplateParm();
5160     AddDeclRef(subst->getParameter(), Record);
5161     AddTemplateName(subst->getReplacement(), Record);
5162     break;
5163   }
5164 
5165   case TemplateName::SubstTemplateTemplateParmPack: {
5166     SubstTemplateTemplateParmPackStorage *SubstPack
5167       = Name.getAsSubstTemplateTemplateParmPack();
5168     AddDeclRef(SubstPack->getParameterPack(), Record);
5169     AddTemplateArgument(SubstPack->getArgumentPack(), Record);
5170     break;
5171   }
5172   }
5173 }
5174 
5175 void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
5176                                     RecordDataImpl &Record) {
5177   Record.push_back(Arg.getKind());
5178   switch (Arg.getKind()) {
5179   case TemplateArgument::Null:
5180     break;
5181   case TemplateArgument::Type:
5182     AddTypeRef(Arg.getAsType(), Record);
5183     break;
5184   case TemplateArgument::Declaration:
5185     AddDeclRef(Arg.getAsDecl(), Record);
5186     Record.push_back(Arg.isDeclForReferenceParam());
5187     break;
5188   case TemplateArgument::NullPtr:
5189     AddTypeRef(Arg.getNullPtrType(), Record);
5190     break;
5191   case TemplateArgument::Integral:
5192     AddAPSInt(Arg.getAsIntegral(), Record);
5193     AddTypeRef(Arg.getIntegralType(), Record);
5194     break;
5195   case TemplateArgument::Template:
5196     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5197     break;
5198   case TemplateArgument::TemplateExpansion:
5199     AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
5200     if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
5201       Record.push_back(*NumExpansions + 1);
5202     else
5203       Record.push_back(0);
5204     break;
5205   case TemplateArgument::Expression:
5206     AddStmt(Arg.getAsExpr());
5207     break;
5208   case TemplateArgument::Pack:
5209     Record.push_back(Arg.pack_size());
5210     for (const auto &P : Arg.pack_elements())
5211       AddTemplateArgument(P, Record);
5212     break;
5213   }
5214 }
5215 
5216 void
5217 ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
5218                                     RecordDataImpl &Record) {
5219   assert(TemplateParams && "No TemplateParams!");
5220   AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
5221   AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
5222   AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
5223   Record.push_back(TemplateParams->size());
5224   for (TemplateParameterList::const_iterator
5225          P = TemplateParams->begin(), PEnd = TemplateParams->end();
5226          P != PEnd; ++P)
5227     AddDeclRef(*P, Record);
5228 }
5229 
5230 /// \brief Emit a template argument list.
5231 void
5232 ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
5233                                    RecordDataImpl &Record) {
5234   assert(TemplateArgs && "No TemplateArgs!");
5235   Record.push_back(TemplateArgs->size());
5236   for (int i=0, e = TemplateArgs->size(); i != e; ++i)
5237     AddTemplateArgument(TemplateArgs->get(i), Record);
5238 }
5239 
5240 void
5241 ASTWriter::AddASTTemplateArgumentListInfo
5242 (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
5243   assert(ASTTemplArgList && "No ASTTemplArgList!");
5244   AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
5245   AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
5246   Record.push_back(ASTTemplArgList->NumTemplateArgs);
5247   const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
5248   for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
5249     AddTemplateArgumentLoc(TemplArgs[i], Record);
5250 }
5251 
5252 void
5253 ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
5254   Record.push_back(Set.size());
5255   for (ASTUnresolvedSet::const_iterator
5256          I = Set.begin(), E = Set.end(); I != E; ++I) {
5257     AddDeclRef(I.getDecl(), Record);
5258     Record.push_back(I.getAccess());
5259   }
5260 }
5261 
5262 void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
5263                                     RecordDataImpl &Record) {
5264   Record.push_back(Base.isVirtual());
5265   Record.push_back(Base.isBaseOfClass());
5266   Record.push_back(Base.getAccessSpecifierAsWritten());
5267   Record.push_back(Base.getInheritConstructors());
5268   AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
5269   AddSourceRange(Base.getSourceRange(), Record);
5270   AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
5271                                           : SourceLocation(),
5272                     Record);
5273 }
5274 
5275 void ASTWriter::FlushCXXBaseSpecifiers() {
5276   RecordData Record;
5277   for (unsigned I = 0, N = CXXBaseSpecifiersToWrite.size(); I != N; ++I) {
5278     Record.clear();
5279 
5280     // Record the offset of this base-specifier set.
5281     unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
5282     if (Index == CXXBaseSpecifiersOffsets.size())
5283       CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
5284     else {
5285       if (Index > CXXBaseSpecifiersOffsets.size())
5286         CXXBaseSpecifiersOffsets.resize(Index + 1);
5287       CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
5288     }
5289 
5290     const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
5291                         *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
5292     Record.push_back(BEnd - B);
5293     for (; B != BEnd; ++B)
5294       AddCXXBaseSpecifier(*B, Record);
5295     Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
5296 
5297     // Flush any expressions that were written as part of the base specifiers.
5298     FlushStmts();
5299   }
5300 
5301   CXXBaseSpecifiersToWrite.clear();
5302 }
5303 
5304 void ASTWriter::AddCXXCtorInitializers(
5305                              const CXXCtorInitializer * const *CtorInitializers,
5306                              unsigned NumCtorInitializers,
5307                              RecordDataImpl &Record) {
5308   Record.push_back(NumCtorInitializers);
5309   for (unsigned i=0; i != NumCtorInitializers; ++i) {
5310     const CXXCtorInitializer *Init = CtorInitializers[i];
5311 
5312     if (Init->isBaseInitializer()) {
5313       Record.push_back(CTOR_INITIALIZER_BASE);
5314       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5315       Record.push_back(Init->isBaseVirtual());
5316     } else if (Init->isDelegatingInitializer()) {
5317       Record.push_back(CTOR_INITIALIZER_DELEGATING);
5318       AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
5319     } else if (Init->isMemberInitializer()){
5320       Record.push_back(CTOR_INITIALIZER_MEMBER);
5321       AddDeclRef(Init->getMember(), Record);
5322     } else {
5323       Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
5324       AddDeclRef(Init->getIndirectMember(), Record);
5325     }
5326 
5327     AddSourceLocation(Init->getMemberLocation(), Record);
5328     AddStmt(Init->getInit());
5329     AddSourceLocation(Init->getLParenLoc(), Record);
5330     AddSourceLocation(Init->getRParenLoc(), Record);
5331     Record.push_back(Init->isWritten());
5332     if (Init->isWritten()) {
5333       Record.push_back(Init->getSourceOrder());
5334     } else {
5335       Record.push_back(Init->getNumArrayIndices());
5336       for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
5337         AddDeclRef(Init->getArrayIndex(i), Record);
5338     }
5339   }
5340 }
5341 
5342 void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
5343   auto &Data = D->data();
5344   Record.push_back(Data.IsLambda);
5345   Record.push_back(Data.UserDeclaredConstructor);
5346   Record.push_back(Data.UserDeclaredSpecialMembers);
5347   Record.push_back(Data.Aggregate);
5348   Record.push_back(Data.PlainOldData);
5349   Record.push_back(Data.Empty);
5350   Record.push_back(Data.Polymorphic);
5351   Record.push_back(Data.Abstract);
5352   Record.push_back(Data.IsStandardLayout);
5353   Record.push_back(Data.HasNoNonEmptyBases);
5354   Record.push_back(Data.HasPrivateFields);
5355   Record.push_back(Data.HasProtectedFields);
5356   Record.push_back(Data.HasPublicFields);
5357   Record.push_back(Data.HasMutableFields);
5358   Record.push_back(Data.HasVariantMembers);
5359   Record.push_back(Data.HasOnlyCMembers);
5360   Record.push_back(Data.HasInClassInitializer);
5361   Record.push_back(Data.HasUninitializedReferenceMember);
5362   Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
5363   Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
5364   Record.push_back(Data.NeedOverloadResolutionForDestructor);
5365   Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
5366   Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
5367   Record.push_back(Data.DefaultedDestructorIsDeleted);
5368   Record.push_back(Data.HasTrivialSpecialMembers);
5369   Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
5370   Record.push_back(Data.HasIrrelevantDestructor);
5371   Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
5372   Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
5373   Record.push_back(Data.HasConstexprDefaultConstructor);
5374   Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
5375   Record.push_back(Data.ComputedVisibleConversions);
5376   Record.push_back(Data.UserProvidedDefaultConstructor);
5377   Record.push_back(Data.DeclaredSpecialMembers);
5378   Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
5379   Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
5380   Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
5381   Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
5382   // IsLambda bit is already saved.
5383 
5384   Record.push_back(Data.NumBases);
5385   if (Data.NumBases > 0)
5386     AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
5387                             Record);
5388 
5389   // FIXME: Make VBases lazily computed when needed to avoid storing them.
5390   Record.push_back(Data.NumVBases);
5391   if (Data.NumVBases > 0)
5392     AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
5393                             Record);
5394 
5395   AddUnresolvedSet(Data.Conversions.get(*Context), Record);
5396   AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
5397   // Data.Definition is the owning decl, no need to write it.
5398   AddDeclRef(D->getFirstFriend(), Record);
5399 
5400   // Add lambda-specific data.
5401   if (Data.IsLambda) {
5402     auto &Lambda = D->getLambdaData();
5403     Record.push_back(Lambda.Dependent);
5404     Record.push_back(Lambda.IsGenericLambda);
5405     Record.push_back(Lambda.CaptureDefault);
5406     Record.push_back(Lambda.NumCaptures);
5407     Record.push_back(Lambda.NumExplicitCaptures);
5408     Record.push_back(Lambda.ManglingNumber);
5409     AddDeclRef(Lambda.ContextDecl, Record);
5410     AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
5411     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
5412       const LambdaCapture &Capture = Lambda.Captures[I];
5413       AddSourceLocation(Capture.getLocation(), Record);
5414       Record.push_back(Capture.isImplicit());
5415       Record.push_back(Capture.getCaptureKind());
5416       switch (Capture.getCaptureKind()) {
5417       case LCK_This:
5418         break;
5419       case LCK_ByCopy:
5420       case LCK_ByRef:
5421         VarDecl *Var =
5422             Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
5423         AddDeclRef(Var, Record);
5424         AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
5425                                                     : SourceLocation(),
5426                           Record);
5427         break;
5428       }
5429     }
5430   }
5431 }
5432 
5433 void ASTWriter::ReaderInitialized(ASTReader *Reader) {
5434   assert(Reader && "Cannot remove chain");
5435   assert((!Chain || Chain == Reader) && "Cannot replace chain");
5436   assert(FirstDeclID == NextDeclID &&
5437          FirstTypeID == NextTypeID &&
5438          FirstIdentID == NextIdentID &&
5439          FirstMacroID == NextMacroID &&
5440          FirstSubmoduleID == NextSubmoduleID &&
5441          FirstSelectorID == NextSelectorID &&
5442          "Setting chain after writing has started.");
5443 
5444   Chain = Reader;
5445 
5446   FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
5447   FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
5448   FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
5449   FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
5450   FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
5451   FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
5452   NextDeclID = FirstDeclID;
5453   NextTypeID = FirstTypeID;
5454   NextIdentID = FirstIdentID;
5455   NextMacroID = FirstMacroID;
5456   NextSelectorID = FirstSelectorID;
5457   NextSubmoduleID = FirstSubmoduleID;
5458 }
5459 
5460 void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
5461   // Always keep the highest ID. See \p TypeRead() for more information.
5462   IdentID &StoredID = IdentifierIDs[II];
5463   if (ID > StoredID)
5464     StoredID = ID;
5465 }
5466 
5467 void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
5468   // Always keep the highest ID. See \p TypeRead() for more information.
5469   MacroID &StoredID = MacroIDs[MI];
5470   if (ID > StoredID)
5471     StoredID = ID;
5472 }
5473 
5474 void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
5475   // Always take the highest-numbered type index. This copes with an interesting
5476   // case for chained AST writing where we schedule writing the type and then,
5477   // later, deserialize the type from another AST. In this case, we want to
5478   // keep the higher-numbered entry so that we can properly write it out to
5479   // the AST file.
5480   TypeIdx &StoredIdx = TypeIdxs[T];
5481   if (Idx.getIndex() >= StoredIdx.getIndex())
5482     StoredIdx = Idx;
5483 }
5484 
5485 void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
5486   // Always keep the highest ID. See \p TypeRead() for more information.
5487   SelectorID &StoredID = SelectorIDs[S];
5488   if (ID > StoredID)
5489     StoredID = ID;
5490 }
5491 
5492 void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
5493                                     MacroDefinition *MD) {
5494   assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
5495   MacroDefinitions[MD] = ID;
5496 }
5497 
5498 void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
5499   assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
5500   SubmoduleIDs[Mod] = ID;
5501 }
5502 
5503 void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
5504   assert(D->isCompleteDefinition());
5505   assert(!WritingAST && "Already writing the AST!");
5506   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
5507     // We are interested when a PCH decl is modified.
5508     if (RD->isFromASTFile()) {
5509       // A forward reference was mutated into a definition. Rewrite it.
5510       // FIXME: This happens during template instantiation, should we
5511       // have created a new definition decl instead ?
5512       assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
5513              "completed a tag from another module but not by instantiation?");
5514       DeclUpdates[RD].push_back(
5515           DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
5516     }
5517   }
5518 }
5519 
5520 void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
5521   assert(!WritingAST && "Already writing the AST!");
5522 
5523   // TU and namespaces are handled elsewhere.
5524   if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
5525     return;
5526 
5527   if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
5528     return; // Not a source decl added to a DeclContext from PCH.
5529 
5530   assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
5531   AddUpdatedDeclContext(DC);
5532   UpdatingVisibleDecls.push_back(D);
5533 }
5534 
5535 void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
5536   assert(!WritingAST && "Already writing the AST!");
5537   assert(D->isImplicit());
5538   if (!(!D->isFromASTFile() && RD->isFromASTFile()))
5539     return; // Not a source member added to a class from PCH.
5540   if (!isa<CXXMethodDecl>(D))
5541     return; // We are interested in lazily declared implicit methods.
5542 
5543   // A decl coming from PCH was modified.
5544   assert(RD->isCompleteDefinition());
5545   DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
5546 }
5547 
5548 void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
5549                                      const ClassTemplateSpecializationDecl *D) {
5550   // The specializations set is kept in the canonical template.
5551   assert(!WritingAST && "Already writing the AST!");
5552   TD = TD->getCanonicalDecl();
5553   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5554     return; // Not a source specialization added to a template from PCH.
5555 
5556   DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5557                                        D));
5558 }
5559 
5560 void ASTWriter::AddedCXXTemplateSpecialization(
5561     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
5562   // The specializations set is kept in the canonical template.
5563   assert(!WritingAST && "Already writing the AST!");
5564   TD = TD->getCanonicalDecl();
5565   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5566     return; // Not a source specialization added to a template from PCH.
5567 
5568   DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5569                                        D));
5570 }
5571 
5572 void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
5573                                                const FunctionDecl *D) {
5574   // The specializations set is kept in the canonical template.
5575   assert(!WritingAST && "Already writing the AST!");
5576   TD = TD->getCanonicalDecl();
5577   if (!(!D->isFromASTFile() && TD->isFromASTFile()))
5578     return; // Not a source specialization added to a template from PCH.
5579 
5580   DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
5581                                        D));
5582 }
5583 
5584 void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
5585   assert(!WritingAST && "Already writing the AST!");
5586   FD = FD->getCanonicalDecl();
5587   if (!FD->isFromASTFile())
5588     return; // Not a function declared in PCH and defined outside.
5589 
5590   DeclUpdates[FD].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
5591 }
5592 
5593 void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
5594   assert(!WritingAST && "Already writing the AST!");
5595   FD = FD->getCanonicalDecl();
5596   if (!FD->isFromASTFile())
5597     return; // Not a function declared in PCH and defined outside.
5598 
5599   DeclUpdates[FD].push_back(DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
5600 }
5601 
5602 void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
5603   assert(!WritingAST && "Already writing the AST!");
5604   if (!D->isFromASTFile())
5605     return; // Declaration not imported from PCH.
5606 
5607   // Implicit decl from a PCH was defined.
5608   // FIXME: Should implicit definition be a separate FunctionDecl?
5609   RewriteDecl(D);
5610 }
5611 
5612 void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
5613   assert(!WritingAST && "Already writing the AST!");
5614   if (!D->isFromASTFile())
5615     return;
5616 
5617   // Since the actual instantiation is delayed, this really means that we need
5618   // to update the instantiation location.
5619   DeclUpdates[D].push_back(
5620       DeclUpdate(UPD_CXX_INSTANTIATED_FUNCTION_DEFINITION));
5621 }
5622 
5623 void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
5624   assert(!WritingAST && "Already writing the AST!");
5625   if (!D->isFromASTFile())
5626     return;
5627 
5628   // Since the actual instantiation is delayed, this really means that we need
5629   // to update the instantiation location.
5630   DeclUpdates[D].push_back(
5631       DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
5632        D->getMemberSpecializationInfo()->getPointOfInstantiation()));
5633 }
5634 
5635 void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
5636                                              const ObjCInterfaceDecl *IFD) {
5637   assert(!WritingAST && "Already writing the AST!");
5638   if (!IFD->isFromASTFile())
5639     return; // Declaration not imported from PCH.
5640 
5641   assert(IFD->getDefinition() && "Category on a class without a definition?");
5642   ObjCClassesWithCategories.insert(
5643     const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
5644 }
5645 
5646 
5647 void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
5648                                           const ObjCPropertyDecl *OrigProp,
5649                                           const ObjCCategoryDecl *ClassExt) {
5650   const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
5651   if (!D)
5652     return;
5653 
5654   assert(!WritingAST && "Already writing the AST!");
5655   if (!D->isFromASTFile())
5656     return; // Declaration not imported from PCH.
5657 
5658   RewriteDecl(D);
5659 }
5660 
5661 void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
5662   assert(!WritingAST && "Already writing the AST!");
5663   if (!D->isFromASTFile())
5664     return;
5665 
5666   DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
5667 }
5668