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