1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
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 the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ASTCommon.h"
16 #include "clang/Serialization/ASTReader.h"
17 #include "clang/Sema/IdentifierResolver.h"
18 #include "clang/Sema/Sema.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "clang/AST/ASTConsumer.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclVisitor.h"
23 #include "clang/AST/DeclGroup.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 using namespace clang;
28 using namespace clang::serialization;
29 
30 //===----------------------------------------------------------------------===//
31 // Declaration deserialization
32 //===----------------------------------------------------------------------===//
33 
34 namespace clang {
35   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
36     ASTReader &Reader;
37     ModuleFile &F;
38     llvm::BitstreamCursor &Cursor;
39     const DeclID ThisDeclID;
40     const unsigned RawLocation;
41     typedef ASTReader::RecordData RecordData;
42     const RecordData &Record;
43     unsigned &Idx;
44     TypeID TypeIDForTypeDecl;
45 
46     DeclID DeclContextIDForTemplateParmDecl;
47     DeclID LexicalDeclContextIDForTemplateParmDecl;
48 
49     uint64_t GetCurrentCursorOffset();
50 
51     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
52       return Reader.ReadSourceLocation(F, R, I);
53     }
54 
55     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
56       return Reader.ReadSourceRange(F, R, I);
57     }
58 
59     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
60       return Reader.GetTypeSourceInfo(F, R, I);
61     }
62 
63     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
64       return Reader.ReadDeclID(F, R, I);
65     }
66 
67     Decl *ReadDecl(const RecordData &R, unsigned &I) {
68       return Reader.ReadDecl(F, R, I);
69     }
70 
71     template<typename T>
72     T *ReadDeclAs(const RecordData &R, unsigned &I) {
73       return Reader.ReadDeclAs<T>(F, R, I);
74     }
75 
76     void ReadQualifierInfo(QualifierInfo &Info,
77                            const RecordData &R, unsigned &I) {
78       Reader.ReadQualifierInfo(F, Info, R, I);
79     }
80 
81     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
82                                 const RecordData &R, unsigned &I) {
83       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
84     }
85 
86     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
87                                 const RecordData &R, unsigned &I) {
88       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
89     }
90 
91     serialization::SubmoduleID readSubmoduleID(const RecordData &R,
92                                                unsigned &I) {
93       if (I >= R.size())
94         return 0;
95 
96       return Reader.getGlobalSubmoduleID(F, R[I++]);
97     }
98 
99     Module *readModule(const RecordData &R, unsigned &I) {
100       return Reader.getSubmodule(readSubmoduleID(R, I));
101     }
102 
103     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
104                                const RecordData &R, unsigned &I);
105 
106     /// \brief RAII class used to capture the first ID within a redeclaration
107     /// chain and to introduce it into the list of pending redeclaration chains
108     /// on destruction.
109     ///
110     /// The caller can choose not to introduce this ID into the redeclaration
111     /// chain by calling \c suppress().
112     class RedeclarableResult {
113       ASTReader &Reader;
114       GlobalDeclID FirstID;
115       mutable bool Owning;
116 
117       RedeclarableResult &operator=(RedeclarableResult&); // DO NOT IMPLEMENT
118 
119     public:
120       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID)
121         : Reader(Reader), FirstID(FirstID), Owning(true) { }
122 
123       RedeclarableResult(const RedeclarableResult &Other)
124         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning)
125       {
126         Other.Owning = false;
127       }
128 
129       ~RedeclarableResult() {
130         // FIXME: We want to suppress this when the declaration is local to
131         // a function, since there's no reason to search other AST files
132         // for redeclarations (they can't exist). However, this is hard to
133         // do locally because the declaration hasn't necessarily loaded its
134         // declaration context yet. Also, local externs still have the function
135         // as their (semantic) declaration context, which is wrong and would
136         // break this optimize.
137 
138         if (FirstID && Owning && Reader.PendingDeclChainsKnown.insert(FirstID))
139           Reader.PendingDeclChains.push_back(FirstID);
140       }
141 
142       /// \brief Retrieve the first ID.
143       GlobalDeclID getFirstID() const { return FirstID; }
144 
145       /// \brief Do not introduce this declaration ID into the set of pending
146       /// declaration chains.
147       void suppress() {
148         Owning = false;
149       }
150     };
151 
152     /// \brief Class used to capture the result of searching for an existing
153     /// declaration of a specific kind and name, along with the ability
154     /// to update the place where this result was found (the declaration
155     /// chain hanging off an identifier or the DeclContext we searched in)
156     /// if requested.
157     class FindExistingResult {
158       ASTReader &Reader;
159       NamedDecl *New;
160       NamedDecl *Existing;
161       mutable bool AddResult;
162 
163       FindExistingResult &operator=(FindExistingResult&); // DO NOT IMPLEMENT
164 
165     public:
166       FindExistingResult(ASTReader &Reader)
167         : Reader(Reader), New(0), Existing(0), AddResult(false) { }
168 
169       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing)
170         : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
171 
172       FindExistingResult(const FindExistingResult &Other)
173         : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
174           AddResult(Other.AddResult)
175       {
176         Other.AddResult = false;
177       }
178 
179       ~FindExistingResult();
180 
181       /// \brief Suppress the addition of this result into the known set of
182       /// names.
183       void suppress() { AddResult = false; }
184 
185       operator NamedDecl*() const { return Existing; }
186 
187       template<typename T>
188       operator T*() const { return dyn_cast_or_null<T>(Existing); }
189     };
190 
191     FindExistingResult findExisting(NamedDecl *D);
192 
193   public:
194     ASTDeclReader(ASTReader &Reader, ModuleFile &F,
195                   llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
196                   unsigned RawLocation,
197                   const RecordData &Record, unsigned &Idx)
198       : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
199         RawLocation(RawLocation), Record(Record), Idx(Idx),
200         TypeIDForTypeDecl(0) { }
201 
202     static void attachPreviousDecl(Decl *D, Decl *previous);
203     static void attachLatestDecl(Decl *D, Decl *latest);
204 
205     void Visit(Decl *D);
206 
207     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
208                     const RecordData &Record);
209 
210     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
211                                     ObjCCategoryDecl *Next) {
212       Cat->NextClassCategory = Next;
213     }
214 
215     void VisitDecl(Decl *D);
216     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
217     void VisitNamedDecl(NamedDecl *ND);
218     void VisitLabelDecl(LabelDecl *LD);
219     void VisitNamespaceDecl(NamespaceDecl *D);
220     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
221     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
222     void VisitTypeDecl(TypeDecl *TD);
223     void VisitTypedefNameDecl(TypedefNameDecl *TD);
224     void VisitTypedefDecl(TypedefDecl *TD);
225     void VisitTypeAliasDecl(TypeAliasDecl *TD);
226     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
227     void VisitTagDecl(TagDecl *TD);
228     void VisitEnumDecl(EnumDecl *ED);
229     void VisitRecordDecl(RecordDecl *RD);
230     void VisitCXXRecordDecl(CXXRecordDecl *D);
231     void VisitClassTemplateSpecializationDecl(
232                                             ClassTemplateSpecializationDecl *D);
233     void VisitClassTemplatePartialSpecializationDecl(
234                                      ClassTemplatePartialSpecializationDecl *D);
235     void VisitClassScopeFunctionSpecializationDecl(
236                                        ClassScopeFunctionSpecializationDecl *D);
237     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
238     void VisitValueDecl(ValueDecl *VD);
239     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
240     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
241     void VisitDeclaratorDecl(DeclaratorDecl *DD);
242     void VisitFunctionDecl(FunctionDecl *FD);
243     void VisitCXXMethodDecl(CXXMethodDecl *D);
244     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
245     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
246     void VisitCXXConversionDecl(CXXConversionDecl *D);
247     void VisitFieldDecl(FieldDecl *FD);
248     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
249     void VisitVarDecl(VarDecl *VD);
250     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
251     void VisitParmVarDecl(ParmVarDecl *PD);
252     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
253     void VisitTemplateDecl(TemplateDecl *D);
254     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
255     void VisitClassTemplateDecl(ClassTemplateDecl *D);
256     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
257     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
258     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
259     void VisitUsingDecl(UsingDecl *D);
260     void VisitUsingShadowDecl(UsingShadowDecl *D);
261     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
262     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
263     void VisitImportDecl(ImportDecl *D);
264     void VisitAccessSpecDecl(AccessSpecDecl *D);
265     void VisitFriendDecl(FriendDecl *D);
266     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
267     void VisitStaticAssertDecl(StaticAssertDecl *D);
268     void VisitBlockDecl(BlockDecl *BD);
269 
270     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
271 
272     template<typename T>
273     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
274 
275     template<typename T>
276     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
277 
278     // FIXME: Reorder according to DeclNodes.td?
279     void VisitObjCMethodDecl(ObjCMethodDecl *D);
280     void VisitObjCContainerDecl(ObjCContainerDecl *D);
281     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
282     void VisitObjCIvarDecl(ObjCIvarDecl *D);
283     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
284     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
285     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
286     void VisitObjCImplDecl(ObjCImplDecl *D);
287     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
288     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
289     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
290     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
291     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
292   };
293 }
294 
295 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
296   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
297 }
298 
299 void ASTDeclReader::Visit(Decl *D) {
300   DeclVisitor<ASTDeclReader, void>::Visit(D);
301 
302   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
303     if (DD->DeclInfo) {
304       DeclaratorDecl::ExtInfo *Info =
305           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
306       Info->TInfo =
307           GetTypeSourceInfo(Record, Idx);
308     }
309     else {
310       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
311     }
312   }
313 
314   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
315     // if we have a fully initialized TypeDecl, we can safely read its type now.
316     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
317   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
318     // if we have a fully initialized TypeDecl, we can safely read its type now.
319     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
320   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
321     // FunctionDecl's body was written last after all other Stmts/Exprs.
322     if (Record[Idx++])
323       FD->setLazyBody(GetCurrentCursorOffset());
324   } else if (D->isTemplateParameter()) {
325     // If we have a fully initialized template parameter, we can now
326     // set its DeclContext.
327     DeclContext *SemaDC = cast<DeclContext>(
328                               Reader.GetDecl(DeclContextIDForTemplateParmDecl));
329     DeclContext *LexicalDC = cast<DeclContext>(
330                        Reader.GetDecl(LexicalDeclContextIDForTemplateParmDecl));
331     D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
332   }
333 }
334 
335 void ASTDeclReader::VisitDecl(Decl *D) {
336   if (D->isTemplateParameter()) {
337     // We don't want to deserialize the DeclContext of a template
338     // parameter immediately, because the template parameter might be
339     // used in the formulation of its DeclContext. Use the translation
340     // unit DeclContext as a placeholder.
341     DeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
342     LexicalDeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
343     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
344   } else {
345     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
346     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
347     // Avoid calling setLexicalDeclContext() directly because it uses
348     // Decl::getASTContext() internally which is unsafe during derialization.
349     D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
350   }
351   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
352   D->setInvalidDecl(Record[Idx++]);
353   if (Record[Idx++]) { // hasAttrs
354     AttrVec Attrs;
355     Reader.ReadAttributes(F, Attrs, Record, Idx);
356     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
357     // internally which is unsafe during derialization.
358     D->setAttrsImpl(Attrs, Reader.getContext());
359   }
360   D->setImplicit(Record[Idx++]);
361   D->setUsed(Record[Idx++]);
362   D->setReferenced(Record[Idx++]);
363   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
364   D->setAccess((AccessSpecifier)Record[Idx++]);
365   D->FromASTFile = true;
366   D->setModulePrivate(Record[Idx++]);
367   D->Hidden = D->isModulePrivate();
368 
369   // Determine whether this declaration is part of a (sub)module. If so, it
370   // may not yet be visible.
371   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
372     // Store the owning submodule ID in the declaration.
373     D->setOwningModuleID(SubmoduleID);
374 
375     // Module-private declarations are never visible, so there is no work to do.
376     if (!D->isModulePrivate()) {
377       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
378         if (Owner->NameVisibility != Module::AllVisible) {
379           // The owning module is not visible. Mark this declaration as hidden.
380           D->Hidden = true;
381 
382           // Note that this declaration was hidden because its owning module is
383           // not yet visible.
384           Reader.HiddenNamesMap[Owner].push_back(D);
385         }
386       }
387     }
388   }
389 }
390 
391 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
392   llvm_unreachable("Translation units are not serialized");
393 }
394 
395 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
396   VisitDecl(ND);
397   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
398 }
399 
400 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
401   VisitNamedDecl(TD);
402   TD->setLocStart(ReadSourceLocation(Record, Idx));
403   // Delay type reading until after we have fully initialized the decl.
404   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
405 }
406 
407 void ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
408   RedeclarableResult Redecl = VisitRedeclarable(TD);
409   VisitTypeDecl(TD);
410 
411   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
412   mergeRedeclarable(TD, Redecl);
413 }
414 
415 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
416   VisitTypedefNameDecl(TD);
417 }
418 
419 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
420   VisitTypedefNameDecl(TD);
421 }
422 
423 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
424   RedeclarableResult Redecl = VisitRedeclarable(TD);
425   VisitTypeDecl(TD);
426 
427   TD->IdentifierNamespace = Record[Idx++];
428   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
429   TD->setCompleteDefinition(Record[Idx++]);
430   TD->setEmbeddedInDeclarator(Record[Idx++]);
431   TD->setFreeStanding(Record[Idx++]);
432   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
433 
434   if (Record[Idx++]) { // hasExtInfo
435     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
436     ReadQualifierInfo(*Info, Record, Idx);
437     TD->TypedefNameDeclOrQualifier = Info;
438   } else
439     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx));
440 
441   mergeRedeclarable(TD, Redecl);
442 }
443 
444 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
445   VisitTagDecl(ED);
446   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
447     ED->setIntegerTypeSourceInfo(TI);
448   else
449     ED->setIntegerType(Reader.readType(F, Record, Idx));
450   ED->setPromotionType(Reader.readType(F, Record, Idx));
451   ED->setNumPositiveBits(Record[Idx++]);
452   ED->setNumNegativeBits(Record[Idx++]);
453   ED->IsScoped = Record[Idx++];
454   ED->IsScopedUsingClassTag = Record[Idx++];
455   ED->IsFixed = Record[Idx++];
456   ED->setInstantiationOfMemberEnum(ReadDeclAs<EnumDecl>(Record, Idx));
457 }
458 
459 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
460   VisitTagDecl(RD);
461   RD->setHasFlexibleArrayMember(Record[Idx++]);
462   RD->setAnonymousStructOrUnion(Record[Idx++]);
463   RD->setHasObjectMember(Record[Idx++]);
464 }
465 
466 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
467   VisitNamedDecl(VD);
468   VD->setType(Reader.readType(F, Record, Idx));
469 }
470 
471 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
472   VisitValueDecl(ECD);
473   if (Record[Idx++])
474     ECD->setInitExpr(Reader.ReadExpr(F));
475   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
476 }
477 
478 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
479   VisitValueDecl(DD);
480   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
481   if (Record[Idx++]) { // hasExtInfo
482     DeclaratorDecl::ExtInfo *Info
483         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
484     ReadQualifierInfo(*Info, Record, Idx);
485     DD->DeclInfo = Info;
486   }
487 }
488 
489 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
490   RedeclarableResult Redecl = VisitRedeclarable(FD);
491   VisitDeclaratorDecl(FD);
492 
493   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
494   FD->IdentifierNamespace = Record[Idx++];
495 
496   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
497   // after everything else is read.
498 
499   FD->SClass = (StorageClass)Record[Idx++];
500   FD->SClassAsWritten = (StorageClass)Record[Idx++];
501   FD->IsInline = Record[Idx++];
502   FD->IsInlineSpecified = Record[Idx++];
503   FD->IsVirtualAsWritten = Record[Idx++];
504   FD->IsPure = Record[Idx++];
505   FD->HasInheritedPrototype = Record[Idx++];
506   FD->HasWrittenPrototype = Record[Idx++];
507   FD->IsDeleted = Record[Idx++];
508   FD->IsTrivial = Record[Idx++];
509   FD->IsDefaulted = Record[Idx++];
510   FD->IsExplicitlyDefaulted = Record[Idx++];
511   FD->HasImplicitReturnZero = Record[Idx++];
512   FD->IsConstexpr = Record[Idx++];
513   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
514 
515   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
516   case FunctionDecl::TK_NonTemplate:
517     mergeRedeclarable(FD, Redecl);
518     break;
519   case FunctionDecl::TK_FunctionTemplate:
520     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
521                                                                       Idx));
522     break;
523   case FunctionDecl::TK_MemberSpecialization: {
524     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
525     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
526     SourceLocation POI = ReadSourceLocation(Record, Idx);
527     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
528     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
529     break;
530   }
531   case FunctionDecl::TK_FunctionTemplateSpecialization: {
532     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
533                                                                       Idx);
534     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
535 
536     // Template arguments.
537     SmallVector<TemplateArgument, 8> TemplArgs;
538     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
539 
540     // Template args as written.
541     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
542     SourceLocation LAngleLoc, RAngleLoc;
543     bool HasTemplateArgumentsAsWritten = Record[Idx++];
544     if (HasTemplateArgumentsAsWritten) {
545       unsigned NumTemplateArgLocs = Record[Idx++];
546       TemplArgLocs.reserve(NumTemplateArgLocs);
547       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
548         TemplArgLocs.push_back(
549             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
550 
551       LAngleLoc = ReadSourceLocation(Record, Idx);
552       RAngleLoc = ReadSourceLocation(Record, Idx);
553     }
554 
555     SourceLocation POI = ReadSourceLocation(Record, Idx);
556 
557     ASTContext &C = Reader.getContext();
558     TemplateArgumentList *TemplArgList
559       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
560     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
561     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
562       TemplArgsInfo.addArgument(TemplArgLocs[i]);
563     FunctionTemplateSpecializationInfo *FTInfo
564         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
565                                                      TemplArgList,
566                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
567                                                      POI);
568     FD->TemplateOrSpecialization = FTInfo;
569 
570     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
571       // The template that contains the specializations set. It's not safe to
572       // use getCanonicalDecl on Template since it may still be initializing.
573       FunctionTemplateDecl *CanonTemplate
574         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
575       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
576       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
577       // FunctionTemplateSpecializationInfo's Profile().
578       // We avoid getASTContext because a decl in the parent hierarchy may
579       // be initializing.
580       llvm::FoldingSetNodeID ID;
581       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
582                                                   TemplArgs.size(), C);
583       void *InsertPos = 0;
584       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
585       assert(InsertPos && "Another specialization already inserted!");
586       CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
587     }
588     break;
589   }
590   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
591     // Templates.
592     UnresolvedSet<8> TemplDecls;
593     unsigned NumTemplates = Record[Idx++];
594     while (NumTemplates--)
595       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
596 
597     // Templates args.
598     TemplateArgumentListInfo TemplArgs;
599     unsigned NumArgs = Record[Idx++];
600     while (NumArgs--)
601       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
602     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
603     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
604 
605     FD->setDependentTemplateSpecialization(Reader.getContext(),
606                                            TemplDecls, TemplArgs);
607     break;
608   }
609   }
610 
611   // Read in the parameters.
612   unsigned NumParams = Record[Idx++];
613   SmallVector<ParmVarDecl *, 16> Params;
614   Params.reserve(NumParams);
615   for (unsigned I = 0; I != NumParams; ++I)
616     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
617   FD->setParams(Reader.getContext(), Params);
618 }
619 
620 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
621   VisitNamedDecl(MD);
622   if (Record[Idx++]) {
623     // In practice, this won't be executed (since method definitions
624     // don't occur in header files).
625     MD->setBody(Reader.ReadStmt(F));
626     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
627     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
628   }
629   MD->setInstanceMethod(Record[Idx++]);
630   MD->setVariadic(Record[Idx++]);
631   MD->setSynthesized(Record[Idx++]);
632   MD->setDefined(Record[Idx++]);
633 
634   MD->IsRedeclaration = Record[Idx++];
635   MD->HasRedeclaration = Record[Idx++];
636   if (MD->HasRedeclaration)
637     Reader.getContext().setObjCMethodRedeclaration(MD,
638                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
639 
640   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
641   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
642   MD->SetRelatedResultType(Record[Idx++]);
643   MD->setResultType(Reader.readType(F, Record, Idx));
644   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
645   MD->setEndLoc(ReadSourceLocation(Record, Idx));
646   unsigned NumParams = Record[Idx++];
647   SmallVector<ParmVarDecl *, 16> Params;
648   Params.reserve(NumParams);
649   for (unsigned I = 0; I != NumParams; ++I)
650     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
651 
652   MD->SelLocsKind = Record[Idx++];
653   unsigned NumStoredSelLocs = Record[Idx++];
654   SmallVector<SourceLocation, 16> SelLocs;
655   SelLocs.reserve(NumStoredSelLocs);
656   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
657     SelLocs.push_back(ReadSourceLocation(Record, Idx));
658 
659   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
660 }
661 
662 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
663   VisitNamedDecl(CD);
664   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
665   CD->setAtEndRange(ReadSourceRange(Record, Idx));
666 }
667 
668 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
669   RedeclarableResult Redecl = VisitRedeclarable(ID);
670   VisitObjCContainerDecl(ID);
671   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
672   mergeRedeclarable(ID, Redecl);
673 
674   if (Record[Idx++]) {
675     // Read the definition.
676     ID->allocateDefinitionData();
677 
678     // Set the definition data of the canonical declaration, so other
679     // redeclarations will see it.
680     ID->getCanonicalDecl()->Data = ID->Data;
681 
682     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
683 
684     // Read the superclass.
685     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
686     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
687 
688     Data.EndLoc = ReadSourceLocation(Record, Idx);
689 
690     // Read the directly referenced protocols and their SourceLocations.
691     unsigned NumProtocols = Record[Idx++];
692     SmallVector<ObjCProtocolDecl *, 16> Protocols;
693     Protocols.reserve(NumProtocols);
694     for (unsigned I = 0; I != NumProtocols; ++I)
695       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
696     SmallVector<SourceLocation, 16> ProtoLocs;
697     ProtoLocs.reserve(NumProtocols);
698     for (unsigned I = 0; I != NumProtocols; ++I)
699       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
700     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
701                         Reader.getContext());
702 
703     // Read the transitive closure of protocols referenced by this class.
704     NumProtocols = Record[Idx++];
705     Protocols.clear();
706     Protocols.reserve(NumProtocols);
707     for (unsigned I = 0; I != NumProtocols; ++I)
708       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
709     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
710                                           Reader.getContext());
711 
712     // We will rebuild this list lazily.
713     ID->setIvarList(0);
714 
715     // Note that we have deserialized a definition.
716     Reader.PendingDefinitions.insert(ID);
717 
718     // Note that we've loaded this Objective-C class.
719     Reader.ObjCClassesLoaded.push_back(ID);
720   } else {
721     ID->Data = ID->getCanonicalDecl()->Data;
722   }
723 }
724 
725 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
726   VisitFieldDecl(IVD);
727   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
728   // This field will be built lazily.
729   IVD->setNextIvar(0);
730   bool synth = Record[Idx++];
731   IVD->setSynthesize(synth);
732 }
733 
734 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
735   RedeclarableResult Redecl = VisitRedeclarable(PD);
736   VisitObjCContainerDecl(PD);
737   mergeRedeclarable(PD, Redecl);
738 
739   if (Record[Idx++]) {
740     // Read the definition.
741     PD->allocateDefinitionData();
742 
743     // Set the definition data of the canonical declaration, so other
744     // redeclarations will see it.
745     PD->getCanonicalDecl()->Data = PD->Data;
746 
747     unsigned NumProtoRefs = Record[Idx++];
748     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
749     ProtoRefs.reserve(NumProtoRefs);
750     for (unsigned I = 0; I != NumProtoRefs; ++I)
751       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
752     SmallVector<SourceLocation, 16> ProtoLocs;
753     ProtoLocs.reserve(NumProtoRefs);
754     for (unsigned I = 0; I != NumProtoRefs; ++I)
755       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
756     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
757                         Reader.getContext());
758 
759     // Note that we have deserialized a definition.
760     Reader.PendingDefinitions.insert(PD);
761   } else {
762     PD->Data = PD->getCanonicalDecl()->Data;
763   }
764 }
765 
766 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
767   VisitFieldDecl(FD);
768 }
769 
770 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
771   VisitObjCContainerDecl(CD);
772   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
773   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
774   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
775 
776   // Note that this category has been deserialized. We do this before
777   // deserializing the interface declaration, so that it will consider this
778   /// category.
779   Reader.CategoriesDeserialized.insert(CD);
780 
781   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
782   unsigned NumProtoRefs = Record[Idx++];
783   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
784   ProtoRefs.reserve(NumProtoRefs);
785   for (unsigned I = 0; I != NumProtoRefs; ++I)
786     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
787   SmallVector<SourceLocation, 16> ProtoLocs;
788   ProtoLocs.reserve(NumProtoRefs);
789   for (unsigned I = 0; I != NumProtoRefs; ++I)
790     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
791   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
792                       Reader.getContext());
793   CD->setHasSynthBitfield(Record[Idx++]);
794 }
795 
796 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
797   VisitNamedDecl(CAD);
798   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
799 }
800 
801 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
802   VisitNamedDecl(D);
803   D->setAtLoc(ReadSourceLocation(Record, Idx));
804   D->setLParenLoc(ReadSourceLocation(Record, Idx));
805   D->setType(GetTypeSourceInfo(Record, Idx));
806   // FIXME: stable encoding
807   D->setPropertyAttributes(
808                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
809   D->setPropertyAttributesAsWritten(
810                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
811   // FIXME: stable encoding
812   D->setPropertyImplementation(
813                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
814   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
815   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
816   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
817   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
818   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
819 }
820 
821 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
822   VisitObjCContainerDecl(D);
823   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
824 }
825 
826 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
827   VisitObjCImplDecl(D);
828   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
829   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
830 }
831 
832 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
833   VisitObjCImplDecl(D);
834   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
835   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
836   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
837   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
838       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
839   D->setHasSynthBitfield(Record[Idx++]);
840 }
841 
842 
843 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
844   VisitDecl(D);
845   D->setAtLoc(ReadSourceLocation(Record, Idx));
846   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
847   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
848   D->IvarLoc = ReadSourceLocation(Record, Idx);
849   D->setGetterCXXConstructor(Reader.ReadExpr(F));
850   D->setSetterCXXAssignment(Reader.ReadExpr(F));
851 }
852 
853 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
854   VisitDeclaratorDecl(FD);
855   FD->setMutable(Record[Idx++]);
856   int BitWidthOrInitializer = Record[Idx++];
857   if (BitWidthOrInitializer == 1)
858     FD->setBitWidth(Reader.ReadExpr(F));
859   else if (BitWidthOrInitializer == 2)
860     FD->setInClassInitializer(Reader.ReadExpr(F));
861   if (!FD->getDeclName()) {
862     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
863       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
864   }
865 }
866 
867 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
868   VisitValueDecl(FD);
869 
870   FD->ChainingSize = Record[Idx++];
871   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
872   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
873 
874   for (unsigned I = 0; I != FD->ChainingSize; ++I)
875     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
876 }
877 
878 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
879   RedeclarableResult Redecl = VisitRedeclarable(VD);
880   VisitDeclaratorDecl(VD);
881 
882   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
883   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
884   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
885   VD->VarDeclBits.InitStyle = Record[Idx++];
886   VD->VarDeclBits.ExceptionVar = Record[Idx++];
887   VD->VarDeclBits.NRVOVariable = Record[Idx++];
888   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
889   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
890 
891   // Only true variables (not parameters or implicit parameters) can be merged.
892   if (VD->getKind() == Decl::Var)
893     mergeRedeclarable(VD, Redecl);
894 
895   if (uint64_t Val = Record[Idx++]) {
896     VD->setInit(Reader.ReadExpr(F));
897     if (Val > 1) {
898       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
899       Eval->CheckedICE = true;
900       Eval->IsICE = Val == 3;
901     }
902   }
903 
904   if (Record[Idx++]) { // HasMemberSpecializationInfo.
905     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
906     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
907     SourceLocation POI = ReadSourceLocation(Record, Idx);
908     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
909   }
910 }
911 
912 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
913   VisitVarDecl(PD);
914 }
915 
916 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
917   VisitVarDecl(PD);
918   unsigned isObjCMethodParam = Record[Idx++];
919   unsigned scopeDepth = Record[Idx++];
920   unsigned scopeIndex = Record[Idx++];
921   unsigned declQualifier = Record[Idx++];
922   if (isObjCMethodParam) {
923     assert(scopeDepth == 0);
924     PD->setObjCMethodScopeInfo(scopeIndex);
925     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
926   } else {
927     PD->setScopeInfo(scopeDepth, scopeIndex);
928   }
929   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
930   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
931   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
932     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
933 }
934 
935 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
936   VisitDecl(AD);
937   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
938   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
939 }
940 
941 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
942   VisitDecl(BD);
943   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
944   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
945   unsigned NumParams = Record[Idx++];
946   SmallVector<ParmVarDecl *, 16> Params;
947   Params.reserve(NumParams);
948   for (unsigned I = 0; I != NumParams; ++I)
949     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
950   BD->setParams(Params);
951 
952   bool capturesCXXThis = Record[Idx++];
953   unsigned numCaptures = Record[Idx++];
954   SmallVector<BlockDecl::Capture, 16> captures;
955   captures.reserve(numCaptures);
956   for (unsigned i = 0; i != numCaptures; ++i) {
957     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
958     unsigned flags = Record[Idx++];
959     bool byRef = (flags & 1);
960     bool nested = (flags & 2);
961     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
962 
963     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
964   }
965   BD->setCaptures(Reader.getContext(), captures.begin(),
966                   captures.end(), capturesCXXThis);
967 }
968 
969 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
970   VisitDecl(D);
971   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
972   D->setExternLoc(ReadSourceLocation(Record, Idx));
973   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
974 }
975 
976 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
977   VisitNamedDecl(D);
978   D->setLocStart(ReadSourceLocation(Record, Idx));
979 }
980 
981 
982 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
983   RedeclarableResult Redecl = VisitRedeclarable(D);
984   VisitNamedDecl(D);
985   D->setInline(Record[Idx++]);
986   D->LocStart = ReadSourceLocation(Record, Idx);
987   D->RBraceLoc = ReadSourceLocation(Record, Idx);
988   mergeRedeclarable(D, Redecl);
989 
990   if (Redecl.getFirstID() == ThisDeclID) {
991     // Each module has its own anonymous namespace, which is disjoint from
992     // any other module's anonymous namespaces, so don't attach the anonymous
993     // namespace at all.
994     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
995     if (F.Kind != MK_Module)
996       D->setAnonymousNamespace(Anon);
997   } else {
998     // Link this namespace back to the first declaration, which has already
999     // been deserialized.
1000     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
1001   }
1002 }
1003 
1004 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1005   VisitNamedDecl(D);
1006   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1007   D->IdentLoc = ReadSourceLocation(Record, Idx);
1008   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1009   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1010 }
1011 
1012 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1013   VisitNamedDecl(D);
1014   D->setUsingLocation(ReadSourceLocation(Record, Idx));
1015   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1016   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1017   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1018   D->setTypeName(Record[Idx++]);
1019   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1020     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1021 }
1022 
1023 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1024   VisitNamedDecl(D);
1025   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1026   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1027   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1028   if (Pattern)
1029     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1030 }
1031 
1032 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1033   VisitNamedDecl(D);
1034   D->UsingLoc = ReadSourceLocation(Record, Idx);
1035   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1036   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1037   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1038   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1039 }
1040 
1041 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1042   VisitValueDecl(D);
1043   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1044   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1045   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1046 }
1047 
1048 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1049                                                UnresolvedUsingTypenameDecl *D) {
1050   VisitTypeDecl(D);
1051   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1052   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1053 }
1054 
1055 void ASTDeclReader::ReadCXXDefinitionData(
1056                                    struct CXXRecordDecl::DefinitionData &Data,
1057                                    const RecordData &Record, unsigned &Idx) {
1058   // Note: the caller has deserialized the IsLambda bit already.
1059   Data.UserDeclaredConstructor = Record[Idx++];
1060   Data.UserDeclaredCopyConstructor = Record[Idx++];
1061   Data.UserDeclaredMoveConstructor = Record[Idx++];
1062   Data.UserDeclaredCopyAssignment = Record[Idx++];
1063   Data.UserDeclaredMoveAssignment = Record[Idx++];
1064   Data.UserDeclaredDestructor = Record[Idx++];
1065   Data.Aggregate = Record[Idx++];
1066   Data.PlainOldData = Record[Idx++];
1067   Data.Empty = Record[Idx++];
1068   Data.Polymorphic = Record[Idx++];
1069   Data.Abstract = Record[Idx++];
1070   Data.IsStandardLayout = Record[Idx++];
1071   Data.HasNoNonEmptyBases = Record[Idx++];
1072   Data.HasPrivateFields = Record[Idx++];
1073   Data.HasProtectedFields = Record[Idx++];
1074   Data.HasPublicFields = Record[Idx++];
1075   Data.HasMutableFields = Record[Idx++];
1076   Data.HasOnlyCMembers = Record[Idx++];
1077   Data.HasTrivialDefaultConstructor = Record[Idx++];
1078   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1079   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1080   Data.DefaultedCopyConstructorIsConstexpr = Record[Idx++];
1081   Data.DefaultedMoveConstructorIsConstexpr = Record[Idx++];
1082   Data.HasConstexprDefaultConstructor = Record[Idx++];
1083   Data.HasConstexprCopyConstructor = Record[Idx++];
1084   Data.HasConstexprMoveConstructor = Record[Idx++];
1085   Data.HasTrivialCopyConstructor = Record[Idx++];
1086   Data.HasTrivialMoveConstructor = Record[Idx++];
1087   Data.HasTrivialCopyAssignment = Record[Idx++];
1088   Data.HasTrivialMoveAssignment = Record[Idx++];
1089   Data.HasTrivialDestructor = Record[Idx++];
1090   Data.HasIrrelevantDestructor = Record[Idx++];
1091   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1092   Data.ComputedVisibleConversions = Record[Idx++];
1093   Data.UserProvidedDefaultConstructor = Record[Idx++];
1094   Data.DeclaredDefaultConstructor = Record[Idx++];
1095   Data.DeclaredCopyConstructor = Record[Idx++];
1096   Data.DeclaredMoveConstructor = Record[Idx++];
1097   Data.DeclaredCopyAssignment = Record[Idx++];
1098   Data.DeclaredMoveAssignment = Record[Idx++];
1099   Data.DeclaredDestructor = Record[Idx++];
1100   Data.FailedImplicitMoveConstructor = Record[Idx++];
1101   Data.FailedImplicitMoveAssignment = Record[Idx++];
1102 
1103   Data.NumBases = Record[Idx++];
1104   if (Data.NumBases)
1105     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1106   Data.NumVBases = Record[Idx++];
1107   if (Data.NumVBases)
1108     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1109 
1110   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1111   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1112   assert(Data.Definition && "Data.Definition should be already set!");
1113   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
1114 
1115   if (Data.IsLambda) {
1116     typedef LambdaExpr::Capture Capture;
1117     CXXRecordDecl::LambdaDefinitionData &Lambda
1118       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1119     Lambda.Dependent = Record[Idx++];
1120     Lambda.NumCaptures = Record[Idx++];
1121     Lambda.NumExplicitCaptures = Record[Idx++];
1122     Lambda.ManglingNumber = Record[Idx++];
1123     Lambda.ContextDecl = ReadDecl(Record, Idx);
1124     Lambda.Captures
1125       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1126     Capture *ToCapture = Lambda.Captures;
1127     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1128       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1129       bool IsImplicit = Record[Idx++];
1130       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1131       VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1132       SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1133       *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1134     }
1135   }
1136 }
1137 
1138 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
1139   VisitRecordDecl(D);
1140 
1141   ASTContext &C = Reader.getContext();
1142   if (Record[Idx++]) {
1143     // Determine whether this is a lambda closure type, so that we can
1144     // allocate the appropriate DefinitionData structure.
1145     bool IsLambda = Record[Idx++];
1146     if (IsLambda)
1147       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, false);
1148     else
1149       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1150 
1151     // Propagate the DefinitionData pointer to the canonical declaration, so
1152     // that all other deserialized declarations will see it.
1153     // FIXME: Complain if there already is a DefinitionData!
1154     D->getCanonicalDecl()->DefinitionData = D->DefinitionData;
1155 
1156     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1157 
1158     // Note that we have deserialized a definition. Any declarations
1159     // deserialized before this one will be be given the DefinitionData pointer
1160     // at the end.
1161     Reader.PendingDefinitions.insert(D);
1162   } else {
1163     // Propagate DefinitionData pointer from the canonical declaration.
1164     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1165   }
1166 
1167   enum CXXRecKind {
1168     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1169   };
1170   switch ((CXXRecKind)Record[Idx++]) {
1171   case CXXRecNotTemplate:
1172     break;
1173   case CXXRecTemplate:
1174     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1175     break;
1176   case CXXRecMemberSpecialization: {
1177     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1178     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1179     SourceLocation POI = ReadSourceLocation(Record, Idx);
1180     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1181     MSI->setPointOfInstantiation(POI);
1182     D->TemplateOrInstantiation = MSI;
1183     break;
1184   }
1185   }
1186 
1187   // Load the key function to avoid deserializing every method so we can
1188   // compute it.
1189   if (D->IsCompleteDefinition) {
1190     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1191       C.KeyFunctions[D] = Key;
1192   }
1193 }
1194 
1195 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1196   VisitFunctionDecl(D);
1197   unsigned NumOverridenMethods = Record[Idx++];
1198   while (NumOverridenMethods--) {
1199     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1200     // MD may be initializing.
1201     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1202       Reader.getContext().addOverriddenMethod(D, MD);
1203   }
1204 }
1205 
1206 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1207   VisitCXXMethodDecl(D);
1208 
1209   D->IsExplicitSpecified = Record[Idx++];
1210   D->ImplicitlyDefined = Record[Idx++];
1211   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1212       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1213 }
1214 
1215 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1216   VisitCXXMethodDecl(D);
1217 
1218   D->ImplicitlyDefined = Record[Idx++];
1219   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1220 }
1221 
1222 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1223   VisitCXXMethodDecl(D);
1224   D->IsExplicitSpecified = Record[Idx++];
1225 }
1226 
1227 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1228   VisitDecl(D);
1229   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1230   D->ImportedAndComplete.setInt(Record[Idx++]);
1231   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1232   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1233     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1234   ++Idx;
1235 }
1236 
1237 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1238   VisitDecl(D);
1239   D->setColonLoc(ReadSourceLocation(Record, Idx));
1240 }
1241 
1242 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1243   VisitDecl(D);
1244   if (Record[Idx++])
1245     D->Friend = GetTypeSourceInfo(Record, Idx);
1246   else
1247     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1248   D->NextFriend = Record[Idx++];
1249   D->UnsupportedFriend = (Record[Idx++] != 0);
1250   D->FriendLoc = ReadSourceLocation(Record, Idx);
1251 }
1252 
1253 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1254   VisitDecl(D);
1255   unsigned NumParams = Record[Idx++];
1256   D->NumParams = NumParams;
1257   D->Params = new TemplateParameterList*[NumParams];
1258   for (unsigned i = 0; i != NumParams; ++i)
1259     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1260   if (Record[Idx++]) // HasFriendDecl
1261     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1262   else
1263     D->Friend = GetTypeSourceInfo(Record, Idx);
1264   D->FriendLoc = ReadSourceLocation(Record, Idx);
1265 }
1266 
1267 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1268   VisitNamedDecl(D);
1269 
1270   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1271   TemplateParameterList* TemplateParams
1272       = Reader.ReadTemplateParameterList(F, Record, Idx);
1273   D->init(TemplatedDecl, TemplateParams);
1274 }
1275 
1276 ASTDeclReader::RedeclarableResult
1277 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1278   RedeclarableResult Redecl = VisitRedeclarable(D);
1279 
1280   // Make sure we've allocated the Common pointer first. We do this before
1281   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1282   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1283   if (!CanonD->Common) {
1284     CanonD->Common = CanonD->newCommon(Reader.getContext());
1285     Reader.PendingDefinitions.insert(CanonD);
1286   }
1287   D->Common = CanonD->Common;
1288 
1289   // If this is the first declaration of the template, fill in the information
1290   // for the 'common' pointer.
1291   if (ThisDeclID == Redecl.getFirstID()) {
1292     if (RedeclarableTemplateDecl *RTD
1293           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1294       assert(RTD->getKind() == D->getKind() &&
1295              "InstantiatedFromMemberTemplate kind mismatch");
1296       D->setInstantiatedFromMemberTemplate(RTD);
1297       if (Record[Idx++])
1298         D->setMemberSpecialization();
1299     }
1300   }
1301 
1302   VisitTemplateDecl(D);
1303   D->IdentifierNamespace = Record[Idx++];
1304 
1305   return Redecl;
1306 }
1307 
1308 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1309   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1310 
1311   if (ThisDeclID == Redecl.getFirstID()) {
1312     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1313     // the specializations.
1314     SmallVector<serialization::DeclID, 2> SpecIDs;
1315     SpecIDs.push_back(0);
1316 
1317     // Specializations.
1318     unsigned Size = Record[Idx++];
1319     SpecIDs[0] += Size;
1320     for (unsigned I = 0; I != Size; ++I)
1321       SpecIDs.push_back(ReadDeclID(Record, Idx));
1322 
1323     // Partial specializations.
1324     Size = Record[Idx++];
1325     SpecIDs[0] += Size;
1326     for (unsigned I = 0; I != Size; ++I)
1327       SpecIDs.push_back(ReadDeclID(Record, Idx));
1328 
1329     if (SpecIDs[0]) {
1330       typedef serialization::DeclID DeclID;
1331 
1332       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1333       // FIXME: Append specializations!
1334       CommonPtr->LazySpecializations
1335         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1336       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1337              SpecIDs.size() * sizeof(DeclID));
1338     }
1339 
1340     // InjectedClassNameType is computed.
1341   }
1342 }
1343 
1344 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1345                                            ClassTemplateSpecializationDecl *D) {
1346   VisitCXXRecordDecl(D);
1347 
1348   ASTContext &C = Reader.getContext();
1349   if (Decl *InstD = ReadDecl(Record, Idx)) {
1350     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1351       D->SpecializedTemplate = CTD;
1352     } else {
1353       SmallVector<TemplateArgument, 8> TemplArgs;
1354       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1355       TemplateArgumentList *ArgList
1356         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1357                                            TemplArgs.size());
1358       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1359           = new (C) ClassTemplateSpecializationDecl::
1360                                              SpecializedPartialSpecialization();
1361       PS->PartialSpecialization
1362           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1363       PS->TemplateArgs = ArgList;
1364       D->SpecializedTemplate = PS;
1365     }
1366   }
1367 
1368   // Explicit info.
1369   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1370     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1371         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1372     ExplicitInfo->TypeAsWritten = TyInfo;
1373     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1374     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1375     D->ExplicitInfo = ExplicitInfo;
1376   }
1377 
1378   SmallVector<TemplateArgument, 8> TemplArgs;
1379   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1380   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1381                                                      TemplArgs.size());
1382   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1383   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1384 
1385   if (D->isCanonicalDecl()) { // It's kept in the folding set.
1386     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1387     if (ClassTemplatePartialSpecializationDecl *Partial
1388                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1389       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1390     } else {
1391       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1392     }
1393   }
1394 }
1395 
1396 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1397                                     ClassTemplatePartialSpecializationDecl *D) {
1398   VisitClassTemplateSpecializationDecl(D);
1399 
1400   ASTContext &C = Reader.getContext();
1401   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1402 
1403   unsigned NumArgs = Record[Idx++];
1404   if (NumArgs) {
1405     D->NumArgsAsWritten = NumArgs;
1406     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1407     for (unsigned i=0; i != NumArgs; ++i)
1408       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1409   }
1410 
1411   D->SequenceNumber = Record[Idx++];
1412 
1413   // These are read/set from/to the first declaration.
1414   if (D->getPreviousDecl() == 0) {
1415     D->InstantiatedFromMember.setPointer(
1416       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1417     D->InstantiatedFromMember.setInt(Record[Idx++]);
1418   }
1419 }
1420 
1421 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1422                                     ClassScopeFunctionSpecializationDecl *D) {
1423   VisitDecl(D);
1424   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1425 }
1426 
1427 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1428   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1429 
1430   if (ThisDeclID == Redecl.getFirstID()) {
1431     // This FunctionTemplateDecl owns a CommonPtr; read it.
1432 
1433     // Read the function specialization declarations.
1434     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1435     // when reading the specialized FunctionDecl.
1436     unsigned NumSpecs = Record[Idx++];
1437     while (NumSpecs--)
1438       (void)ReadDecl(Record, Idx);
1439   }
1440 }
1441 
1442 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1443   VisitTypeDecl(D);
1444 
1445   D->setDeclaredWithTypename(Record[Idx++]);
1446 
1447   bool Inherited = Record[Idx++];
1448   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1449   D->setDefaultArgument(DefArg, Inherited);
1450 }
1451 
1452 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1453   VisitDeclaratorDecl(D);
1454   // TemplateParmPosition.
1455   D->setDepth(Record[Idx++]);
1456   D->setPosition(Record[Idx++]);
1457   if (D->isExpandedParameterPack()) {
1458     void **Data = reinterpret_cast<void **>(D + 1);
1459     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1460       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1461       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1462     }
1463   } else {
1464     // Rest of NonTypeTemplateParmDecl.
1465     D->ParameterPack = Record[Idx++];
1466     if (Record[Idx++]) {
1467       Expr *DefArg = Reader.ReadExpr(F);
1468       bool Inherited = Record[Idx++];
1469       D->setDefaultArgument(DefArg, Inherited);
1470    }
1471   }
1472 }
1473 
1474 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1475   VisitTemplateDecl(D);
1476   // TemplateParmPosition.
1477   D->setDepth(Record[Idx++]);
1478   D->setPosition(Record[Idx++]);
1479   // Rest of TemplateTemplateParmDecl.
1480   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1481   bool IsInherited = Record[Idx++];
1482   D->setDefaultArgument(Arg, IsInherited);
1483   D->ParameterPack = Record[Idx++];
1484 }
1485 
1486 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1487   VisitRedeclarableTemplateDecl(D);
1488 }
1489 
1490 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1491   VisitDecl(D);
1492   D->AssertExpr = Reader.ReadExpr(F);
1493   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1494   D->RParenLoc = ReadSourceLocation(Record, Idx);
1495 }
1496 
1497 std::pair<uint64_t, uint64_t>
1498 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1499   uint64_t LexicalOffset = Record[Idx++];
1500   uint64_t VisibleOffset = Record[Idx++];
1501   return std::make_pair(LexicalOffset, VisibleOffset);
1502 }
1503 
1504 template <typename T>
1505 ASTDeclReader::RedeclarableResult
1506 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1507   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1508 
1509   // 0 indicates that this declaration was the only declaration of its entity,
1510   // and is used for space optimization.
1511   if (FirstDeclID == 0)
1512     FirstDeclID = ThisDeclID;
1513 
1514   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1515   if (FirstDecl != D) {
1516     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1517     // We temporarily set the first (canonical) declaration as the previous one
1518     // which is the one that matters and mark the real previous DeclID to be
1519     // loaded & attached later on.
1520     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(FirstDecl);
1521   }
1522 
1523   // Note that this declaration has been deserialized.
1524   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1525 
1526   // The result structure takes care to note that we need to load the
1527   // other declaration chains for this ID.
1528   return RedeclarableResult(Reader, FirstDeclID);
1529 }
1530 
1531 /// \brief Attempts to merge the given declaration (D) with another declaration
1532 /// of the same entity.
1533 template<typename T>
1534 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1535                                       RedeclarableResult &Redecl) {
1536   // If modules are not available, there is no reason to perform this merge.
1537   if (!Reader.getContext().getLangOptions().Modules)
1538     return;
1539 
1540   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
1541     if (T *Existing = ExistingRes) {
1542       T *ExistingCanon = Existing->getCanonicalDecl();
1543       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1544       if (ExistingCanon != DCanon) {
1545         // Have our redeclaration link point back at the canonical declaration
1546         // of the existing declaration, so that this declaration has the
1547         // appropriate canonical declaration.
1548         D->RedeclLink
1549           = typename Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1550 
1551         // When we merge a namespace, update its pointer to the first namespace.
1552         if (NamespaceDecl *Namespace
1553               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1554           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1555             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1556         }
1557 
1558         // Don't introduce DCanon into the set of pending declaration chains.
1559         Redecl.suppress();
1560 
1561         // Introduce ExistingCanon into the set of pending declaration chains,
1562         // if in fact it came from a module file.
1563         if (ExistingCanon->isFromASTFile()) {
1564           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1565           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1566           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1567             Reader.PendingDeclChains.push_back(ExistingCanonID);
1568         }
1569 
1570         // If this declaration was the canonical declaration, make a note of
1571         // that. We accept the linear algorithm here because the number of
1572         // unique canonical declarations of an entity should always be tiny.
1573         if (DCanon == static_cast<T*>(D)) {
1574           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1575           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1576                 == Merged.end())
1577             Merged.push_back(Redecl.getFirstID());
1578 
1579           // If ExistingCanon did not come from a module file, introduce the
1580           // first declaration that *does* come from a module file to the
1581           // set of pending declaration chains, so that we merge this
1582           // declaration.
1583           if (!ExistingCanon->isFromASTFile() &&
1584               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1585             Reader.PendingDeclChains.push_back(Merged[0]);
1586         }
1587       }
1588     }
1589   }
1590 }
1591 
1592 //===----------------------------------------------------------------------===//
1593 // Attribute Reading
1594 //===----------------------------------------------------------------------===//
1595 
1596 /// \brief Reads attributes from the current stream position.
1597 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1598                                const RecordData &Record, unsigned &Idx) {
1599   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1600     Attr *New = 0;
1601     attr::Kind Kind = (attr::Kind)Record[Idx++];
1602     SourceRange Range = ReadSourceRange(F, Record, Idx);
1603 
1604 #include "clang/Serialization/AttrPCHRead.inc"
1605 
1606     assert(New && "Unable to decode attribute?");
1607     Attrs.push_back(New);
1608   }
1609 }
1610 
1611 //===----------------------------------------------------------------------===//
1612 // ASTReader Implementation
1613 //===----------------------------------------------------------------------===//
1614 
1615 /// \brief Note that we have loaded the declaration with the given
1616 /// Index.
1617 ///
1618 /// This routine notes that this declaration has already been loaded,
1619 /// so that future GetDecl calls will return this declaration rather
1620 /// than trying to load a new declaration.
1621 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1622   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1623   DeclsLoaded[Index] = D;
1624 }
1625 
1626 
1627 /// \brief Determine whether the consumer will be interested in seeing
1628 /// this declaration (via HandleTopLevelDecl).
1629 ///
1630 /// This routine should return true for anything that might affect
1631 /// code generation, e.g., inline function definitions, Objective-C
1632 /// declarations with metadata, etc.
1633 static bool isConsumerInterestedIn(Decl *D) {
1634   // An ObjCMethodDecl is never considered as "interesting" because its
1635   // implementation container always is.
1636 
1637   if (isa<FileScopeAsmDecl>(D) ||
1638       isa<ObjCProtocolDecl>(D) ||
1639       isa<ObjCImplDecl>(D))
1640     return true;
1641   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1642     return Var->isFileVarDecl() &&
1643            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1644   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1645     return Func->doesThisDeclarationHaveABody();
1646 
1647   return false;
1648 }
1649 
1650 /// \brief Get the correct cursor and offset for loading a declaration.
1651 ASTReader::RecordLocation
1652 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1653   // See if there's an override.
1654   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1655   if (It != ReplacedDecls.end()) {
1656     RawLocation = It->second.RawLoc;
1657     return RecordLocation(It->second.Mod, It->second.Offset);
1658   }
1659 
1660   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1661   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1662   ModuleFile *M = I->second;
1663   const DeclOffset &
1664     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1665   RawLocation = DOffs.Loc;
1666   return RecordLocation(M, DOffs.BitOffset);
1667 }
1668 
1669 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1670   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
1671     = GlobalBitOffsetsMap.find(GlobalOffset);
1672 
1673   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1674   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1675 }
1676 
1677 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
1678   return LocalOffset + M.GlobalBitOffset;
1679 }
1680 
1681 /// \brief Determine whether the two declarations refer to the same entity.
1682 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
1683   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
1684 
1685   if (X == Y)
1686     return true;
1687 
1688   // Must be in the same context.
1689   if (!X->getDeclContext()->getRedeclContext()->Equals(
1690          Y->getDeclContext()->getRedeclContext()))
1691     return false;
1692 
1693   // Two typedefs refer to the same entity if they have the same underlying
1694   // type.
1695   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
1696     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
1697       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
1698                                             TypedefY->getUnderlyingType());
1699 
1700   // Must have the same kind.
1701   if (X->getKind() != Y->getKind())
1702     return false;
1703 
1704   // Objective-C classes and protocols with the same name always match.
1705   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
1706     return true;
1707 
1708   // Compatible tags match.
1709   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
1710     TagDecl *TagY = cast<TagDecl>(Y);
1711     return (TagX->getTagKind() == TagY->getTagKind()) ||
1712       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class) &&
1713        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class));
1714   }
1715 
1716   // Functions with the same type and linkage match.
1717   // FIXME: This needs to cope with function templates, merging of
1718   //prototyped/non-prototyped functions, etc.
1719   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
1720     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
1721     return (FuncX->getLinkage() == FuncY->getLinkage()) &&
1722       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
1723   }
1724 
1725   // Variables with the same type and linkage match.
1726   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
1727     VarDecl *VarY = cast<VarDecl>(Y);
1728     return (VarX->getLinkage() == VarY->getLinkage()) &&
1729       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
1730   }
1731 
1732   // Namespaces with the same name and inlinedness match.
1733   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
1734     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
1735     return NamespaceX->isInline() == NamespaceY->isInline();
1736   }
1737 
1738   // FIXME: Many other cases to implement.
1739   return false;
1740 }
1741 
1742 ASTDeclReader::FindExistingResult::~FindExistingResult() {
1743   if (!AddResult || Existing)
1744     return;
1745 
1746   DeclContext *DC = New->getDeclContext()->getRedeclContext();
1747   if (DC->isTranslationUnit() && Reader.SemaObj) {
1748     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
1749   } else if (DC->isNamespace()) {
1750     DC->addDecl(New);
1751   }
1752 }
1753 
1754 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
1755   DeclarationName Name = D->getDeclName();
1756   if (!Name) {
1757     // Don't bother trying to find unnamed declarations.
1758     FindExistingResult Result(Reader, D, /*Existing=*/0);
1759     Result.suppress();
1760     return Result;
1761   }
1762 
1763   DeclContext *DC = D->getDeclContext()->getRedeclContext();
1764   if (!DC->isFileContext())
1765     return FindExistingResult(Reader);
1766 
1767   if (DC->isTranslationUnit() && Reader.SemaObj) {
1768     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
1769     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1770                                    IEnd = IdResolver.end();
1771          I != IEnd; ++I) {
1772       if (isSameEntity(*I, D))
1773         return FindExistingResult(Reader, D, *I);
1774     }
1775   }
1776 
1777   if (DC->isNamespace()) {
1778     for (DeclContext::lookup_result R = DC->lookup(Name);
1779          R.first != R.second; ++R.first) {
1780       if (isSameEntity(*R.first, D))
1781         return FindExistingResult(Reader, D, *R.first);
1782     }
1783   }
1784 
1785   return FindExistingResult(Reader, D, /*Existing=*/0);
1786 }
1787 
1788 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1789   assert(D && previous);
1790   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1791     TD->RedeclLink.setPointer(cast<TagDecl>(previous));
1792   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1793     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
1794   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1795     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
1796   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1797     TD->RedeclLink.setPointer(cast<TypedefNameDecl>(previous));
1798   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1799     ID->RedeclLink.setPointer(cast<ObjCInterfaceDecl>(previous));
1800   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1801     PD->RedeclLink.setPointer(cast<ObjCProtocolDecl>(previous));
1802   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1803     ND->RedeclLink.setPointer(cast<NamespaceDecl>(previous));
1804   } else {
1805     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1806     TD->RedeclLink.setPointer(cast<RedeclarableTemplateDecl>(previous));
1807   }
1808 }
1809 
1810 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
1811   assert(D && Latest);
1812   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1813     TD->RedeclLink
1814       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
1815   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1816     FD->RedeclLink
1817       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
1818   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1819     VD->RedeclLink
1820       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
1821   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1822     TD->RedeclLink
1823       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
1824                                                 cast<TypedefNameDecl>(Latest));
1825   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1826     ID->RedeclLink
1827       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
1828                                               cast<ObjCInterfaceDecl>(Latest));
1829   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1830     PD->RedeclLink
1831       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
1832                                                 cast<ObjCProtocolDecl>(Latest));
1833   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1834     ND->RedeclLink
1835       = Redeclarable<NamespaceDecl>::LatestDeclLink(
1836                                                    cast<NamespaceDecl>(Latest));
1837   } else {
1838     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1839     TD->RedeclLink
1840       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
1841                                         cast<RedeclarableTemplateDecl>(Latest));
1842   }
1843 }
1844 
1845 ASTReader::MergedDeclsMap::iterator
1846 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
1847   // If we don't have any stored merged declarations, just look in the
1848   // merged declarations set.
1849   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
1850   if (StoredPos == StoredMergedDecls.end())
1851     return MergedDecls.find(Canon);
1852 
1853   // Append the stored merged declarations to the merged declarations set.
1854   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
1855   if (Pos == MergedDecls.end())
1856     Pos = MergedDecls.insert(std::make_pair(Canon,
1857                                             SmallVector<DeclID, 2>())).first;
1858   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
1859   StoredMergedDecls.erase(StoredPos);
1860 
1861   // Sort and uniquify the set of merged declarations.
1862   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
1863   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
1864                     Pos->second.end());
1865   return Pos;
1866 }
1867 
1868 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1869   Decl *previous = GetDecl(ID);
1870   ASTDeclReader::attachPreviousDecl(D, previous);
1871 }
1872 
1873 /// \brief Read the declaration at the given offset from the AST file.
1874 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1875   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1876   unsigned RawLocation = 0;
1877   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1878   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1879   // Keep track of where we are in the stream, then jump back there
1880   // after reading this declaration.
1881   SavedStreamPosition SavedPosition(DeclsCursor);
1882 
1883   ReadingKindTracker ReadingKind(Read_Decl, *this);
1884 
1885   // Note that we are loading a declaration record.
1886   Deserializing ADecl(this);
1887 
1888   DeclsCursor.JumpToBit(Loc.Offset);
1889   RecordData Record;
1890   unsigned Code = DeclsCursor.ReadCode();
1891   unsigned Idx = 0;
1892   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, RawLocation, Record,Idx);
1893 
1894   Decl *D = 0;
1895   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1896   case DECL_CONTEXT_LEXICAL:
1897   case DECL_CONTEXT_VISIBLE:
1898     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1899   case DECL_TYPEDEF:
1900     D = TypedefDecl::CreateDeserialized(Context, ID);
1901     break;
1902   case DECL_TYPEALIAS:
1903     D = TypeAliasDecl::CreateDeserialized(Context, ID);
1904     break;
1905   case DECL_ENUM:
1906     D = EnumDecl::CreateDeserialized(Context, ID);
1907     break;
1908   case DECL_RECORD:
1909     D = RecordDecl::CreateDeserialized(Context, ID);
1910     break;
1911   case DECL_ENUM_CONSTANT:
1912     D = EnumConstantDecl::CreateDeserialized(Context, ID);
1913     break;
1914   case DECL_FUNCTION:
1915     D = FunctionDecl::CreateDeserialized(Context, ID);
1916     break;
1917   case DECL_LINKAGE_SPEC:
1918     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
1919     break;
1920   case DECL_LABEL:
1921     D = LabelDecl::CreateDeserialized(Context, ID);
1922     break;
1923   case DECL_NAMESPACE:
1924     D = NamespaceDecl::CreateDeserialized(Context, ID);
1925     break;
1926   case DECL_NAMESPACE_ALIAS:
1927     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
1928     break;
1929   case DECL_USING:
1930     D = UsingDecl::CreateDeserialized(Context, ID);
1931     break;
1932   case DECL_USING_SHADOW:
1933     D = UsingShadowDecl::CreateDeserialized(Context, ID);
1934     break;
1935   case DECL_USING_DIRECTIVE:
1936     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
1937     break;
1938   case DECL_UNRESOLVED_USING_VALUE:
1939     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
1940     break;
1941   case DECL_UNRESOLVED_USING_TYPENAME:
1942     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
1943     break;
1944   case DECL_CXX_RECORD:
1945     D = CXXRecordDecl::CreateDeserialized(Context, ID);
1946     break;
1947   case DECL_CXX_METHOD:
1948     D = CXXMethodDecl::CreateDeserialized(Context, ID);
1949     break;
1950   case DECL_CXX_CONSTRUCTOR:
1951     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
1952     break;
1953   case DECL_CXX_DESTRUCTOR:
1954     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
1955     break;
1956   case DECL_CXX_CONVERSION:
1957     D = CXXConversionDecl::CreateDeserialized(Context, ID);
1958     break;
1959   case DECL_ACCESS_SPEC:
1960     D = AccessSpecDecl::CreateDeserialized(Context, ID);
1961     break;
1962   case DECL_FRIEND:
1963     D = FriendDecl::CreateDeserialized(Context, ID);
1964     break;
1965   case DECL_FRIEND_TEMPLATE:
1966     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
1967     break;
1968   case DECL_CLASS_TEMPLATE:
1969     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
1970     break;
1971   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1972     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
1973     break;
1974   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1975     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
1976     break;
1977   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
1978     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
1979     break;
1980   case DECL_FUNCTION_TEMPLATE:
1981     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
1982     break;
1983   case DECL_TEMPLATE_TYPE_PARM:
1984     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
1985     break;
1986   case DECL_NON_TYPE_TEMPLATE_PARM:
1987     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
1988     break;
1989   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1990     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
1991     break;
1992   case DECL_TEMPLATE_TEMPLATE_PARM:
1993     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
1994     break;
1995   case DECL_TYPE_ALIAS_TEMPLATE:
1996     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
1997     break;
1998   case DECL_STATIC_ASSERT:
1999     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2000     break;
2001   case DECL_OBJC_METHOD:
2002     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2003     break;
2004   case DECL_OBJC_INTERFACE:
2005     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2006     break;
2007   case DECL_OBJC_IVAR:
2008     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2009     break;
2010   case DECL_OBJC_PROTOCOL:
2011     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2012     break;
2013   case DECL_OBJC_AT_DEFS_FIELD:
2014     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2015     break;
2016   case DECL_OBJC_CATEGORY:
2017     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2018     break;
2019   case DECL_OBJC_CATEGORY_IMPL:
2020     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2021     break;
2022   case DECL_OBJC_IMPLEMENTATION:
2023     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2024     break;
2025   case DECL_OBJC_COMPATIBLE_ALIAS:
2026     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2027     break;
2028   case DECL_OBJC_PROPERTY:
2029     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2030     break;
2031   case DECL_OBJC_PROPERTY_IMPL:
2032     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2033     break;
2034   case DECL_FIELD:
2035     D = FieldDecl::CreateDeserialized(Context, ID);
2036     break;
2037   case DECL_INDIRECTFIELD:
2038     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2039     break;
2040   case DECL_VAR:
2041     D = VarDecl::CreateDeserialized(Context, ID);
2042     break;
2043   case DECL_IMPLICIT_PARAM:
2044     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2045     break;
2046   case DECL_PARM_VAR:
2047     D = ParmVarDecl::CreateDeserialized(Context, ID);
2048     break;
2049   case DECL_FILE_SCOPE_ASM:
2050     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2051     break;
2052   case DECL_BLOCK:
2053     D = BlockDecl::CreateDeserialized(Context, ID);
2054     break;
2055   case DECL_CXX_BASE_SPECIFIERS:
2056     Error("attempt to read a C++ base-specifier record as a declaration");
2057     return 0;
2058   case DECL_IMPORT:
2059     // Note: last entry of the ImportDecl record is the number of stored source
2060     // locations.
2061     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2062     break;
2063   }
2064 
2065   assert(D && "Unknown declaration reading AST file");
2066   LoadedDecl(Index, D);
2067   // Set the DeclContext before doing any deserialization, to make sure internal
2068   // calls to Decl::getASTContext() by Decl's methods will find the
2069   // TranslationUnitDecl without crashing.
2070   D->setDeclContext(Context.getTranslationUnitDecl());
2071   Reader.Visit(D);
2072 
2073   // If this declaration is also a declaration context, get the
2074   // offsets for its tables of lexical and visible declarations.
2075   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2076     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2077     if (Offsets.first || Offsets.second) {
2078       if (Offsets.first != 0)
2079         DC->setHasExternalLexicalStorage(true);
2080       if (Offsets.second != 0)
2081         DC->setHasExternalVisibleStorage(true);
2082       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2083                                  Loc.F->DeclContextInfos[DC]))
2084         return 0;
2085     }
2086 
2087     // Now add the pending visible updates for this decl context, if it has any.
2088     DeclContextVisibleUpdatesPending::iterator I =
2089         PendingVisibleUpdates.find(ID);
2090     if (I != PendingVisibleUpdates.end()) {
2091       // There are updates. This means the context has external visible
2092       // storage, even if the original stored version didn't.
2093       DC->setHasExternalVisibleStorage(true);
2094       DeclContextVisibleUpdates &U = I->second;
2095       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2096            UI != UE; ++UI) {
2097         UI->second->DeclContextInfos[DC].NameLookupTableData = UI->first;
2098       }
2099       PendingVisibleUpdates.erase(I);
2100     }
2101   }
2102   assert(Idx == Record.size());
2103 
2104   // Load any relevant update records.
2105   loadDeclUpdateRecords(ID, D);
2106 
2107   // Load the categories after recursive loading is finished.
2108   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2109     if (Class->isThisDeclarationADefinition())
2110       loadObjCCategories(ID, Class);
2111 
2112   // If we have deserialized a declaration that has a definition the
2113   // AST consumer might need to know about, queue it.
2114   // We don't pass it to the consumer immediately because we may be in recursive
2115   // loading, and some declarations may still be initializing.
2116   if (isConsumerInterestedIn(D))
2117     InterestingDecls.push_back(D);
2118 
2119   return D;
2120 }
2121 
2122 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2123   // The declaration may have been modified by files later in the chain.
2124   // If this is the case, read the record containing the updates from each file
2125   // and pass it to ASTDeclReader to make the modifications.
2126   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2127   if (UpdI != DeclUpdateOffsets.end()) {
2128     FileOffsetsTy &UpdateOffsets = UpdI->second;
2129     for (FileOffsetsTy::iterator
2130          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2131       ModuleFile *F = I->first;
2132       uint64_t Offset = I->second;
2133       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2134       SavedStreamPosition SavedPosition(Cursor);
2135       Cursor.JumpToBit(Offset);
2136       RecordData Record;
2137       unsigned Code = Cursor.ReadCode();
2138       unsigned RecCode = Cursor.ReadRecord(Code, Record);
2139       (void)RecCode;
2140       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2141 
2142       unsigned Idx = 0;
2143       ASTDeclReader Reader(*this, *F, Cursor, ID, 0, Record, Idx);
2144       Reader.UpdateDecl(D, *F, Record);
2145     }
2146   }
2147 }
2148 
2149 namespace {
2150   struct CompareLocalRedeclarationsInfoToID {
2151     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2152       return X.FirstID < Y;
2153     }
2154 
2155     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2156       return X < Y.FirstID;
2157     }
2158 
2159     bool operator()(const LocalRedeclarationsInfo &X,
2160                     const LocalRedeclarationsInfo &Y) {
2161       return X.FirstID < Y.FirstID;
2162     }
2163     bool operator()(DeclID X, DeclID Y) {
2164       return X < Y;
2165     }
2166   };
2167 
2168   /// \brief Module visitor class that finds all of the redeclarations of a
2169   ///
2170   class RedeclChainVisitor {
2171     ASTReader &Reader;
2172     SmallVectorImpl<DeclID> &SearchDecls;
2173     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2174     GlobalDeclID CanonID;
2175     llvm::SmallVector<Decl *, 4> Chain;
2176 
2177   public:
2178     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2179                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2180                        GlobalDeclID CanonID)
2181       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2182         CanonID(CanonID) {
2183       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2184         addToChain(Reader.GetDecl(SearchDecls[I]));
2185     }
2186 
2187     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2188       if (Preorder)
2189         return false;
2190 
2191       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2192     }
2193 
2194     void addToChain(Decl *D) {
2195       if (!D)
2196         return;
2197 
2198       if (Deserialized.count(D)) {
2199         Deserialized.erase(D);
2200         Chain.push_back(D);
2201       }
2202     }
2203 
2204     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2205       // Map global ID of the first declaration down to the local ID
2206       // used in this module file.
2207       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2208       if (!ID)
2209         return;
2210 
2211       // Perform a binary search to find the local redeclarations for this
2212       // declaration (if any).
2213       const LocalRedeclarationsInfo *Result
2214         = std::lower_bound(M.RedeclarationsMap,
2215                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2216                            ID, CompareLocalRedeclarationsInfoToID());
2217       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2218           Result->FirstID != ID) {
2219         // If we have a previously-canonical singleton declaration that was
2220         // merged into another redeclaration chain, create a trivial chain
2221         // for this single declaration so that it will get wired into the
2222         // complete redeclaration chain.
2223         if (GlobalID != CanonID &&
2224             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2225             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2226           addToChain(Reader.GetDecl(GlobalID));
2227         }
2228 
2229         return;
2230       }
2231 
2232       // Dig out all of the redeclarations.
2233       unsigned Offset = Result->Offset;
2234       unsigned N = M.RedeclarationChains[Offset];
2235       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2236       for (unsigned I = 0; I != N; ++I)
2237         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2238     }
2239 
2240     bool visit(ModuleFile &M) {
2241       // Visit each of the declarations.
2242       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2243         searchForID(M, SearchDecls[I]);
2244       return false;
2245     }
2246 
2247     ArrayRef<Decl *> getChain() const {
2248       return Chain;
2249     }
2250   };
2251 }
2252 
2253 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2254   Decl *D = GetDecl(ID);
2255   Decl *CanonDecl = D->getCanonicalDecl();
2256 
2257   // Determine the set of declaration IDs we'll be searching for.
2258   llvm::SmallVector<DeclID, 1> SearchDecls;
2259   GlobalDeclID CanonID = 0;
2260   if (D == CanonDecl) {
2261     SearchDecls.push_back(ID); // Always first.
2262     CanonID = ID;
2263   }
2264   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2265   if (MergedPos != MergedDecls.end())
2266     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2267 
2268   // Build up the list of redeclarations.
2269   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2270   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2271 
2272   // Retrieve the chains.
2273   ArrayRef<Decl *> Chain = Visitor.getChain();
2274   if (Chain.empty())
2275     return;
2276 
2277   // Hook up the chains.
2278   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2279   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2280     if (Chain[I] == CanonDecl)
2281       continue;
2282 
2283     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2284     MostRecent = Chain[I];
2285   }
2286 
2287   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2288 }
2289 
2290 namespace {
2291   struct CompareObjCCategoriesInfo {
2292     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2293       return X.DefinitionID < Y;
2294     }
2295 
2296     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2297       return X < Y.DefinitionID;
2298     }
2299 
2300     bool operator()(const ObjCCategoriesInfo &X,
2301                     const ObjCCategoriesInfo &Y) {
2302       return X.DefinitionID < Y.DefinitionID;
2303     }
2304     bool operator()(DeclID X, DeclID Y) {
2305       return X < Y;
2306     }
2307   };
2308 
2309   /// \brief Given an ObjC interface, goes through the modules and links to the
2310   /// interface all the categories for it.
2311   class ObjCCategoriesVisitor {
2312     ASTReader &Reader;
2313     serialization::GlobalDeclID InterfaceID;
2314     ObjCInterfaceDecl *Interface;
2315     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2316     unsigned PreviousGeneration;
2317     ObjCCategoryDecl *Tail;
2318     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2319 
2320     void add(ObjCCategoryDecl *Cat) {
2321       // Only process each category once.
2322       if (!Deserialized.count(Cat))
2323         return;
2324       Deserialized.erase(Cat);
2325 
2326       // Check for duplicate categories.
2327       if (Cat->getDeclName()) {
2328         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2329         if (Existing &&
2330             Reader.getOwningModuleFile(Existing)
2331                                           != Reader.getOwningModuleFile(Cat)) {
2332           // FIXME: We should not warn for duplicates in diamond:
2333           //
2334           //   MT     //
2335           //  /  \    //
2336           // ML  MR   //
2337           //  \  /    //
2338           //   MB     //
2339           //
2340           // If there are duplicates in ML/MR, there will be warning when
2341           // creating MB *and* when importing MB. We should not warn when
2342           // importing.
2343           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2344             << Interface->getDeclName() << Cat->getDeclName();
2345           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2346         } else if (!Existing) {
2347           // Record this category.
2348           Existing = Cat;
2349         }
2350       }
2351 
2352       // Add this category to the end of the chain.
2353       if (Tail)
2354         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2355       else
2356         Interface->setCategoryList(Cat);
2357       Tail = Cat;
2358     }
2359 
2360   public:
2361     ObjCCategoriesVisitor(ASTReader &Reader,
2362                           serialization::GlobalDeclID InterfaceID,
2363                           ObjCInterfaceDecl *Interface,
2364                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2365                           unsigned PreviousGeneration)
2366       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2367         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2368         Tail(0)
2369     {
2370       // Populate the name -> category map with the set of known categories.
2371       for (ObjCCategoryDecl *Cat = Interface->getCategoryList(); Cat;
2372            Cat = Cat->getNextClassCategory()) {
2373         if (Cat->getDeclName())
2374           NameCategoryMap[Cat->getDeclName()] = Cat;
2375 
2376         // Keep track of the tail of the category list.
2377         Tail = Cat;
2378       }
2379     }
2380 
2381     static bool visit(ModuleFile &M, void *UserData) {
2382       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2383     }
2384 
2385     bool visit(ModuleFile &M) {
2386       // If we've loaded all of the category information we care about from
2387       // this module file, we're done.
2388       if (M.Generation <= PreviousGeneration)
2389         return true;
2390 
2391       // Map global ID of the definition down to the local ID used in this
2392       // module file. If there is no such mapping, we'll find nothing here
2393       // (or in any module it imports).
2394       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2395       if (!LocalID)
2396         return true;
2397 
2398       // Perform a binary search to find the local redeclarations for this
2399       // declaration (if any).
2400       const ObjCCategoriesInfo *Result
2401         = std::lower_bound(M.ObjCCategoriesMap,
2402                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2403                            LocalID, CompareObjCCategoriesInfo());
2404       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2405           Result->DefinitionID != LocalID) {
2406         // We didn't find anything. If the class definition is in this module
2407         // file, then the module files it depends on cannot have any categories,
2408         // so suppress further lookup.
2409         return Reader.isDeclIDFromModule(InterfaceID, M);
2410       }
2411 
2412       // We found something. Dig out all of the categories.
2413       unsigned Offset = Result->Offset;
2414       unsigned N = M.ObjCCategories[Offset];
2415       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2416       for (unsigned I = 0; I != N; ++I)
2417         add(cast_or_null<ObjCCategoryDecl>(
2418               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2419       return true;
2420     }
2421   };
2422 }
2423 
2424 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2425                                    ObjCInterfaceDecl *D,
2426                                    unsigned PreviousGeneration) {
2427   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2428                                 PreviousGeneration);
2429   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2430 }
2431 
2432 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2433                                const RecordData &Record) {
2434   unsigned Idx = 0;
2435   while (Idx < Record.size()) {
2436     switch ((DeclUpdateKind)Record[Idx++]) {
2437     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2438       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2439       break;
2440 
2441     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2442       // It will be added to the template's specializations set when loaded.
2443       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2444       break;
2445 
2446     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2447       NamespaceDecl *Anon
2448         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2449 
2450       // Each module has its own anonymous namespace, which is disjoint from
2451       // any other module's anonymous namespaces, so don't attach the anonymous
2452       // namespace at all.
2453       if (ModuleFile.Kind != MK_Module) {
2454         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2455           TU->setAnonymousNamespace(Anon);
2456         else
2457           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2458       }
2459       break;
2460     }
2461 
2462     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2463       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2464           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2465       break;
2466     }
2467   }
2468 }
2469