1 //===--- ASTWriterDecl.cpp - Declaration Serialization --------------------===//
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 implements serialization for Declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Serialization/ASTWriter.h"
15 #include "ASTCommon.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/DeclContextInternals.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/Bitcode/BitstreamWriter.h"
23 #include "llvm/Support/ErrorHandling.h"
24 using namespace clang;
25 using namespace serialization;
26 
27 //===----------------------------------------------------------------------===//
28 // Declaration serialization
29 //===----------------------------------------------------------------------===//
30 
31 namespace clang {
32   class ASTDeclWriter : public DeclVisitor<ASTDeclWriter, void> {
33 
34     ASTWriter &Writer;
35     ASTContext &Context;
36     typedef ASTWriter::RecordData RecordData;
37     RecordData &Record;
38 
39   public:
40     serialization::DeclCode Code;
41     unsigned AbbrevToUse;
42 
43     ASTDeclWriter(ASTWriter &Writer, ASTContext &Context, RecordData &Record)
44       : Writer(Writer), Context(Context), Record(Record) {
45     }
46 
47     void Visit(Decl *D);
48 
49     void VisitDecl(Decl *D);
50     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
51     void VisitNamedDecl(NamedDecl *D);
52     void VisitLabelDecl(LabelDecl *LD);
53     void VisitNamespaceDecl(NamespaceDecl *D);
54     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
55     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
56     void VisitTypeDecl(TypeDecl *D);
57     void VisitTypedefDecl(TypedefDecl *D);
58     void VisitTypeAliasDecl(TypeAliasDecl *D);
59     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
60     void VisitTagDecl(TagDecl *D);
61     void VisitEnumDecl(EnumDecl *D);
62     void VisitRecordDecl(RecordDecl *D);
63     void VisitCXXRecordDecl(CXXRecordDecl *D);
64     void VisitClassTemplateSpecializationDecl(
65                                             ClassTemplateSpecializationDecl *D);
66     void VisitClassTemplatePartialSpecializationDecl(
67                                      ClassTemplatePartialSpecializationDecl *D);
68     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
69     void VisitValueDecl(ValueDecl *D);
70     void VisitEnumConstantDecl(EnumConstantDecl *D);
71     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
72     void VisitDeclaratorDecl(DeclaratorDecl *D);
73     void VisitFunctionDecl(FunctionDecl *D);
74     void VisitCXXMethodDecl(CXXMethodDecl *D);
75     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
76     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
77     void VisitCXXConversionDecl(CXXConversionDecl *D);
78     void VisitFieldDecl(FieldDecl *D);
79     void VisitIndirectFieldDecl(IndirectFieldDecl *D);
80     void VisitVarDecl(VarDecl *D);
81     void VisitImplicitParamDecl(ImplicitParamDecl *D);
82     void VisitParmVarDecl(ParmVarDecl *D);
83     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
84     void VisitTemplateDecl(TemplateDecl *D);
85     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
86     void VisitClassTemplateDecl(ClassTemplateDecl *D);
87     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
88     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
89     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
90     void VisitUsingDecl(UsingDecl *D);
91     void VisitUsingShadowDecl(UsingShadowDecl *D);
92     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
93     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
94     void VisitAccessSpecDecl(AccessSpecDecl *D);
95     void VisitFriendDecl(FriendDecl *D);
96     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
97     void VisitStaticAssertDecl(StaticAssertDecl *D);
98     void VisitBlockDecl(BlockDecl *D);
99 
100     void VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
101                           uint64_t VisibleOffset);
102     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
103 
104 
105     // FIXME: Put in the same order is DeclNodes.td?
106     void VisitObjCMethodDecl(ObjCMethodDecl *D);
107     void VisitObjCContainerDecl(ObjCContainerDecl *D);
108     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
109     void VisitObjCIvarDecl(ObjCIvarDecl *D);
110     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
111     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
112     void VisitObjCClassDecl(ObjCClassDecl *D);
113     void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
114     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
115     void VisitObjCImplDecl(ObjCImplDecl *D);
116     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
117     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
118     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
119     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
120     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
121   };
122 }
123 
124 void ASTDeclWriter::Visit(Decl *D) {
125   DeclVisitor<ASTDeclWriter>::Visit(D);
126 
127   // Handle FunctionDecl's body here and write it after all other Stmts/Exprs
128   // have been written. We want it last because we will not read it back when
129   // retrieving it from the AST, we'll just lazily set the offset.
130   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
131     Record.push_back(FD->isThisDeclarationADefinition());
132     if (FD->isThisDeclarationADefinition())
133       Writer.AddStmt(FD->getBody());
134   }
135 }
136 
137 void ASTDeclWriter::VisitDecl(Decl *D) {
138   Writer.AddDeclRef(cast_or_null<Decl>(D->getDeclContext()), Record);
139   Writer.AddDeclRef(cast_or_null<Decl>(D->getLexicalDeclContext()), Record);
140   Writer.AddSourceLocation(D->getLocation(), Record);
141   Record.push_back(D->isInvalidDecl());
142   Record.push_back(D->hasAttrs());
143   if (D->hasAttrs())
144     Writer.WriteAttributes(D->getAttrs(), Record);
145   Record.push_back(D->isImplicit());
146   Record.push_back(D->isUsed(false));
147   Record.push_back(D->isReferenced());
148   Record.push_back(D->getAccess());
149   Record.push_back(D->getPCHLevel());
150 }
151 
152 void ASTDeclWriter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
153   VisitDecl(D);
154   Writer.AddDeclRef(D->getAnonymousNamespace(), Record);
155   Code = serialization::DECL_TRANSLATION_UNIT;
156 }
157 
158 void ASTDeclWriter::VisitNamedDecl(NamedDecl *D) {
159   VisitDecl(D);
160   Writer.AddDeclarationName(D->getDeclName(), Record);
161 }
162 
163 void ASTDeclWriter::VisitTypeDecl(TypeDecl *D) {
164   VisitNamedDecl(D);
165   Writer.AddSourceLocation(D->getLocStart(), Record);
166   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
167 }
168 
169 void ASTDeclWriter::VisitTypedefDecl(TypedefDecl *D) {
170   VisitTypeDecl(D);
171   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
172   Code = serialization::DECL_TYPEDEF;
173 }
174 
175 void ASTDeclWriter::VisitTypeAliasDecl(TypeAliasDecl *D) {
176   VisitTypeDecl(D);
177   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
178   Code = serialization::DECL_TYPEALIAS;
179 }
180 
181 void ASTDeclWriter::VisitTagDecl(TagDecl *D) {
182   VisitTypeDecl(D);
183   VisitRedeclarable(D);
184   Record.push_back(D->getIdentifierNamespace());
185   Record.push_back((unsigned)D->getTagKind()); // FIXME: stable encoding
186   Record.push_back(D->isDefinition());
187   Record.push_back(D->isEmbeddedInDeclarator());
188   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
189   Record.push_back(D->hasExtInfo());
190   if (D->hasExtInfo())
191     Writer.AddQualifierInfo(*D->getExtInfo(), Record);
192   else
193     Writer.AddDeclRef(D->getTypedefNameForAnonDecl(), Record);
194 }
195 
196 void ASTDeclWriter::VisitEnumDecl(EnumDecl *D) {
197   VisitTagDecl(D);
198   Writer.AddTypeSourceInfo(D->getIntegerTypeSourceInfo(), Record);
199   if (!D->getIntegerTypeSourceInfo())
200     Writer.AddTypeRef(D->getIntegerType(), Record);
201   Writer.AddTypeRef(D->getPromotionType(), Record);
202   Record.push_back(D->getNumPositiveBits());
203   Record.push_back(D->getNumNegativeBits());
204   Record.push_back(D->isScoped());
205   Record.push_back(D->isScopedUsingClassTag());
206   Record.push_back(D->isFixed());
207   Writer.AddDeclRef(D->getInstantiatedFromMemberEnum(), Record);
208   Code = serialization::DECL_ENUM;
209 }
210 
211 void ASTDeclWriter::VisitRecordDecl(RecordDecl *D) {
212   VisitTagDecl(D);
213   Record.push_back(D->hasFlexibleArrayMember());
214   Record.push_back(D->isAnonymousStructOrUnion());
215   Record.push_back(D->hasObjectMember());
216   Code = serialization::DECL_RECORD;
217 }
218 
219 void ASTDeclWriter::VisitValueDecl(ValueDecl *D) {
220   VisitNamedDecl(D);
221   Writer.AddTypeRef(D->getType(), Record);
222 }
223 
224 void ASTDeclWriter::VisitEnumConstantDecl(EnumConstantDecl *D) {
225   VisitValueDecl(D);
226   Record.push_back(D->getInitExpr()? 1 : 0);
227   if (D->getInitExpr())
228     Writer.AddStmt(D->getInitExpr());
229   Writer.AddAPSInt(D->getInitVal(), Record);
230   Code = serialization::DECL_ENUM_CONSTANT;
231 }
232 
233 void ASTDeclWriter::VisitDeclaratorDecl(DeclaratorDecl *D) {
234   VisitValueDecl(D);
235   Writer.AddSourceLocation(D->getInnerLocStart(), Record);
236   Record.push_back(D->hasExtInfo());
237   if (D->hasExtInfo())
238     Writer.AddQualifierInfo(*D->getExtInfo(), Record);
239   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
240 }
241 
242 void ASTDeclWriter::VisitFunctionDecl(FunctionDecl *D) {
243   VisitDeclaratorDecl(D);
244   VisitRedeclarable(D);
245 
246   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
247   Record.push_back(D->getIdentifierNamespace());
248   Record.push_back(D->getTemplatedKind());
249   switch (D->getTemplatedKind()) {
250   default: assert(false && "Unhandled TemplatedKind!");
251     break;
252   case FunctionDecl::TK_NonTemplate:
253     break;
254   case FunctionDecl::TK_FunctionTemplate:
255     Writer.AddDeclRef(D->getDescribedFunctionTemplate(), Record);
256     break;
257   case FunctionDecl::TK_MemberSpecialization: {
258     MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo();
259     Writer.AddDeclRef(MemberInfo->getInstantiatedFrom(), Record);
260     Record.push_back(MemberInfo->getTemplateSpecializationKind());
261     Writer.AddSourceLocation(MemberInfo->getPointOfInstantiation(), Record);
262     break;
263   }
264   case FunctionDecl::TK_FunctionTemplateSpecialization: {
265     FunctionTemplateSpecializationInfo *
266       FTSInfo = D->getTemplateSpecializationInfo();
267     Writer.AddDeclRef(FTSInfo->getTemplate(), Record);
268     Record.push_back(FTSInfo->getTemplateSpecializationKind());
269 
270     // Template arguments.
271     Writer.AddTemplateArgumentList(FTSInfo->TemplateArguments, Record);
272 
273     // Template args as written.
274     Record.push_back(FTSInfo->TemplateArgumentsAsWritten != 0);
275     if (FTSInfo->TemplateArgumentsAsWritten) {
276       Record.push_back(FTSInfo->TemplateArgumentsAsWritten->size());
277       for (int i=0, e = FTSInfo->TemplateArgumentsAsWritten->size(); i!=e; ++i)
278         Writer.AddTemplateArgumentLoc((*FTSInfo->TemplateArgumentsAsWritten)[i],
279                                       Record);
280       Writer.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->getLAngleLoc(),
281                                Record);
282       Writer.AddSourceLocation(FTSInfo->TemplateArgumentsAsWritten->getRAngleLoc(),
283                                Record);
284     }
285 
286     Writer.AddSourceLocation(FTSInfo->getPointOfInstantiation(), Record);
287 
288     if (D->isCanonicalDecl()) {
289       // Write the template that contains the specializations set. We will
290       // add a FunctionTemplateSpecializationInfo to it when reading.
291       Writer.AddDeclRef(FTSInfo->getTemplate()->getCanonicalDecl(), Record);
292     }
293     break;
294   }
295   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
296     DependentFunctionTemplateSpecializationInfo *
297       DFTSInfo = D->getDependentSpecializationInfo();
298 
299     // Templates.
300     Record.push_back(DFTSInfo->getNumTemplates());
301     for (int i=0, e = DFTSInfo->getNumTemplates(); i != e; ++i)
302       Writer.AddDeclRef(DFTSInfo->getTemplate(i), Record);
303 
304     // Templates args.
305     Record.push_back(DFTSInfo->getNumTemplateArgs());
306     for (int i=0, e = DFTSInfo->getNumTemplateArgs(); i != e; ++i)
307       Writer.AddTemplateArgumentLoc(DFTSInfo->getTemplateArg(i), Record);
308     Writer.AddSourceLocation(DFTSInfo->getLAngleLoc(), Record);
309     Writer.AddSourceLocation(DFTSInfo->getRAngleLoc(), Record);
310     break;
311   }
312   }
313 
314   // FunctionDecl's body is handled last at ASTWriterDecl::Visit,
315   // after everything else is written.
316 
317   Record.push_back(D->getStorageClass()); // FIXME: stable encoding
318   Record.push_back(D->getStorageClassAsWritten());
319   Record.push_back(D->IsInline);
320   Record.push_back(D->isInlineSpecified());
321   Record.push_back(D->isVirtualAsWritten());
322   Record.push_back(D->isPure());
323   Record.push_back(D->hasInheritedPrototype());
324   Record.push_back(D->hasWrittenPrototype());
325   Record.push_back(D->isDeleted());
326   Record.push_back(D->isTrivial());
327   Record.push_back(D->hasImplicitReturnZero());
328   Writer.AddSourceLocation(D->getLocEnd(), Record);
329 
330   Record.push_back(D->param_size());
331   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
332        P != PEnd; ++P)
333     Writer.AddDeclRef(*P, Record);
334   Code = serialization::DECL_FUNCTION;
335 }
336 
337 void ASTDeclWriter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
338   VisitNamedDecl(D);
339   // FIXME: convert to LazyStmtPtr?
340   // Unlike C/C++, method bodies will never be in header files.
341   bool HasBodyStuff = D->getBody() != 0     ||
342                       D->getSelfDecl() != 0 || D->getCmdDecl() != 0;
343   Record.push_back(HasBodyStuff);
344   if (HasBodyStuff) {
345     Writer.AddStmt(D->getBody());
346     Writer.AddDeclRef(D->getSelfDecl(), Record);
347     Writer.AddDeclRef(D->getCmdDecl(), Record);
348   }
349   Record.push_back(D->isInstanceMethod());
350   Record.push_back(D->isVariadic());
351   Record.push_back(D->isSynthesized());
352   Record.push_back(D->isDefined());
353   // FIXME: stable encoding for @required/@optional
354   Record.push_back(D->getImplementationControl());
355   // FIXME: stable encoding for in/out/inout/bycopy/byref/oneway
356   Record.push_back(D->getObjCDeclQualifier());
357   Record.push_back(D->getNumSelectorArgs());
358   Writer.AddTypeRef(D->getResultType(), Record);
359   Writer.AddTypeSourceInfo(D->getResultTypeSourceInfo(), Record);
360   Writer.AddSourceLocation(D->getLocEnd(), Record);
361   Record.push_back(D->param_size());
362   for (ObjCMethodDecl::param_iterator P = D->param_begin(),
363                                    PEnd = D->param_end(); P != PEnd; ++P)
364     Writer.AddDeclRef(*P, Record);
365   Code = serialization::DECL_OBJC_METHOD;
366 }
367 
368 void ASTDeclWriter::VisitObjCContainerDecl(ObjCContainerDecl *D) {
369   VisitNamedDecl(D);
370   Writer.AddSourceRange(D->getAtEndRange(), Record);
371   // Abstract class (no need to define a stable serialization::DECL code).
372 }
373 
374 void ASTDeclWriter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
375   VisitObjCContainerDecl(D);
376   Writer.AddTypeRef(QualType(D->getTypeForDecl(), 0), Record);
377   Writer.AddDeclRef(D->getSuperClass(), Record);
378 
379   // Write out the protocols that are directly referenced by the @interface.
380   Record.push_back(D->ReferencedProtocols.size());
381   for (ObjCInterfaceDecl::protocol_iterator P = D->protocol_begin(),
382          PEnd = D->protocol_end();
383        P != PEnd; ++P)
384     Writer.AddDeclRef(*P, Record);
385   for (ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(),
386          PLEnd = D->protocol_loc_end();
387        PL != PLEnd; ++PL)
388     Writer.AddSourceLocation(*PL, Record);
389 
390   // Write out the protocols that are transitively referenced.
391   Record.push_back(D->AllReferencedProtocols.size());
392   for (ObjCList<ObjCProtocolDecl>::iterator
393         P = D->AllReferencedProtocols.begin(),
394         PEnd = D->AllReferencedProtocols.end();
395        P != PEnd; ++P)
396     Writer.AddDeclRef(*P, Record);
397 
398   // Write out the ivars.
399   Record.push_back(D->ivar_size());
400   for (ObjCInterfaceDecl::ivar_iterator I = D->ivar_begin(),
401                                      IEnd = D->ivar_end(); I != IEnd; ++I)
402     Writer.AddDeclRef(*I, Record);
403   Writer.AddDeclRef(D->getCategoryList(), Record);
404   Record.push_back(D->isForwardDecl());
405   Record.push_back(D->isImplicitInterfaceDecl());
406   Writer.AddSourceLocation(D->getClassLoc(), Record);
407   Writer.AddSourceLocation(D->getSuperClassLoc(), Record);
408   Writer.AddSourceLocation(D->getLocEnd(), Record);
409   Code = serialization::DECL_OBJC_INTERFACE;
410 }
411 
412 void ASTDeclWriter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
413   VisitFieldDecl(D);
414   // FIXME: stable encoding for @public/@private/@protected/@package
415   Record.push_back(D->getAccessControl());
416   Record.push_back(D->getSynthesize());
417   Code = serialization::DECL_OBJC_IVAR;
418 }
419 
420 void ASTDeclWriter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
421   VisitObjCContainerDecl(D);
422   Record.push_back(D->isForwardDecl());
423   Writer.AddSourceLocation(D->getLocEnd(), Record);
424   Record.push_back(D->protocol_size());
425   for (ObjCProtocolDecl::protocol_iterator
426        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
427     Writer.AddDeclRef(*I, Record);
428   for (ObjCProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(),
429          PLEnd = D->protocol_loc_end();
430        PL != PLEnd; ++PL)
431     Writer.AddSourceLocation(*PL, Record);
432   Code = serialization::DECL_OBJC_PROTOCOL;
433 }
434 
435 void ASTDeclWriter::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
436   VisitFieldDecl(D);
437   Code = serialization::DECL_OBJC_AT_DEFS_FIELD;
438 }
439 
440 void ASTDeclWriter::VisitObjCClassDecl(ObjCClassDecl *D) {
441   VisitDecl(D);
442   Record.push_back(D->size());
443   for (ObjCClassDecl::iterator I = D->begin(), IEnd = D->end(); I != IEnd; ++I)
444     Writer.AddDeclRef(I->getInterface(), Record);
445   for (ObjCClassDecl::iterator I = D->begin(), IEnd = D->end(); I != IEnd; ++I)
446     Writer.AddSourceLocation(I->getLocation(), Record);
447   Code = serialization::DECL_OBJC_CLASS;
448 }
449 
450 void ASTDeclWriter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
451   VisitDecl(D);
452   Record.push_back(D->protocol_size());
453   for (ObjCForwardProtocolDecl::protocol_iterator
454        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
455     Writer.AddDeclRef(*I, Record);
456   for (ObjCForwardProtocolDecl::protocol_loc_iterator
457          PL = D->protocol_loc_begin(), PLEnd = D->protocol_loc_end();
458        PL != PLEnd; ++PL)
459     Writer.AddSourceLocation(*PL, Record);
460   Code = serialization::DECL_OBJC_FORWARD_PROTOCOL;
461 }
462 
463 void ASTDeclWriter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
464   VisitObjCContainerDecl(D);
465   Writer.AddDeclRef(D->getClassInterface(), Record);
466   Record.push_back(D->protocol_size());
467   for (ObjCCategoryDecl::protocol_iterator
468        I = D->protocol_begin(), IEnd = D->protocol_end(); I != IEnd; ++I)
469     Writer.AddDeclRef(*I, Record);
470   for (ObjCCategoryDecl::protocol_loc_iterator
471          PL = D->protocol_loc_begin(), PLEnd = D->protocol_loc_end();
472        PL != PLEnd; ++PL)
473     Writer.AddSourceLocation(*PL, Record);
474   Writer.AddDeclRef(D->getNextClassCategory(), Record);
475   Record.push_back(D->hasSynthBitfield());
476   Writer.AddSourceLocation(D->getAtLoc(), Record);
477   Writer.AddSourceLocation(D->getCategoryNameLoc(), Record);
478   Code = serialization::DECL_OBJC_CATEGORY;
479 }
480 
481 void ASTDeclWriter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D) {
482   VisitNamedDecl(D);
483   Writer.AddDeclRef(D->getClassInterface(), Record);
484   Code = serialization::DECL_OBJC_COMPATIBLE_ALIAS;
485 }
486 
487 void ASTDeclWriter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
488   VisitNamedDecl(D);
489   Writer.AddSourceLocation(D->getAtLoc(), Record);
490   Writer.AddTypeSourceInfo(D->getTypeSourceInfo(), Record);
491   // FIXME: stable encoding
492   Record.push_back((unsigned)D->getPropertyAttributes());
493   Record.push_back((unsigned)D->getPropertyAttributesAsWritten());
494   // FIXME: stable encoding
495   Record.push_back((unsigned)D->getPropertyImplementation());
496   Writer.AddDeclarationName(D->getGetterName(), Record);
497   Writer.AddDeclarationName(D->getSetterName(), Record);
498   Writer.AddDeclRef(D->getGetterMethodDecl(), Record);
499   Writer.AddDeclRef(D->getSetterMethodDecl(), Record);
500   Writer.AddDeclRef(D->getPropertyIvarDecl(), Record);
501   Code = serialization::DECL_OBJC_PROPERTY;
502 }
503 
504 void ASTDeclWriter::VisitObjCImplDecl(ObjCImplDecl *D) {
505   VisitObjCContainerDecl(D);
506   Writer.AddDeclRef(D->getClassInterface(), Record);
507   // Abstract class (no need to define a stable serialization::DECL code).
508 }
509 
510 void ASTDeclWriter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
511   VisitObjCImplDecl(D);
512   Writer.AddIdentifierRef(D->getIdentifier(), Record);
513   Code = serialization::DECL_OBJC_CATEGORY_IMPL;
514 }
515 
516 void ASTDeclWriter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
517   VisitObjCImplDecl(D);
518   Writer.AddDeclRef(D->getSuperClass(), Record);
519   Writer.AddCXXCtorInitializers(D->IvarInitializers, D->NumIvarInitializers,
520                                 Record);
521   Record.push_back(D->hasSynthBitfield());
522   Code = serialization::DECL_OBJC_IMPLEMENTATION;
523 }
524 
525 void ASTDeclWriter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
526   VisitDecl(D);
527   Writer.AddSourceLocation(D->getLocStart(), Record);
528   Writer.AddDeclRef(D->getPropertyDecl(), Record);
529   Writer.AddDeclRef(D->getPropertyIvarDecl(), Record);
530   Writer.AddSourceLocation(D->getPropertyIvarDeclLoc(), Record);
531   Writer.AddStmt(D->getGetterCXXConstructor());
532   Writer.AddStmt(D->getSetterCXXAssignment());
533   Code = serialization::DECL_OBJC_PROPERTY_IMPL;
534 }
535 
536 void ASTDeclWriter::VisitFieldDecl(FieldDecl *D) {
537   VisitDeclaratorDecl(D);
538   Record.push_back(D->isMutable());
539   Record.push_back(D->getBitWidth()? 1 : 0);
540   if (D->getBitWidth())
541     Writer.AddStmt(D->getBitWidth());
542   if (!D->getDeclName())
543     Writer.AddDeclRef(Context.getInstantiatedFromUnnamedFieldDecl(D), Record);
544   Code = serialization::DECL_FIELD;
545 }
546 
547 void ASTDeclWriter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
548   VisitValueDecl(D);
549   Record.push_back(D->getChainingSize());
550 
551   for (IndirectFieldDecl::chain_iterator
552        P = D->chain_begin(),
553        PEnd = D->chain_end(); P != PEnd; ++P)
554     Writer.AddDeclRef(*P, Record);
555   Code = serialization::DECL_INDIRECTFIELD;
556 }
557 
558 void ASTDeclWriter::VisitVarDecl(VarDecl *D) {
559   VisitDeclaratorDecl(D);
560   VisitRedeclarable(D);
561   Record.push_back(D->getStorageClass()); // FIXME: stable encoding
562   Record.push_back(D->getStorageClassAsWritten());
563   Record.push_back(D->isThreadSpecified());
564   Record.push_back(D->hasCXXDirectInitializer());
565   Record.push_back(D->isExceptionVariable());
566   Record.push_back(D->isNRVOVariable());
567   Record.push_back(D->isCXXForRangeDecl());
568   Record.push_back(D->getInit() ? 1 : 0);
569   if (D->getInit())
570     Writer.AddStmt(D->getInit());
571 
572   MemberSpecializationInfo *SpecInfo
573     = D->isStaticDataMember() ? D->getMemberSpecializationInfo() : 0;
574   Record.push_back(SpecInfo != 0);
575   if (SpecInfo) {
576     Writer.AddDeclRef(SpecInfo->getInstantiatedFrom(), Record);
577     Record.push_back(SpecInfo->getTemplateSpecializationKind());
578     Writer.AddSourceLocation(SpecInfo->getPointOfInstantiation(), Record);
579   }
580 
581   Code = serialization::DECL_VAR;
582 }
583 
584 void ASTDeclWriter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
585   VisitVarDecl(D);
586   Code = serialization::DECL_IMPLICIT_PARAM;
587 }
588 
589 void ASTDeclWriter::VisitParmVarDecl(ParmVarDecl *D) {
590   VisitVarDecl(D);
591   Record.push_back(D->isObjCMethodParameter());
592   Record.push_back(D->getFunctionScopeDepth());
593   Record.push_back(D->getFunctionScopeIndex());
594   Record.push_back(D->getObjCDeclQualifier()); // FIXME: stable encoding
595   Record.push_back(D->isKNRPromoted());
596   Record.push_back(D->hasInheritedDefaultArg());
597   Record.push_back(D->hasUninstantiatedDefaultArg());
598   if (D->hasUninstantiatedDefaultArg())
599     Writer.AddStmt(D->getUninstantiatedDefaultArg());
600   Code = serialization::DECL_PARM_VAR;
601 
602   // If the assumptions about the DECL_PARM_VAR abbrev are true, use it.  Here
603   // we dynamically check for the properties that we optimize for, but don't
604   // know are true of all PARM_VAR_DECLs.
605   if (!D->getTypeSourceInfo() &&
606       !D->hasAttrs() &&
607       !D->isImplicit() &&
608       !D->isUsed(false) &&
609       D->getAccess() == AS_none &&
610       D->getPCHLevel() == 0 &&
611       D->getStorageClass() == 0 &&
612       !D->hasCXXDirectInitializer() && // Can params have this ever?
613       D->getFunctionScopeDepth() == 0 &&
614       D->getObjCDeclQualifier() == 0 &&
615       !D->isKNRPromoted() &&
616       !D->hasInheritedDefaultArg() &&
617       D->getInit() == 0 &&
618       !D->hasUninstantiatedDefaultArg())  // No default expr.
619     AbbrevToUse = Writer.getParmVarDeclAbbrev();
620 
621   // Check things we know are true of *every* PARM_VAR_DECL, which is more than
622   // just us assuming it.
623   assert(!D->isInvalidDecl() && "Shouldn't emit invalid decls");
624   assert(!D->isThreadSpecified() && "PARM_VAR_DECL can't be __thread");
625   assert(D->getAccess() == AS_none && "PARM_VAR_DECL can't be public/private");
626   assert(!D->isExceptionVariable() && "PARM_VAR_DECL can't be exception var");
627   assert(D->getPreviousDeclaration() == 0 && "PARM_VAR_DECL can't be redecl");
628   assert(!D->isStaticDataMember() &&
629          "PARM_VAR_DECL can't be static data member");
630 }
631 
632 void ASTDeclWriter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
633   VisitDecl(D);
634   Writer.AddStmt(D->getAsmString());
635   Writer.AddSourceLocation(D->getRParenLoc(), Record);
636   Code = serialization::DECL_FILE_SCOPE_ASM;
637 }
638 
639 void ASTDeclWriter::VisitBlockDecl(BlockDecl *D) {
640   VisitDecl(D);
641   Writer.AddStmt(D->getBody());
642   Writer.AddTypeSourceInfo(D->getSignatureAsWritten(), Record);
643   Record.push_back(D->param_size());
644   for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
645        P != PEnd; ++P)
646     Writer.AddDeclRef(*P, Record);
647   Record.push_back(D->capturesCXXThis());
648   Record.push_back(D->getNumCaptures());
649   for (BlockDecl::capture_iterator
650          i = D->capture_begin(), e = D->capture_end(); i != e; ++i) {
651     const BlockDecl::Capture &capture = *i;
652     Writer.AddDeclRef(capture.getVariable(), Record);
653 
654     unsigned flags = 0;
655     if (capture.isByRef()) flags |= 1;
656     if (capture.isNested()) flags |= 2;
657     if (capture.hasCopyExpr()) flags |= 4;
658     Record.push_back(flags);
659 
660     if (capture.hasCopyExpr()) Writer.AddStmt(capture.getCopyExpr());
661   }
662 
663   Code = serialization::DECL_BLOCK;
664 }
665 
666 void ASTDeclWriter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
667   VisitDecl(D);
668   Record.push_back(D->getLanguage());
669   Writer.AddSourceLocation(D->getExternLoc(), Record);
670   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
671   Code = serialization::DECL_LINKAGE_SPEC;
672 }
673 
674 void ASTDeclWriter::VisitLabelDecl(LabelDecl *D) {
675   VisitNamedDecl(D);
676   Writer.AddSourceLocation(D->getLocStart(), Record);
677   Code = serialization::DECL_LABEL;
678 }
679 
680 
681 void ASTDeclWriter::VisitNamespaceDecl(NamespaceDecl *D) {
682   VisitNamedDecl(D);
683   Record.push_back(D->isInline());
684   Writer.AddSourceLocation(D->getLocStart(), Record);
685   Writer.AddSourceLocation(D->getRBraceLoc(), Record);
686   Writer.AddDeclRef(D->getNextNamespace(), Record);
687 
688   // Only write one reference--original or anonymous
689   Record.push_back(D->isOriginalNamespace());
690   if (D->isOriginalNamespace())
691     Writer.AddDeclRef(D->getAnonymousNamespace(), Record);
692   else
693     Writer.AddDeclRef(D->getOriginalNamespace(), Record);
694   Code = serialization::DECL_NAMESPACE;
695 
696   if (Writer.hasChain() && !D->isOriginalNamespace() &&
697       D->getOriginalNamespace()->getPCHLevel() > 0) {
698     NamespaceDecl *NS = D->getOriginalNamespace();
699     Writer.AddUpdatedDeclContext(NS);
700 
701     // Make sure all visible decls are written. They will be recorded later.
702     NS->lookup(DeclarationName());
703     StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(NS->getLookupPtr());
704     if (Map) {
705       for (StoredDeclsMap::iterator D = Map->begin(), DEnd = Map->end();
706            D != DEnd; ++D) {
707         DeclContext::lookup_result Result = D->second.getLookupResult();
708         while (Result.first != Result.second) {
709           Writer.GetDeclRef(*Result.first);
710           ++Result.first;
711         }
712       }
713     }
714   }
715 
716   if (Writer.hasChain() && D->isAnonymousNamespace() && !D->getNextNamespace()){
717     // This is a most recent reopening of the anonymous namespace. If its parent
718     // is in a previous PCH (or is the TU), mark that parent for update, because
719     // the original namespace always points to the latest re-opening of its
720     // anonymous namespace.
721     Decl *Parent = cast<Decl>(
722         D->getParent()->getRedeclContext()->getPrimaryContext());
723     if (Parent->getPCHLevel() > 0) {
724       ASTWriter::UpdateRecord &Record = Writer.DeclUpdates[Parent];
725       Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);
726       Writer.AddDeclRef(D, Record);
727     }
728   }
729 }
730 
731 void ASTDeclWriter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
732   VisitNamedDecl(D);
733   Writer.AddSourceLocation(D->getNamespaceLoc(), Record);
734   Writer.AddSourceLocation(D->getTargetNameLoc(), Record);
735   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
736   Writer.AddDeclRef(D->getNamespace(), Record);
737   Code = serialization::DECL_NAMESPACE_ALIAS;
738 }
739 
740 void ASTDeclWriter::VisitUsingDecl(UsingDecl *D) {
741   VisitNamedDecl(D);
742   Writer.AddSourceLocation(D->getUsingLocation(), Record);
743   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
744   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
745   Writer.AddDeclRef(D->FirstUsingShadow, Record);
746   Record.push_back(D->isTypeName());
747   Writer.AddDeclRef(Context.getInstantiatedFromUsingDecl(D), Record);
748   Code = serialization::DECL_USING;
749 }
750 
751 void ASTDeclWriter::VisitUsingShadowDecl(UsingShadowDecl *D) {
752   VisitNamedDecl(D);
753   Writer.AddDeclRef(D->getTargetDecl(), Record);
754   Writer.AddDeclRef(D->UsingOrNextShadow, Record);
755   Writer.AddDeclRef(Context.getInstantiatedFromUsingShadowDecl(D), Record);
756   Code = serialization::DECL_USING_SHADOW;
757 }
758 
759 void ASTDeclWriter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
760   VisitNamedDecl(D);
761   Writer.AddSourceLocation(D->getUsingLoc(), Record);
762   Writer.AddSourceLocation(D->getNamespaceKeyLocation(), Record);
763   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
764   Writer.AddDeclRef(D->getNominatedNamespace(), Record);
765   Writer.AddDeclRef(dyn_cast<Decl>(D->getCommonAncestor()), Record);
766   Code = serialization::DECL_USING_DIRECTIVE;
767 }
768 
769 void ASTDeclWriter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
770   VisitValueDecl(D);
771   Writer.AddSourceLocation(D->getUsingLoc(), Record);
772   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
773   Writer.AddDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record);
774   Code = serialization::DECL_UNRESOLVED_USING_VALUE;
775 }
776 
777 void ASTDeclWriter::VisitUnresolvedUsingTypenameDecl(
778                                                UnresolvedUsingTypenameDecl *D) {
779   VisitTypeDecl(D);
780   Writer.AddSourceLocation(D->getTypenameLoc(), Record);
781   Writer.AddNestedNameSpecifierLoc(D->getQualifierLoc(), Record);
782   Code = serialization::DECL_UNRESOLVED_USING_TYPENAME;
783 }
784 
785 void ASTDeclWriter::VisitCXXRecordDecl(CXXRecordDecl *D) {
786   VisitRecordDecl(D);
787 
788   CXXRecordDecl *DefinitionDecl = 0;
789   if (D->DefinitionData)
790     DefinitionDecl = D->DefinitionData->Definition;
791   Writer.AddDeclRef(DefinitionDecl, Record);
792   if (D == DefinitionDecl)
793     Writer.AddCXXDefinitionData(D, Record);
794 
795   enum {
796     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
797   };
798   if (ClassTemplateDecl *TemplD = D->getDescribedClassTemplate()) {
799     Record.push_back(CXXRecTemplate);
800     Writer.AddDeclRef(TemplD, Record);
801   } else if (MemberSpecializationInfo *MSInfo
802                = D->getMemberSpecializationInfo()) {
803     Record.push_back(CXXRecMemberSpecialization);
804     Writer.AddDeclRef(MSInfo->getInstantiatedFrom(), Record);
805     Record.push_back(MSInfo->getTemplateSpecializationKind());
806     Writer.AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
807   } else {
808     Record.push_back(CXXRecNotTemplate);
809   }
810 
811   // Store the key function to avoid deserializing every method so we can
812   // compute it.
813   if (D->IsDefinition)
814     Writer.AddDeclRef(Context.getKeyFunction(D), Record);
815 
816   Code = serialization::DECL_CXX_RECORD;
817 }
818 
819 void ASTDeclWriter::VisitCXXMethodDecl(CXXMethodDecl *D) {
820   VisitFunctionDecl(D);
821   Record.push_back(D->size_overridden_methods());
822   for (CXXMethodDecl::method_iterator
823          I = D->begin_overridden_methods(), E = D->end_overridden_methods();
824          I != E; ++I)
825     Writer.AddDeclRef(*I, Record);
826   Code = serialization::DECL_CXX_METHOD;
827 }
828 
829 void ASTDeclWriter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
830   VisitCXXMethodDecl(D);
831 
832   Record.push_back(D->IsExplicitSpecified);
833   Record.push_back(D->ImplicitlyDefined);
834   Writer.AddCXXCtorInitializers(D->CtorInitializers, D->NumCtorInitializers,
835                                 Record);
836 
837   Code = serialization::DECL_CXX_CONSTRUCTOR;
838 }
839 
840 void ASTDeclWriter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
841   VisitCXXMethodDecl(D);
842 
843   Record.push_back(D->ImplicitlyDefined);
844   Writer.AddDeclRef(D->OperatorDelete, Record);
845 
846   Code = serialization::DECL_CXX_DESTRUCTOR;
847 }
848 
849 void ASTDeclWriter::VisitCXXConversionDecl(CXXConversionDecl *D) {
850   VisitCXXMethodDecl(D);
851   Record.push_back(D->IsExplicitSpecified);
852   Code = serialization::DECL_CXX_CONVERSION;
853 }
854 
855 void ASTDeclWriter::VisitAccessSpecDecl(AccessSpecDecl *D) {
856   VisitDecl(D);
857   Writer.AddSourceLocation(D->getColonLoc(), Record);
858   Code = serialization::DECL_ACCESS_SPEC;
859 }
860 
861 void ASTDeclWriter::VisitFriendDecl(FriendDecl *D) {
862   VisitDecl(D);
863   Record.push_back(D->Friend.is<TypeSourceInfo*>());
864   if (D->Friend.is<TypeSourceInfo*>())
865     Writer.AddTypeSourceInfo(D->Friend.get<TypeSourceInfo*>(), Record);
866   else
867     Writer.AddDeclRef(D->Friend.get<NamedDecl*>(), Record);
868   Writer.AddDeclRef(D->getNextFriend(), Record);
869   Record.push_back(D->UnsupportedFriend);
870   Writer.AddSourceLocation(D->FriendLoc, Record);
871   Code = serialization::DECL_FRIEND;
872 }
873 
874 void ASTDeclWriter::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
875   VisitDecl(D);
876   Record.push_back(D->getNumTemplateParameters());
877   for (unsigned i = 0, e = D->getNumTemplateParameters(); i != e; ++i)
878     Writer.AddTemplateParameterList(D->getTemplateParameterList(i), Record);
879   Record.push_back(D->getFriendDecl() != 0);
880   if (D->getFriendDecl())
881     Writer.AddDeclRef(D->getFriendDecl(), Record);
882   else
883     Writer.AddTypeSourceInfo(D->getFriendType(), Record);
884   Writer.AddSourceLocation(D->getFriendLoc(), Record);
885   Code = serialization::DECL_FRIEND_TEMPLATE;
886 }
887 
888 void ASTDeclWriter::VisitTemplateDecl(TemplateDecl *D) {
889   VisitNamedDecl(D);
890 
891   Writer.AddDeclRef(D->getTemplatedDecl(), Record);
892   Writer.AddTemplateParameterList(D->getTemplateParameters(), Record);
893 }
894 
895 void ASTDeclWriter::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
896   // Emit data to initialize CommonOrPrev before VisitTemplateDecl so that
897   // getCommonPtr() can be used while this is still initializing.
898 
899   Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
900   if (D->getPreviousDeclaration())
901     Writer.AddDeclRef(D->getFirstDeclaration(), Record);
902 
903   if (D->getPreviousDeclaration() == 0) {
904     // This TemplateDecl owns the CommonPtr; write it.
905     assert(D->isCanonicalDecl());
906 
907     Writer.AddDeclRef(D->getInstantiatedFromMemberTemplate(), Record);
908     if (D->getInstantiatedFromMemberTemplate())
909       Record.push_back(D->isMemberSpecialization());
910 
911     Writer.AddDeclRef(D->getCommonPtr()->Latest, Record);
912   } else {
913     RedeclarableTemplateDecl *First = D->getFirstDeclaration();
914     assert(First != D);
915     // If this is a most recent redeclaration that is pointed to by a first decl
916     // in a chained PCH, keep track of the association with the map so we can
917     // update the first decl during AST reading.
918     if (First->getMostRecentDeclaration() == D &&
919         First->getPCHLevel() > D->getPCHLevel()) {
920       assert(Writer.FirstLatestDecls.find(First)==Writer.FirstLatestDecls.end()
921              && "The latest is already set");
922       Writer.FirstLatestDecls[First] = D;
923     }
924   }
925 
926   VisitTemplateDecl(D);
927   Record.push_back(D->getIdentifierNamespace());
928 }
929 
930 void ASTDeclWriter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
931   VisitRedeclarableTemplateDecl(D);
932 
933   if (D->getPreviousDeclaration() == 0) {
934     typedef llvm::FoldingSet<ClassTemplateSpecializationDecl> CTSDSetTy;
935     CTSDSetTy &CTSDSet = D->getSpecializations();
936     Record.push_back(CTSDSet.size());
937     for (CTSDSetTy::iterator I=CTSDSet.begin(), E = CTSDSet.end(); I!=E; ++I) {
938       assert(I->isCanonicalDecl() && "Expected only canonical decls in set");
939       Writer.AddDeclRef(&*I, Record);
940     }
941 
942     typedef llvm::FoldingSet<ClassTemplatePartialSpecializationDecl> CTPSDSetTy;
943     CTPSDSetTy &CTPSDSet = D->getPartialSpecializations();
944     Record.push_back(CTPSDSet.size());
945     for (CTPSDSetTy::iterator I=CTPSDSet.begin(), E=CTPSDSet.end(); I!=E; ++I) {
946       assert(I->isCanonicalDecl() && "Expected only canonical decls in set");
947       Writer.AddDeclRef(&*I, Record);
948     }
949 
950     // InjectedClassNameType is computed, no need to write it.
951   }
952   Code = serialization::DECL_CLASS_TEMPLATE;
953 }
954 
955 void ASTDeclWriter::VisitClassTemplateSpecializationDecl(
956                                            ClassTemplateSpecializationDecl *D) {
957   VisitCXXRecordDecl(D);
958 
959   llvm::PointerUnion<ClassTemplateDecl *,
960                      ClassTemplatePartialSpecializationDecl *> InstFrom
961     = D->getSpecializedTemplateOrPartial();
962   Decl *InstFromD;
963   if (InstFrom.is<ClassTemplateDecl *>()) {
964     InstFromD = InstFrom.get<ClassTemplateDecl *>();
965     Writer.AddDeclRef(InstFromD, Record);
966   } else {
967     InstFromD = InstFrom.get<ClassTemplatePartialSpecializationDecl *>();
968     Writer.AddDeclRef(InstFromD, Record);
969     Writer.AddTemplateArgumentList(&D->getTemplateInstantiationArgs(), Record);
970     InstFromD = cast<ClassTemplatePartialSpecializationDecl>(InstFromD)->
971                     getSpecializedTemplate();
972   }
973 
974   // Explicit info.
975   Writer.AddTypeSourceInfo(D->getTypeAsWritten(), Record);
976   if (D->getTypeAsWritten()) {
977     Writer.AddSourceLocation(D->getExternLoc(), Record);
978     Writer.AddSourceLocation(D->getTemplateKeywordLoc(), Record);
979   }
980 
981   Writer.AddTemplateArgumentList(&D->getTemplateArgs(), Record);
982   Writer.AddSourceLocation(D->getPointOfInstantiation(), Record);
983   Record.push_back(D->getSpecializationKind());
984 
985   if (D->isCanonicalDecl()) {
986     // When reading, we'll add it to the folding set of the following template.
987     Writer.AddDeclRef(D->getSpecializedTemplate()->getCanonicalDecl(), Record);
988   }
989 
990   Code = serialization::DECL_CLASS_TEMPLATE_SPECIALIZATION;
991 }
992 
993 void ASTDeclWriter::VisitClassTemplatePartialSpecializationDecl(
994                                     ClassTemplatePartialSpecializationDecl *D) {
995   VisitClassTemplateSpecializationDecl(D);
996 
997   Writer.AddTemplateParameterList(D->getTemplateParameters(), Record);
998 
999   Record.push_back(D->getNumTemplateArgsAsWritten());
1000   for (int i = 0, e = D->getNumTemplateArgsAsWritten(); i != e; ++i)
1001     Writer.AddTemplateArgumentLoc(D->getTemplateArgsAsWritten()[i], Record);
1002 
1003   Record.push_back(D->getSequenceNumber());
1004 
1005   // These are read/set from/to the first declaration.
1006   if (D->getPreviousDeclaration() == 0) {
1007     Writer.AddDeclRef(D->getInstantiatedFromMember(), Record);
1008     Record.push_back(D->isMemberSpecialization());
1009   }
1010 
1011   Code = serialization::DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION;
1012 }
1013 
1014 void ASTDeclWriter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1015   VisitRedeclarableTemplateDecl(D);
1016 
1017   if (D->getPreviousDeclaration() == 0) {
1018     // This FunctionTemplateDecl owns the CommonPtr; write it.
1019 
1020     // Write the function specialization declarations.
1021     Record.push_back(D->getSpecializations().size());
1022     for (llvm::FoldingSet<FunctionTemplateSpecializationInfo>::iterator
1023            I = D->getSpecializations().begin(),
1024            E = D->getSpecializations().end()   ; I != E; ++I) {
1025       assert(I->Function->isCanonicalDecl() &&
1026              "Expected only canonical decls in set");
1027       Writer.AddDeclRef(I->Function, Record);
1028     }
1029   }
1030   Code = serialization::DECL_FUNCTION_TEMPLATE;
1031 }
1032 
1033 void ASTDeclWriter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1034   VisitTypeDecl(D);
1035 
1036   Record.push_back(D->wasDeclaredWithTypename());
1037   Record.push_back(D->defaultArgumentWasInherited());
1038   Writer.AddTypeSourceInfo(D->getDefaultArgumentInfo(), Record);
1039 
1040   Code = serialization::DECL_TEMPLATE_TYPE_PARM;
1041 }
1042 
1043 void ASTDeclWriter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1044   // For an expanded parameter pack, record the number of expansion types here
1045   // so that it's easier for
1046   if (D->isExpandedParameterPack())
1047     Record.push_back(D->getNumExpansionTypes());
1048 
1049   VisitDeclaratorDecl(D);
1050   // TemplateParmPosition.
1051   Record.push_back(D->getDepth());
1052   Record.push_back(D->getPosition());
1053 
1054   if (D->isExpandedParameterPack()) {
1055     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1056       Writer.AddTypeRef(D->getExpansionType(I), Record);
1057       Writer.AddTypeSourceInfo(D->getExpansionTypeSourceInfo(I), Record);
1058     }
1059 
1060     Code = serialization::DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK;
1061   } else {
1062     // Rest of NonTypeTemplateParmDecl.
1063     Record.push_back(D->isParameterPack());
1064     Record.push_back(D->getDefaultArgument() != 0);
1065     if (D->getDefaultArgument()) {
1066       Writer.AddStmt(D->getDefaultArgument());
1067       Record.push_back(D->defaultArgumentWasInherited());
1068     }
1069     Code = serialization::DECL_NON_TYPE_TEMPLATE_PARM;
1070   }
1071 }
1072 
1073 void ASTDeclWriter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1074   VisitTemplateDecl(D);
1075   // TemplateParmPosition.
1076   Record.push_back(D->getDepth());
1077   Record.push_back(D->getPosition());
1078   // Rest of TemplateTemplateParmDecl.
1079   Writer.AddTemplateArgumentLoc(D->getDefaultArgument(), Record);
1080   Record.push_back(D->defaultArgumentWasInherited());
1081   Record.push_back(D->isParameterPack());
1082   Code = serialization::DECL_TEMPLATE_TEMPLATE_PARM;
1083 }
1084 
1085 void ASTDeclWriter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1086   VisitRedeclarableTemplateDecl(D);
1087   Code = serialization::DECL_TYPE_ALIAS_TEMPLATE;
1088 }
1089 
1090 void ASTDeclWriter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1091   VisitDecl(D);
1092   Writer.AddStmt(D->getAssertExpr());
1093   Writer.AddStmt(D->getMessage());
1094   Writer.AddSourceLocation(D->getRParenLoc(), Record);
1095   Code = serialization::DECL_STATIC_ASSERT;
1096 }
1097 
1098 /// \brief Emit the DeclContext part of a declaration context decl.
1099 ///
1100 /// \param LexicalOffset the offset at which the DECL_CONTEXT_LEXICAL
1101 /// block for this declaration context is stored. May be 0 to indicate
1102 /// that there are no declarations stored within this context.
1103 ///
1104 /// \param VisibleOffset the offset at which the DECL_CONTEXT_VISIBLE
1105 /// block for this declaration context is stored. May be 0 to indicate
1106 /// that there are no declarations visible from this context. Note
1107 /// that this value will not be emitted for non-primary declaration
1108 /// contexts.
1109 void ASTDeclWriter::VisitDeclContext(DeclContext *DC, uint64_t LexicalOffset,
1110                                      uint64_t VisibleOffset) {
1111   Record.push_back(LexicalOffset);
1112   Record.push_back(VisibleOffset);
1113 }
1114 
1115 template <typename T>
1116 void ASTDeclWriter::VisitRedeclarable(Redeclarable<T> *D) {
1117   enum { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
1118   if (D->RedeclLink.getNext() == D) {
1119     Record.push_back(NoRedeclaration);
1120   } else {
1121     if (D->RedeclLink.NextIsPrevious()) {
1122       Record.push_back(PointsToPrevious);
1123       Writer.AddDeclRef(D->getPreviousDeclaration(), Record);
1124       Writer.AddDeclRef(D->getFirstDeclaration(), Record);
1125     } else {
1126       Record.push_back(PointsToLatest);
1127       Writer.AddDeclRef(D->RedeclLink.getPointer(), Record);
1128     }
1129   }
1130 
1131   T *First = D->getFirstDeclaration();
1132   T *ThisDecl = static_cast<T*>(D);
1133   // If this is a most recent redeclaration that is pointed to by a first decl
1134   // in a chained PCH, keep track of the association with the map so we can
1135   // update the first decl during AST reading.
1136   if (ThisDecl != First && First->getMostRecentDeclaration() == ThisDecl &&
1137       First->getPCHLevel() > ThisDecl->getPCHLevel()) {
1138     assert(Writer.FirstLatestDecls.find(First) == Writer.FirstLatestDecls.end()
1139            && "The latest is already set");
1140     Writer.FirstLatestDecls[First] = ThisDecl;
1141   }
1142 }
1143 
1144 //===----------------------------------------------------------------------===//
1145 // ASTWriter Implementation
1146 //===----------------------------------------------------------------------===//
1147 
1148 void ASTWriter::WriteDeclsBlockAbbrevs() {
1149   using namespace llvm;
1150   // Abbreviation for DECL_PARM_VAR.
1151   BitCodeAbbrev *Abv = new BitCodeAbbrev();
1152   Abv->Add(BitCodeAbbrevOp(serialization::DECL_PARM_VAR));
1153 
1154   // Decl
1155   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // DeclContext
1156   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LexicalDeclContext
1157   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Location
1158   Abv->Add(BitCodeAbbrevOp(0));                       // isInvalidDecl (!?)
1159   Abv->Add(BitCodeAbbrevOp(0));                       // HasAttrs
1160   Abv->Add(BitCodeAbbrevOp(0));                       // isImplicit
1161   Abv->Add(BitCodeAbbrevOp(0));                       // isUsed
1162   Abv->Add(BitCodeAbbrevOp(0));                       // isReferenced
1163   Abv->Add(BitCodeAbbrevOp(AS_none));                 // C++ AccessSpecifier
1164   Abv->Add(BitCodeAbbrevOp(0));                       // PCH level
1165 
1166   // NamedDecl
1167   Abv->Add(BitCodeAbbrevOp(0));                       // NameKind = Identifier
1168   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Name
1169   // ValueDecl
1170   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
1171   // DeclaratorDecl
1172   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // InnerStartLoc
1173   Abv->Add(BitCodeAbbrevOp(0));                       // hasExtInfo
1174   Abv->Add(BitCodeAbbrevOp(serialization::PREDEF_TYPE_NULL_ID)); // InfoType
1175   // VarDecl
1176   Abv->Add(BitCodeAbbrevOp(0));                       // No redeclaration
1177   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClass
1178   Abv->Add(BitCodeAbbrevOp(0));                       // StorageClassAsWritten
1179   Abv->Add(BitCodeAbbrevOp(0));                       // isThreadSpecified
1180   Abv->Add(BitCodeAbbrevOp(0));                       // hasCXXDirectInitializer
1181   Abv->Add(BitCodeAbbrevOp(0));                       // isExceptionVariable
1182   Abv->Add(BitCodeAbbrevOp(0));                       // isNRVOVariable
1183   Abv->Add(BitCodeAbbrevOp(0));                       // isCXXForRangeDecl
1184   Abv->Add(BitCodeAbbrevOp(0));                       // HasInit
1185   Abv->Add(BitCodeAbbrevOp(0));                   // HasMemberSpecializationInfo
1186   // ParmVarDecl
1187   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsObjCMethodParameter
1188   Abv->Add(BitCodeAbbrevOp(0));                       // ScopeDepth
1189   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ScopeIndex
1190   Abv->Add(BitCodeAbbrevOp(0));                       // ObjCDeclQualifier
1191   Abv->Add(BitCodeAbbrevOp(0));                       // KNRPromoted
1192   Abv->Add(BitCodeAbbrevOp(0));                       // HasInheritedDefaultArg
1193   Abv->Add(BitCodeAbbrevOp(0));                   // HasUninstantiatedDefaultArg
1194 
1195   ParmVarDeclAbbrev = Stream.EmitAbbrev(Abv);
1196 
1197   Abv = new BitCodeAbbrev();
1198   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_LEXICAL));
1199   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1200   DeclContextLexicalAbbrev = Stream.EmitAbbrev(Abv);
1201 
1202   Abv = new BitCodeAbbrev();
1203   Abv->Add(BitCodeAbbrevOp(serialization::DECL_CONTEXT_VISIBLE));
1204   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1205   Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
1206   DeclContextVisibleLookupAbbrev = Stream.EmitAbbrev(Abv);
1207 }
1208 
1209 /// isRequiredDecl - Check if this is a "required" Decl, which must be seen by
1210 /// consumers of the AST.
1211 ///
1212 /// Such decls will always be deserialized from the AST file, so we would like
1213 /// this to be as restrictive as possible. Currently the predicate is driven by
1214 /// code generation requirements, if other clients have a different notion of
1215 /// what is "required" then we may have to consider an alternate scheme where
1216 /// clients can iterate over the top-level decls and get information on them,
1217 /// without necessary deserializing them. We could explicitly require such
1218 /// clients to use a separate API call to "realize" the decl. This should be
1219 /// relatively painless since they would presumably only do it for top-level
1220 /// decls.
1221 static bool isRequiredDecl(const Decl *D, ASTContext &Context) {
1222   // File scoped assembly or obj-c implementation must be seen.
1223   if (isa<FileScopeAsmDecl>(D) || isa<ObjCImplementationDecl>(D))
1224     return true;
1225 
1226   return Context.DeclMustBeEmitted(D);
1227 }
1228 
1229 void ASTWriter::WriteDecl(ASTContext &Context, Decl *D) {
1230   // Switch case IDs are per Decl.
1231   ClearSwitchCaseIDs();
1232 
1233   RecordData Record;
1234   ASTDeclWriter W(*this, Context, Record);
1235 
1236   // If this declaration is also a DeclContext, write blocks for the
1237   // declarations that lexically stored inside its context and those
1238   // declarations that are visible from its context. These blocks
1239   // are written before the declaration itself so that we can put
1240   // their offsets into the record for the declaration.
1241   uint64_t LexicalOffset = 0;
1242   uint64_t VisibleOffset = 0;
1243   DeclContext *DC = dyn_cast<DeclContext>(D);
1244   if (DC) {
1245     LexicalOffset = WriteDeclContextLexicalBlock(Context, DC);
1246     VisibleOffset = WriteDeclContextVisibleBlock(Context, DC);
1247   }
1248 
1249   // Determine the ID for this declaration
1250   serialization::DeclID &IDR = DeclIDs[D];
1251   if (IDR == 0)
1252     IDR = NextDeclID++;
1253   serialization::DeclID ID = IDR;
1254 
1255   if (ID < FirstDeclID) {
1256     // We're replacing a decl in a previous file.
1257     ReplacedDecls.push_back(std::make_pair(ID, Stream.GetCurrentBitNo()));
1258   } else {
1259     unsigned Index = ID - FirstDeclID;
1260 
1261     // Record the offset for this declaration
1262     if (DeclOffsets.size() == Index)
1263       DeclOffsets.push_back(Stream.GetCurrentBitNo());
1264     else if (DeclOffsets.size() < Index) {
1265       DeclOffsets.resize(Index+1);
1266       DeclOffsets[Index] = Stream.GetCurrentBitNo();
1267     }
1268   }
1269 
1270   // Build and emit a record for this declaration
1271   Record.clear();
1272   W.Code = (serialization::DeclCode)0;
1273   W.AbbrevToUse = 0;
1274   W.Visit(D);
1275   if (DC) W.VisitDeclContext(DC, LexicalOffset, VisibleOffset);
1276 
1277   if (!W.Code)
1278     llvm::report_fatal_error(llvm::StringRef("unexpected declaration kind '") +
1279                             D->getDeclKindName() + "'");
1280   Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
1281 
1282   // Flush any expressions that were written as part of this declaration.
1283   FlushStmts();
1284 
1285   // Flush C++ base specifiers, if there are any.
1286   FlushCXXBaseSpecifiers();
1287 
1288   // Note "external" declarations so that we can add them to a record in the
1289   // AST file later.
1290   //
1291   // FIXME: This should be renamed, the predicate is much more complicated.
1292   if (isRequiredDecl(D, Context))
1293     ExternalDefinitions.push_back(ID);
1294 }
1295