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