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