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