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