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->setType(GetTypeSourceInfo(Record, Idx));
805   // FIXME: stable encoding
806   D->setPropertyAttributes(
807                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
808   D->setPropertyAttributesAsWritten(
809                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
810   // FIXME: stable encoding
811   D->setPropertyImplementation(
812                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
813   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
814   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
815   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
816   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
817   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
818 }
819 
820 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
821   VisitObjCContainerDecl(D);
822   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
823 }
824 
825 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
826   VisitObjCImplDecl(D);
827   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
828   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
829 }
830 
831 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
832   VisitObjCImplDecl(D);
833   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
834   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
835   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
836   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
837       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
838   D->setHasSynthBitfield(Record[Idx++]);
839 }
840 
841 
842 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
843   VisitDecl(D);
844   D->setAtLoc(ReadSourceLocation(Record, Idx));
845   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
846   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
847   D->IvarLoc = ReadSourceLocation(Record, Idx);
848   D->setGetterCXXConstructor(Reader.ReadExpr(F));
849   D->setSetterCXXAssignment(Reader.ReadExpr(F));
850 }
851 
852 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
853   VisitDeclaratorDecl(FD);
854   FD->setMutable(Record[Idx++]);
855   int BitWidthOrInitializer = Record[Idx++];
856   if (BitWidthOrInitializer == 1)
857     FD->setBitWidth(Reader.ReadExpr(F));
858   else if (BitWidthOrInitializer == 2)
859     FD->setInClassInitializer(Reader.ReadExpr(F));
860   if (!FD->getDeclName()) {
861     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
862       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
863   }
864 }
865 
866 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
867   VisitValueDecl(FD);
868 
869   FD->ChainingSize = Record[Idx++];
870   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
871   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
872 
873   for (unsigned I = 0; I != FD->ChainingSize; ++I)
874     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
875 }
876 
877 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
878   RedeclarableResult Redecl = VisitRedeclarable(VD);
879   VisitDeclaratorDecl(VD);
880 
881   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
882   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
883   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
884   VD->VarDeclBits.InitStyle = Record[Idx++];
885   VD->VarDeclBits.ExceptionVar = Record[Idx++];
886   VD->VarDeclBits.NRVOVariable = Record[Idx++];
887   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
888   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
889 
890   // Only true variables (not parameters or implicit parameters) can be merged.
891   if (VD->getKind() == Decl::Var)
892     mergeRedeclarable(VD, Redecl);
893 
894   if (uint64_t Val = Record[Idx++]) {
895     VD->setInit(Reader.ReadExpr(F));
896     if (Val > 1) {
897       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
898       Eval->CheckedICE = true;
899       Eval->IsICE = Val == 3;
900     }
901   }
902 
903   if (Record[Idx++]) { // HasMemberSpecializationInfo.
904     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
905     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
906     SourceLocation POI = ReadSourceLocation(Record, Idx);
907     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
908   }
909 }
910 
911 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
912   VisitVarDecl(PD);
913 }
914 
915 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
916   VisitVarDecl(PD);
917   unsigned isObjCMethodParam = Record[Idx++];
918   unsigned scopeDepth = Record[Idx++];
919   unsigned scopeIndex = Record[Idx++];
920   unsigned declQualifier = Record[Idx++];
921   if (isObjCMethodParam) {
922     assert(scopeDepth == 0);
923     PD->setObjCMethodScopeInfo(scopeIndex);
924     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
925   } else {
926     PD->setScopeInfo(scopeDepth, scopeIndex);
927   }
928   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
929   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
930   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
931     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
932 }
933 
934 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
935   VisitDecl(AD);
936   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
937   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
938 }
939 
940 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
941   VisitDecl(BD);
942   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
943   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
944   unsigned NumParams = Record[Idx++];
945   SmallVector<ParmVarDecl *, 16> Params;
946   Params.reserve(NumParams);
947   for (unsigned I = 0; I != NumParams; ++I)
948     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
949   BD->setParams(Params);
950 
951   bool capturesCXXThis = Record[Idx++];
952   unsigned numCaptures = Record[Idx++];
953   SmallVector<BlockDecl::Capture, 16> captures;
954   captures.reserve(numCaptures);
955   for (unsigned i = 0; i != numCaptures; ++i) {
956     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
957     unsigned flags = Record[Idx++];
958     bool byRef = (flags & 1);
959     bool nested = (flags & 2);
960     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
961 
962     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
963   }
964   BD->setCaptures(Reader.getContext(), captures.begin(),
965                   captures.end(), capturesCXXThis);
966 }
967 
968 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
969   VisitDecl(D);
970   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
971   D->setExternLoc(ReadSourceLocation(Record, Idx));
972   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
973 }
974 
975 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
976   VisitNamedDecl(D);
977   D->setLocStart(ReadSourceLocation(Record, Idx));
978 }
979 
980 
981 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
982   RedeclarableResult Redecl = VisitRedeclarable(D);
983   VisitNamedDecl(D);
984   D->setInline(Record[Idx++]);
985   D->LocStart = ReadSourceLocation(Record, Idx);
986   D->RBraceLoc = ReadSourceLocation(Record, Idx);
987   mergeRedeclarable(D, Redecl);
988 
989   if (Redecl.getFirstID() == ThisDeclID) {
990     // Each module has its own anonymous namespace, which is disjoint from
991     // any other module's anonymous namespaces, so don't attach the anonymous
992     // namespace at all.
993     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
994     if (F.Kind != MK_Module)
995       D->setAnonymousNamespace(Anon);
996   } else {
997     // Link this namespace back to the first declaration, which has already
998     // been deserialized.
999     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
1000   }
1001 }
1002 
1003 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1004   VisitNamedDecl(D);
1005   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1006   D->IdentLoc = ReadSourceLocation(Record, Idx);
1007   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1008   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1009 }
1010 
1011 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1012   VisitNamedDecl(D);
1013   D->setUsingLocation(ReadSourceLocation(Record, Idx));
1014   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1015   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1016   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1017   D->setTypeName(Record[Idx++]);
1018   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1019     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1020 }
1021 
1022 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1023   VisitNamedDecl(D);
1024   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1025   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1026   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1027   if (Pattern)
1028     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1029 }
1030 
1031 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1032   VisitNamedDecl(D);
1033   D->UsingLoc = ReadSourceLocation(Record, Idx);
1034   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1035   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1036   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1037   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1038 }
1039 
1040 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1041   VisitValueDecl(D);
1042   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1043   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1044   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1045 }
1046 
1047 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1048                                                UnresolvedUsingTypenameDecl *D) {
1049   VisitTypeDecl(D);
1050   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1051   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1052 }
1053 
1054 void ASTDeclReader::ReadCXXDefinitionData(
1055                                    struct CXXRecordDecl::DefinitionData &Data,
1056                                    const RecordData &Record, unsigned &Idx) {
1057   // Note: the caller has deserialized the IsLambda bit already.
1058   Data.UserDeclaredConstructor = Record[Idx++];
1059   Data.UserDeclaredCopyConstructor = Record[Idx++];
1060   Data.UserDeclaredMoveConstructor = Record[Idx++];
1061   Data.UserDeclaredCopyAssignment = Record[Idx++];
1062   Data.UserDeclaredMoveAssignment = Record[Idx++];
1063   Data.UserDeclaredDestructor = Record[Idx++];
1064   Data.Aggregate = Record[Idx++];
1065   Data.PlainOldData = Record[Idx++];
1066   Data.Empty = Record[Idx++];
1067   Data.Polymorphic = Record[Idx++];
1068   Data.Abstract = Record[Idx++];
1069   Data.IsStandardLayout = Record[Idx++];
1070   Data.HasNoNonEmptyBases = Record[Idx++];
1071   Data.HasPrivateFields = Record[Idx++];
1072   Data.HasProtectedFields = Record[Idx++];
1073   Data.HasPublicFields = Record[Idx++];
1074   Data.HasMutableFields = Record[Idx++];
1075   Data.HasTrivialDefaultConstructor = Record[Idx++];
1076   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1077   Data.HasTrivialCopyConstructor = Record[Idx++];
1078   Data.HasTrivialMoveConstructor = Record[Idx++];
1079   Data.HasTrivialCopyAssignment = Record[Idx++];
1080   Data.HasTrivialMoveAssignment = Record[Idx++];
1081   Data.HasTrivialDestructor = Record[Idx++];
1082   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1083   Data.ComputedVisibleConversions = Record[Idx++];
1084   Data.UserProvidedDefaultConstructor = Record[Idx++];
1085   Data.DeclaredDefaultConstructor = Record[Idx++];
1086   Data.DeclaredCopyConstructor = Record[Idx++];
1087   Data.DeclaredMoveConstructor = Record[Idx++];
1088   Data.DeclaredCopyAssignment = Record[Idx++];
1089   Data.DeclaredMoveAssignment = Record[Idx++];
1090   Data.DeclaredDestructor = Record[Idx++];
1091   Data.FailedImplicitMoveConstructor = Record[Idx++];
1092   Data.FailedImplicitMoveAssignment = Record[Idx++];
1093 
1094   Data.NumBases = Record[Idx++];
1095   if (Data.NumBases)
1096     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1097   Data.NumVBases = Record[Idx++];
1098   if (Data.NumVBases)
1099     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1100 
1101   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1102   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1103   assert(Data.Definition && "Data.Definition should be already set!");
1104   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
1105 
1106   if (Data.IsLambda) {
1107     typedef LambdaExpr::Capture Capture;
1108     CXXRecordDecl::LambdaDefinitionData &Lambda
1109       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1110     Lambda.NumCaptures = Record[Idx++];
1111     Lambda.NumExplicitCaptures = Record[Idx++];
1112     Lambda.ManglingNumber = Record[Idx++];
1113     Lambda.ContextDecl = ReadDecl(Record, Idx);
1114     Lambda.Captures
1115       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1116     Capture *ToCapture = Lambda.Captures;
1117     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1118       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1119       bool IsImplicit = Record[Idx++];
1120       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1121       VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1122       SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1123       *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1124     }
1125   }
1126 }
1127 
1128 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
1129   VisitRecordDecl(D);
1130 
1131   ASTContext &C = Reader.getContext();
1132   if (Record[Idx++]) {
1133     // Determine whether this is a lambda closure type, so that we can
1134     // allocate the appropriate DefinitionData structure.
1135     bool IsLambda = Record[Idx++];
1136     if (IsLambda)
1137       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D);
1138     else
1139       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1140 
1141     // Propagate the DefinitionData pointer to the canonical declaration, so
1142     // that all other deserialized declarations will see it.
1143     // FIXME: Complain if there already is a DefinitionData!
1144     D->getCanonicalDecl()->DefinitionData = D->DefinitionData;
1145 
1146     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1147 
1148     // Note that we have deserialized a definition. Any declarations
1149     // deserialized before this one will be be given the DefinitionData pointer
1150     // at the end.
1151     Reader.PendingDefinitions.insert(D);
1152   } else {
1153     // Propagate DefinitionData pointer from the canonical declaration.
1154     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1155   }
1156 
1157   enum CXXRecKind {
1158     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1159   };
1160   switch ((CXXRecKind)Record[Idx++]) {
1161   case CXXRecNotTemplate:
1162     break;
1163   case CXXRecTemplate:
1164     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1165     break;
1166   case CXXRecMemberSpecialization: {
1167     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1168     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1169     SourceLocation POI = ReadSourceLocation(Record, Idx);
1170     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1171     MSI->setPointOfInstantiation(POI);
1172     D->TemplateOrInstantiation = MSI;
1173     break;
1174   }
1175   }
1176 
1177   // Load the key function to avoid deserializing every method so we can
1178   // compute it.
1179   if (D->IsCompleteDefinition) {
1180     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1181       C.KeyFunctions[D] = Key;
1182   }
1183 }
1184 
1185 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1186   VisitFunctionDecl(D);
1187   unsigned NumOverridenMethods = Record[Idx++];
1188   while (NumOverridenMethods--) {
1189     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1190     // MD may be initializing.
1191     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1192       Reader.getContext().addOverriddenMethod(D, MD);
1193   }
1194 }
1195 
1196 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1197   VisitCXXMethodDecl(D);
1198 
1199   D->IsExplicitSpecified = Record[Idx++];
1200   D->ImplicitlyDefined = Record[Idx++];
1201   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1202       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1203 }
1204 
1205 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1206   VisitCXXMethodDecl(D);
1207 
1208   D->ImplicitlyDefined = Record[Idx++];
1209   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1210 }
1211 
1212 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1213   VisitCXXMethodDecl(D);
1214   D->IsExplicitSpecified = Record[Idx++];
1215   if (D->isLambdaToBlockPointerConversion())
1216     D->setLambdaToBlockPointerCopyInit(Reader.ReadExpr(F));
1217 }
1218 
1219 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1220   VisitDecl(D);
1221   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1222   D->ImportedAndComplete.setInt(Record[Idx++]);
1223   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1224   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1225     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1226   ++Idx;
1227 }
1228 
1229 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1230   VisitDecl(D);
1231   D->setColonLoc(ReadSourceLocation(Record, Idx));
1232 }
1233 
1234 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1235   VisitDecl(D);
1236   if (Record[Idx++])
1237     D->Friend = GetTypeSourceInfo(Record, Idx);
1238   else
1239     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1240   D->NextFriend = Record[Idx++];
1241   D->UnsupportedFriend = (Record[Idx++] != 0);
1242   D->FriendLoc = ReadSourceLocation(Record, Idx);
1243 }
1244 
1245 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1246   VisitDecl(D);
1247   unsigned NumParams = Record[Idx++];
1248   D->NumParams = NumParams;
1249   D->Params = new TemplateParameterList*[NumParams];
1250   for (unsigned i = 0; i != NumParams; ++i)
1251     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1252   if (Record[Idx++]) // HasFriendDecl
1253     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1254   else
1255     D->Friend = GetTypeSourceInfo(Record, Idx);
1256   D->FriendLoc = ReadSourceLocation(Record, Idx);
1257 }
1258 
1259 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1260   VisitNamedDecl(D);
1261 
1262   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1263   TemplateParameterList* TemplateParams
1264       = Reader.ReadTemplateParameterList(F, Record, Idx);
1265   D->init(TemplatedDecl, TemplateParams);
1266 }
1267 
1268 ASTDeclReader::RedeclarableResult
1269 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1270   RedeclarableResult Redecl = VisitRedeclarable(D);
1271 
1272   // Make sure we've allocated the Common pointer first. We do this before
1273   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1274   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1275   if (!CanonD->Common) {
1276     CanonD->Common = CanonD->newCommon(Reader.getContext());
1277     Reader.PendingDefinitions.insert(CanonD);
1278   }
1279   D->Common = CanonD->Common;
1280 
1281   // If this is the first declaration of the template, fill in the information
1282   // for the 'common' pointer.
1283   if (ThisDeclID == Redecl.getFirstID()) {
1284     if (RedeclarableTemplateDecl *RTD
1285           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1286       assert(RTD->getKind() == D->getKind() &&
1287              "InstantiatedFromMemberTemplate kind mismatch");
1288       D->setInstantiatedFromMemberTemplate(RTD);
1289       if (Record[Idx++])
1290         D->setMemberSpecialization();
1291     }
1292   }
1293 
1294   VisitTemplateDecl(D);
1295   D->IdentifierNamespace = Record[Idx++];
1296 
1297   return Redecl;
1298 }
1299 
1300 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1301   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1302 
1303   if (ThisDeclID == Redecl.getFirstID()) {
1304     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1305     // the specializations.
1306     SmallVector<serialization::DeclID, 2> SpecIDs;
1307     SpecIDs.push_back(0);
1308 
1309     // Specializations.
1310     unsigned Size = Record[Idx++];
1311     SpecIDs[0] += Size;
1312     for (unsigned I = 0; I != Size; ++I)
1313       SpecIDs.push_back(ReadDeclID(Record, Idx));
1314 
1315     // Partial specializations.
1316     Size = Record[Idx++];
1317     SpecIDs[0] += Size;
1318     for (unsigned I = 0; I != Size; ++I)
1319       SpecIDs.push_back(ReadDeclID(Record, Idx));
1320 
1321     if (SpecIDs[0]) {
1322       typedef serialization::DeclID DeclID;
1323 
1324       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1325       // FIXME: Append specializations!
1326       CommonPtr->LazySpecializations
1327         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1328       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1329              SpecIDs.size() * sizeof(DeclID));
1330     }
1331 
1332     // InjectedClassNameType is computed.
1333   }
1334 }
1335 
1336 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1337                                            ClassTemplateSpecializationDecl *D) {
1338   VisitCXXRecordDecl(D);
1339 
1340   ASTContext &C = Reader.getContext();
1341   if (Decl *InstD = ReadDecl(Record, Idx)) {
1342     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1343       D->SpecializedTemplate = CTD;
1344     } else {
1345       SmallVector<TemplateArgument, 8> TemplArgs;
1346       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1347       TemplateArgumentList *ArgList
1348         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1349                                            TemplArgs.size());
1350       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1351           = new (C) ClassTemplateSpecializationDecl::
1352                                              SpecializedPartialSpecialization();
1353       PS->PartialSpecialization
1354           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1355       PS->TemplateArgs = ArgList;
1356       D->SpecializedTemplate = PS;
1357     }
1358   }
1359 
1360   // Explicit info.
1361   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1362     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1363         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1364     ExplicitInfo->TypeAsWritten = TyInfo;
1365     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1366     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1367     D->ExplicitInfo = ExplicitInfo;
1368   }
1369 
1370   SmallVector<TemplateArgument, 8> TemplArgs;
1371   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1372   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1373                                                      TemplArgs.size());
1374   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1375   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1376 
1377   if (D->isCanonicalDecl()) { // It's kept in the folding set.
1378     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1379     if (ClassTemplatePartialSpecializationDecl *Partial
1380                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1381       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
1382     } else {
1383       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
1384     }
1385   }
1386 }
1387 
1388 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1389                                     ClassTemplatePartialSpecializationDecl *D) {
1390   VisitClassTemplateSpecializationDecl(D);
1391 
1392   ASTContext &C = Reader.getContext();
1393   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1394 
1395   unsigned NumArgs = Record[Idx++];
1396   if (NumArgs) {
1397     D->NumArgsAsWritten = NumArgs;
1398     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1399     for (unsigned i=0; i != NumArgs; ++i)
1400       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1401   }
1402 
1403   D->SequenceNumber = Record[Idx++];
1404 
1405   // These are read/set from/to the first declaration.
1406   if (D->getPreviousDecl() == 0) {
1407     D->InstantiatedFromMember.setPointer(
1408       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1409     D->InstantiatedFromMember.setInt(Record[Idx++]);
1410   }
1411 }
1412 
1413 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1414                                     ClassScopeFunctionSpecializationDecl *D) {
1415   VisitDecl(D);
1416   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1417 }
1418 
1419 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1420   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1421 
1422   if (ThisDeclID == Redecl.getFirstID()) {
1423     // This FunctionTemplateDecl owns a CommonPtr; read it.
1424 
1425     // Read the function specialization declarations.
1426     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1427     // when reading the specialized FunctionDecl.
1428     unsigned NumSpecs = Record[Idx++];
1429     while (NumSpecs--)
1430       (void)ReadDecl(Record, Idx);
1431   }
1432 }
1433 
1434 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1435   VisitTypeDecl(D);
1436 
1437   D->setDeclaredWithTypename(Record[Idx++]);
1438 
1439   bool Inherited = Record[Idx++];
1440   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1441   D->setDefaultArgument(DefArg, Inherited);
1442 }
1443 
1444 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1445   VisitDeclaratorDecl(D);
1446   // TemplateParmPosition.
1447   D->setDepth(Record[Idx++]);
1448   D->setPosition(Record[Idx++]);
1449   if (D->isExpandedParameterPack()) {
1450     void **Data = reinterpret_cast<void **>(D + 1);
1451     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1452       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1453       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1454     }
1455   } else {
1456     // Rest of NonTypeTemplateParmDecl.
1457     D->ParameterPack = Record[Idx++];
1458     if (Record[Idx++]) {
1459       Expr *DefArg = Reader.ReadExpr(F);
1460       bool Inherited = Record[Idx++];
1461       D->setDefaultArgument(DefArg, Inherited);
1462    }
1463   }
1464 }
1465 
1466 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1467   VisitTemplateDecl(D);
1468   // TemplateParmPosition.
1469   D->setDepth(Record[Idx++]);
1470   D->setPosition(Record[Idx++]);
1471   // Rest of TemplateTemplateParmDecl.
1472   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1473   bool IsInherited = Record[Idx++];
1474   D->setDefaultArgument(Arg, IsInherited);
1475   D->ParameterPack = Record[Idx++];
1476 }
1477 
1478 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1479   VisitRedeclarableTemplateDecl(D);
1480 }
1481 
1482 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1483   VisitDecl(D);
1484   D->AssertExpr = Reader.ReadExpr(F);
1485   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1486   D->RParenLoc = ReadSourceLocation(Record, Idx);
1487 }
1488 
1489 std::pair<uint64_t, uint64_t>
1490 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1491   uint64_t LexicalOffset = Record[Idx++];
1492   uint64_t VisibleOffset = Record[Idx++];
1493   return std::make_pair(LexicalOffset, VisibleOffset);
1494 }
1495 
1496 template <typename T>
1497 ASTDeclReader::RedeclarableResult
1498 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1499   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1500 
1501   // 0 indicates that this declaration was the only declaration of its entity,
1502   // and is used for space optimization.
1503   if (FirstDeclID == 0)
1504     FirstDeclID = ThisDeclID;
1505 
1506   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1507   if (FirstDecl != D) {
1508     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1509     // We temporarily set the first (canonical) declaration as the previous one
1510     // which is the one that matters and mark the real previous DeclID to be
1511     // loaded & attached later on.
1512     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(FirstDecl);
1513   }
1514 
1515   // Note that this declaration has been deserialized.
1516   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1517 
1518   // The result structure takes care to note that we need to load the
1519   // other declaration chains for this ID.
1520   return RedeclarableResult(Reader, FirstDeclID);
1521 }
1522 
1523 /// \brief Attempts to merge the given declaration (D) with another declaration
1524 /// of the same entity.
1525 template<typename T>
1526 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1527                                       RedeclarableResult &Redecl) {
1528   // If modules are not available, there is no reason to perform this merge.
1529   if (!Reader.getContext().getLangOptions().Modules)
1530     return;
1531 
1532   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
1533     if (T *Existing = ExistingRes) {
1534       T *ExistingCanon = Existing->getCanonicalDecl();
1535       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1536       if (ExistingCanon != DCanon) {
1537         // Have our redeclaration link point back at the canonical declaration
1538         // of the existing declaration, so that this declaration has the
1539         // appropriate canonical declaration.
1540         D->RedeclLink
1541           = typename Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1542 
1543         // When we merge a namespace, update its pointer to the first namespace.
1544         if (NamespaceDecl *Namespace
1545               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1546           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1547             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1548         }
1549 
1550         // Don't introduce DCanon into the set of pending declaration chains.
1551         Redecl.suppress();
1552 
1553         // Introduce ExistingCanon into the set of pending declaration chains,
1554         // if in fact it came from a module file.
1555         if (ExistingCanon->isFromASTFile()) {
1556           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1557           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1558           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1559             Reader.PendingDeclChains.push_back(ExistingCanonID);
1560         }
1561 
1562         // If this declaration was the canonical declaration, make a note of
1563         // that. We accept the linear algorithm here because the number of
1564         // unique canonical declarations of an entity should always be tiny.
1565         if (DCanon == static_cast<T*>(D)) {
1566           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1567           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1568                 == Merged.end())
1569             Merged.push_back(Redecl.getFirstID());
1570 
1571           // If ExistingCanon did not come from a module file, introduce the
1572           // first declaration that *does* come from a module file to the
1573           // set of pending declaration chains, so that we merge this
1574           // declaration.
1575           if (!ExistingCanon->isFromASTFile() &&
1576               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1577             Reader.PendingDeclChains.push_back(Merged[0]);
1578         }
1579       }
1580     }
1581   }
1582 }
1583 
1584 //===----------------------------------------------------------------------===//
1585 // Attribute Reading
1586 //===----------------------------------------------------------------------===//
1587 
1588 /// \brief Reads attributes from the current stream position.
1589 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1590                                const RecordData &Record, unsigned &Idx) {
1591   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1592     Attr *New = 0;
1593     attr::Kind Kind = (attr::Kind)Record[Idx++];
1594     SourceRange Range = ReadSourceRange(F, Record, Idx);
1595 
1596 #include "clang/Serialization/AttrPCHRead.inc"
1597 
1598     assert(New && "Unable to decode attribute?");
1599     Attrs.push_back(New);
1600   }
1601 }
1602 
1603 //===----------------------------------------------------------------------===//
1604 // ASTReader Implementation
1605 //===----------------------------------------------------------------------===//
1606 
1607 /// \brief Note that we have loaded the declaration with the given
1608 /// Index.
1609 ///
1610 /// This routine notes that this declaration has already been loaded,
1611 /// so that future GetDecl calls will return this declaration rather
1612 /// than trying to load a new declaration.
1613 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1614   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1615   DeclsLoaded[Index] = D;
1616 }
1617 
1618 
1619 /// \brief Determine whether the consumer will be interested in seeing
1620 /// this declaration (via HandleTopLevelDecl).
1621 ///
1622 /// This routine should return true for anything that might affect
1623 /// code generation, e.g., inline function definitions, Objective-C
1624 /// declarations with metadata, etc.
1625 static bool isConsumerInterestedIn(Decl *D) {
1626   // An ObjCMethodDecl is never considered as "interesting" because its
1627   // implementation container always is.
1628 
1629   if (isa<FileScopeAsmDecl>(D) ||
1630       isa<ObjCProtocolDecl>(D) ||
1631       isa<ObjCImplDecl>(D))
1632     return true;
1633   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1634     return Var->isFileVarDecl() &&
1635            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1636   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1637     return Func->doesThisDeclarationHaveABody();
1638 
1639   return false;
1640 }
1641 
1642 /// \brief Get the correct cursor and offset for loading a declaration.
1643 ASTReader::RecordLocation
1644 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1645   // See if there's an override.
1646   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1647   if (It != ReplacedDecls.end()) {
1648     RawLocation = It->second.RawLoc;
1649     return RecordLocation(It->second.Mod, It->second.Offset);
1650   }
1651 
1652   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1653   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1654   ModuleFile *M = I->second;
1655   const DeclOffset &
1656     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1657   RawLocation = DOffs.Loc;
1658   return RecordLocation(M, DOffs.BitOffset);
1659 }
1660 
1661 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1662   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
1663     = GlobalBitOffsetsMap.find(GlobalOffset);
1664 
1665   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1666   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1667 }
1668 
1669 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
1670   return LocalOffset + M.GlobalBitOffset;
1671 }
1672 
1673 /// \brief Determine whether the two declarations refer to the same entity.
1674 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
1675   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
1676 
1677   if (X == Y)
1678     return true;
1679 
1680   // Must be in the same context.
1681   if (!X->getDeclContext()->getRedeclContext()->Equals(
1682          Y->getDeclContext()->getRedeclContext()))
1683     return false;
1684 
1685   // Two typedefs refer to the same entity if they have the same underlying
1686   // type.
1687   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
1688     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
1689       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
1690                                             TypedefY->getUnderlyingType());
1691 
1692   // Must have the same kind.
1693   if (X->getKind() != Y->getKind())
1694     return false;
1695 
1696   // Objective-C classes and protocols with the same name always match.
1697   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
1698     return true;
1699 
1700   // Compatible tags match.
1701   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
1702     TagDecl *TagY = cast<TagDecl>(Y);
1703     return (TagX->getTagKind() == TagY->getTagKind()) ||
1704       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class) &&
1705        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class));
1706   }
1707 
1708   // Functions with the same type and linkage match.
1709   // FIXME: This needs to cope with function templates, merging of
1710   //prototyped/non-prototyped functions, etc.
1711   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
1712     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
1713     return (FuncX->getLinkage() == FuncY->getLinkage()) &&
1714       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
1715   }
1716 
1717   // Variables with the same type and linkage match.
1718   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
1719     VarDecl *VarY = cast<VarDecl>(Y);
1720     return (VarX->getLinkage() == VarY->getLinkage()) &&
1721       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
1722   }
1723 
1724   // Namespaces with the same name and inlinedness match.
1725   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
1726     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
1727     return NamespaceX->isInline() == NamespaceY->isInline();
1728   }
1729 
1730   // FIXME: Many other cases to implement.
1731   return false;
1732 }
1733 
1734 ASTDeclReader::FindExistingResult::~FindExistingResult() {
1735   if (!AddResult || Existing)
1736     return;
1737 
1738   DeclContext *DC = New->getDeclContext()->getRedeclContext();
1739   if (DC->isTranslationUnit() && Reader.SemaObj) {
1740     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
1741   } else if (DC->isNamespace()) {
1742     DC->addDecl(New);
1743   }
1744 }
1745 
1746 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
1747   DeclarationName Name = D->getDeclName();
1748   if (!Name) {
1749     // Don't bother trying to find unnamed declarations.
1750     FindExistingResult Result(Reader, D, /*Existing=*/0);
1751     Result.suppress();
1752     return Result;
1753   }
1754 
1755   DeclContext *DC = D->getDeclContext()->getRedeclContext();
1756   if (!DC->isFileContext())
1757     return FindExistingResult(Reader);
1758 
1759   if (DC->isTranslationUnit() && Reader.SemaObj) {
1760     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
1761     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1762                                    IEnd = IdResolver.end();
1763          I != IEnd; ++I) {
1764       if (isSameEntity(*I, D))
1765         return FindExistingResult(Reader, D, *I);
1766     }
1767   }
1768 
1769   if (DC->isNamespace()) {
1770     for (DeclContext::lookup_result R = DC->lookup(Name);
1771          R.first != R.second; ++R.first) {
1772       if (isSameEntity(*R.first, D))
1773         return FindExistingResult(Reader, D, *R.first);
1774     }
1775   }
1776 
1777   return FindExistingResult(Reader, D, /*Existing=*/0);
1778 }
1779 
1780 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1781   assert(D && previous);
1782   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1783     TD->RedeclLink.setPointer(cast<TagDecl>(previous));
1784   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1785     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
1786   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1787     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
1788   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1789     TD->RedeclLink.setPointer(cast<TypedefNameDecl>(previous));
1790   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1791     ID->RedeclLink.setPointer(cast<ObjCInterfaceDecl>(previous));
1792   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1793     PD->RedeclLink.setPointer(cast<ObjCProtocolDecl>(previous));
1794   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1795     ND->RedeclLink.setPointer(cast<NamespaceDecl>(previous));
1796   } else {
1797     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1798     TD->RedeclLink.setPointer(cast<RedeclarableTemplateDecl>(previous));
1799   }
1800 }
1801 
1802 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
1803   assert(D && Latest);
1804   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1805     TD->RedeclLink
1806       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
1807   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1808     FD->RedeclLink
1809       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
1810   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1811     VD->RedeclLink
1812       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
1813   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1814     TD->RedeclLink
1815       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
1816                                                 cast<TypedefNameDecl>(Latest));
1817   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1818     ID->RedeclLink
1819       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
1820                                               cast<ObjCInterfaceDecl>(Latest));
1821   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1822     PD->RedeclLink
1823       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
1824                                                 cast<ObjCProtocolDecl>(Latest));
1825   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1826     ND->RedeclLink
1827       = Redeclarable<NamespaceDecl>::LatestDeclLink(
1828                                                    cast<NamespaceDecl>(Latest));
1829   } else {
1830     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1831     TD->RedeclLink
1832       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
1833                                         cast<RedeclarableTemplateDecl>(Latest));
1834   }
1835 }
1836 
1837 ASTReader::MergedDeclsMap::iterator
1838 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
1839   // If we don't have any stored merged declarations, just look in the
1840   // merged declarations set.
1841   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
1842   if (StoredPos == StoredMergedDecls.end())
1843     return MergedDecls.find(Canon);
1844 
1845   // Append the stored merged declarations to the merged declarations set.
1846   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
1847   if (Pos == MergedDecls.end())
1848     Pos = MergedDecls.insert(std::make_pair(Canon,
1849                                             SmallVector<DeclID, 2>())).first;
1850   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
1851   StoredMergedDecls.erase(StoredPos);
1852 
1853   // Sort and uniquify the set of merged declarations.
1854   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
1855   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
1856                     Pos->second.end());
1857   return Pos;
1858 }
1859 
1860 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1861   Decl *previous = GetDecl(ID);
1862   ASTDeclReader::attachPreviousDecl(D, previous);
1863 }
1864 
1865 /// \brief Read the declaration at the given offset from the AST file.
1866 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1867   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1868   unsigned RawLocation = 0;
1869   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1870   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1871   // Keep track of where we are in the stream, then jump back there
1872   // after reading this declaration.
1873   SavedStreamPosition SavedPosition(DeclsCursor);
1874 
1875   ReadingKindTracker ReadingKind(Read_Decl, *this);
1876 
1877   // Note that we are loading a declaration record.
1878   Deserializing ADecl(this);
1879 
1880   DeclsCursor.JumpToBit(Loc.Offset);
1881   RecordData Record;
1882   unsigned Code = DeclsCursor.ReadCode();
1883   unsigned Idx = 0;
1884   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, RawLocation, Record,Idx);
1885 
1886   Decl *D = 0;
1887   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
1888   case DECL_CONTEXT_LEXICAL:
1889   case DECL_CONTEXT_VISIBLE:
1890     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1891   case DECL_TYPEDEF:
1892     D = TypedefDecl::CreateDeserialized(Context, ID);
1893     break;
1894   case DECL_TYPEALIAS:
1895     D = TypeAliasDecl::CreateDeserialized(Context, ID);
1896     break;
1897   case DECL_ENUM:
1898     D = EnumDecl::CreateDeserialized(Context, ID);
1899     break;
1900   case DECL_RECORD:
1901     D = RecordDecl::CreateDeserialized(Context, ID);
1902     break;
1903   case DECL_ENUM_CONSTANT:
1904     D = EnumConstantDecl::CreateDeserialized(Context, ID);
1905     break;
1906   case DECL_FUNCTION:
1907     D = FunctionDecl::CreateDeserialized(Context, ID);
1908     break;
1909   case DECL_LINKAGE_SPEC:
1910     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
1911     break;
1912   case DECL_LABEL:
1913     D = LabelDecl::CreateDeserialized(Context, ID);
1914     break;
1915   case DECL_NAMESPACE:
1916     D = NamespaceDecl::CreateDeserialized(Context, ID);
1917     break;
1918   case DECL_NAMESPACE_ALIAS:
1919     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
1920     break;
1921   case DECL_USING:
1922     D = UsingDecl::CreateDeserialized(Context, ID);
1923     break;
1924   case DECL_USING_SHADOW:
1925     D = UsingShadowDecl::CreateDeserialized(Context, ID);
1926     break;
1927   case DECL_USING_DIRECTIVE:
1928     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
1929     break;
1930   case DECL_UNRESOLVED_USING_VALUE:
1931     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
1932     break;
1933   case DECL_UNRESOLVED_USING_TYPENAME:
1934     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
1935     break;
1936   case DECL_CXX_RECORD:
1937     D = CXXRecordDecl::CreateDeserialized(Context, ID);
1938     break;
1939   case DECL_CXX_METHOD:
1940     D = CXXMethodDecl::CreateDeserialized(Context, ID);
1941     break;
1942   case DECL_CXX_CONSTRUCTOR:
1943     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
1944     break;
1945   case DECL_CXX_DESTRUCTOR:
1946     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
1947     break;
1948   case DECL_CXX_CONVERSION:
1949     D = CXXConversionDecl::CreateDeserialized(Context, ID);
1950     break;
1951   case DECL_ACCESS_SPEC:
1952     D = AccessSpecDecl::CreateDeserialized(Context, ID);
1953     break;
1954   case DECL_FRIEND:
1955     D = FriendDecl::CreateDeserialized(Context, ID);
1956     break;
1957   case DECL_FRIEND_TEMPLATE:
1958     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
1959     break;
1960   case DECL_CLASS_TEMPLATE:
1961     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
1962     break;
1963   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
1964     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
1965     break;
1966   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
1967     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
1968     break;
1969   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
1970     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
1971     break;
1972   case DECL_FUNCTION_TEMPLATE:
1973     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
1974     break;
1975   case DECL_TEMPLATE_TYPE_PARM:
1976     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
1977     break;
1978   case DECL_NON_TYPE_TEMPLATE_PARM:
1979     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
1980     break;
1981   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
1982     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
1983     break;
1984   case DECL_TEMPLATE_TEMPLATE_PARM:
1985     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
1986     break;
1987   case DECL_TYPE_ALIAS_TEMPLATE:
1988     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
1989     break;
1990   case DECL_STATIC_ASSERT:
1991     D = StaticAssertDecl::CreateDeserialized(Context, ID);
1992     break;
1993   case DECL_OBJC_METHOD:
1994     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
1995     break;
1996   case DECL_OBJC_INTERFACE:
1997     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
1998     break;
1999   case DECL_OBJC_IVAR:
2000     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2001     break;
2002   case DECL_OBJC_PROTOCOL:
2003     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2004     break;
2005   case DECL_OBJC_AT_DEFS_FIELD:
2006     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2007     break;
2008   case DECL_OBJC_CATEGORY:
2009     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2010     break;
2011   case DECL_OBJC_CATEGORY_IMPL:
2012     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2013     break;
2014   case DECL_OBJC_IMPLEMENTATION:
2015     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2016     break;
2017   case DECL_OBJC_COMPATIBLE_ALIAS:
2018     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2019     break;
2020   case DECL_OBJC_PROPERTY:
2021     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2022     break;
2023   case DECL_OBJC_PROPERTY_IMPL:
2024     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2025     break;
2026   case DECL_FIELD:
2027     D = FieldDecl::CreateDeserialized(Context, ID);
2028     break;
2029   case DECL_INDIRECTFIELD:
2030     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2031     break;
2032   case DECL_VAR:
2033     D = VarDecl::CreateDeserialized(Context, ID);
2034     break;
2035   case DECL_IMPLICIT_PARAM:
2036     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2037     break;
2038   case DECL_PARM_VAR:
2039     D = ParmVarDecl::CreateDeserialized(Context, ID);
2040     break;
2041   case DECL_FILE_SCOPE_ASM:
2042     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2043     break;
2044   case DECL_BLOCK:
2045     D = BlockDecl::CreateDeserialized(Context, ID);
2046     break;
2047   case DECL_CXX_BASE_SPECIFIERS:
2048     Error("attempt to read a C++ base-specifier record as a declaration");
2049     return 0;
2050   case DECL_IMPORT:
2051     // Note: last entry of the ImportDecl record is the number of stored source
2052     // locations.
2053     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2054     break;
2055   }
2056 
2057   assert(D && "Unknown declaration reading AST file");
2058   LoadedDecl(Index, D);
2059   // Set the DeclContext before doing any deserialization, to make sure internal
2060   // calls to Decl::getASTContext() by Decl's methods will find the
2061   // TranslationUnitDecl without crashing.
2062   D->setDeclContext(Context.getTranslationUnitDecl());
2063   Reader.Visit(D);
2064 
2065   // If this declaration is also a declaration context, get the
2066   // offsets for its tables of lexical and visible declarations.
2067   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2068     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2069     if (Offsets.first || Offsets.second) {
2070       if (Offsets.first != 0)
2071         DC->setHasExternalLexicalStorage(true);
2072       if (Offsets.second != 0)
2073         DC->setHasExternalVisibleStorage(true);
2074       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2075                                  Loc.F->DeclContextInfos[DC]))
2076         return 0;
2077     }
2078 
2079     // Now add the pending visible updates for this decl context, if it has any.
2080     DeclContextVisibleUpdatesPending::iterator I =
2081         PendingVisibleUpdates.find(ID);
2082     if (I != PendingVisibleUpdates.end()) {
2083       // There are updates. This means the context has external visible
2084       // storage, even if the original stored version didn't.
2085       DC->setHasExternalVisibleStorage(true);
2086       DeclContextVisibleUpdates &U = I->second;
2087       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2088            UI != UE; ++UI) {
2089         UI->second->DeclContextInfos[DC].NameLookupTableData = UI->first;
2090       }
2091       PendingVisibleUpdates.erase(I);
2092     }
2093   }
2094   assert(Idx == Record.size());
2095 
2096   // Load any relevant update records.
2097   loadDeclUpdateRecords(ID, D);
2098 
2099   // Load the categories after recursive loading is finished.
2100   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2101     if (Class->isThisDeclarationADefinition())
2102       loadObjCCategories(ID, Class);
2103 
2104   // If we have deserialized a declaration that has a definition the
2105   // AST consumer might need to know about, queue it.
2106   // We don't pass it to the consumer immediately because we may be in recursive
2107   // loading, and some declarations may still be initializing.
2108   if (isConsumerInterestedIn(D))
2109     InterestingDecls.push_back(D);
2110 
2111   return D;
2112 }
2113 
2114 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2115   // The declaration may have been modified by files later in the chain.
2116   // If this is the case, read the record containing the updates from each file
2117   // and pass it to ASTDeclReader to make the modifications.
2118   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2119   if (UpdI != DeclUpdateOffsets.end()) {
2120     FileOffsetsTy &UpdateOffsets = UpdI->second;
2121     for (FileOffsetsTy::iterator
2122          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2123       ModuleFile *F = I->first;
2124       uint64_t Offset = I->second;
2125       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2126       SavedStreamPosition SavedPosition(Cursor);
2127       Cursor.JumpToBit(Offset);
2128       RecordData Record;
2129       unsigned Code = Cursor.ReadCode();
2130       unsigned RecCode = Cursor.ReadRecord(Code, Record);
2131       (void)RecCode;
2132       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2133 
2134       unsigned Idx = 0;
2135       ASTDeclReader Reader(*this, *F, Cursor, ID, 0, Record, Idx);
2136       Reader.UpdateDecl(D, *F, Record);
2137     }
2138   }
2139 }
2140 
2141 namespace {
2142   struct CompareLocalRedeclarationsInfoToID {
2143     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2144       return X.FirstID < Y;
2145     }
2146 
2147     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2148       return X < Y.FirstID;
2149     }
2150 
2151     bool operator()(const LocalRedeclarationsInfo &X,
2152                     const LocalRedeclarationsInfo &Y) {
2153       return X.FirstID < Y.FirstID;
2154     }
2155     bool operator()(DeclID X, DeclID Y) {
2156       return X < Y;
2157     }
2158   };
2159 
2160   /// \brief Module visitor class that finds all of the redeclarations of a
2161   ///
2162   class RedeclChainVisitor {
2163     ASTReader &Reader;
2164     SmallVectorImpl<DeclID> &SearchDecls;
2165     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2166     GlobalDeclID CanonID;
2167     llvm::SmallVector<Decl *, 4> Chain;
2168 
2169   public:
2170     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2171                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2172                        GlobalDeclID CanonID)
2173       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2174         CanonID(CanonID) {
2175       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2176         addToChain(Reader.GetDecl(SearchDecls[I]));
2177     }
2178 
2179     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2180       if (Preorder)
2181         return false;
2182 
2183       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2184     }
2185 
2186     void addToChain(Decl *D) {
2187       if (!D)
2188         return;
2189 
2190       if (Deserialized.count(D)) {
2191         Deserialized.erase(D);
2192         Chain.push_back(D);
2193       }
2194     }
2195 
2196     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2197       // Map global ID of the first declaration down to the local ID
2198       // used in this module file.
2199       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2200       if (!ID)
2201         return;
2202 
2203       // Perform a binary search to find the local redeclarations for this
2204       // declaration (if any).
2205       const LocalRedeclarationsInfo *Result
2206         = std::lower_bound(M.RedeclarationsMap,
2207                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2208                            ID, CompareLocalRedeclarationsInfoToID());
2209       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2210           Result->FirstID != ID) {
2211         // If we have a previously-canonical singleton declaration that was
2212         // merged into another redeclaration chain, create a trivial chain
2213         // for this single declaration so that it will get wired into the
2214         // complete redeclaration chain.
2215         if (GlobalID != CanonID &&
2216             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2217             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2218           addToChain(Reader.GetDecl(GlobalID));
2219         }
2220 
2221         return;
2222       }
2223 
2224       // Dig out all of the redeclarations.
2225       unsigned Offset = Result->Offset;
2226       unsigned N = M.RedeclarationChains[Offset];
2227       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2228       for (unsigned I = 0; I != N; ++I)
2229         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2230     }
2231 
2232     bool visit(ModuleFile &M) {
2233       // Visit each of the declarations.
2234       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2235         searchForID(M, SearchDecls[I]);
2236       return false;
2237     }
2238 
2239     ArrayRef<Decl *> getChain() const {
2240       return Chain;
2241     }
2242   };
2243 }
2244 
2245 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2246   Decl *D = GetDecl(ID);
2247   Decl *CanonDecl = D->getCanonicalDecl();
2248 
2249   // Determine the set of declaration IDs we'll be searching for.
2250   llvm::SmallVector<DeclID, 1> SearchDecls;
2251   GlobalDeclID CanonID = 0;
2252   if (D == CanonDecl) {
2253     SearchDecls.push_back(ID); // Always first.
2254     CanonID = ID;
2255   }
2256   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2257   if (MergedPos != MergedDecls.end())
2258     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2259 
2260   // Build up the list of redeclarations.
2261   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2262   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2263 
2264   // Retrieve the chains.
2265   ArrayRef<Decl *> Chain = Visitor.getChain();
2266   if (Chain.empty())
2267     return;
2268 
2269   // Hook up the chains.
2270   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2271   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2272     if (Chain[I] == CanonDecl)
2273       continue;
2274 
2275     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2276     MostRecent = Chain[I];
2277   }
2278 
2279   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2280 }
2281 
2282 namespace {
2283   struct CompareObjCCategoriesInfo {
2284     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2285       return X.DefinitionID < Y;
2286     }
2287 
2288     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2289       return X < Y.DefinitionID;
2290     }
2291 
2292     bool operator()(const ObjCCategoriesInfo &X,
2293                     const ObjCCategoriesInfo &Y) {
2294       return X.DefinitionID < Y.DefinitionID;
2295     }
2296     bool operator()(DeclID X, DeclID Y) {
2297       return X < Y;
2298     }
2299   };
2300 
2301   /// \brief Given an ObjC interface, goes through the modules and links to the
2302   /// interface all the categories for it.
2303   class ObjCCategoriesVisitor {
2304     ASTReader &Reader;
2305     serialization::GlobalDeclID InterfaceID;
2306     ObjCInterfaceDecl *Interface;
2307     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2308     unsigned PreviousGeneration;
2309     ObjCCategoryDecl *Tail;
2310     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2311 
2312     void add(ObjCCategoryDecl *Cat) {
2313       // Only process each category once.
2314       if (!Deserialized.count(Cat))
2315         return;
2316       Deserialized.erase(Cat);
2317 
2318       // Check for duplicate categories.
2319       if (Cat->getDeclName()) {
2320         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2321         if (Existing &&
2322             Reader.getOwningModuleFile(Existing)
2323                                           != Reader.getOwningModuleFile(Cat)) {
2324           // FIXME: We should not warn for duplicates in diamond:
2325           //
2326           //   MT     //
2327           //  /  \    //
2328           // ML  MR   //
2329           //  \  /    //
2330           //   MB     //
2331           //
2332           // If there are duplicates in ML/MR, there will be warning when
2333           // creating MB *and* when importing MB. We should not warn when
2334           // importing.
2335           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2336             << Interface->getDeclName() << Cat->getDeclName();
2337           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2338         } else if (!Existing) {
2339           // Record this category.
2340           Existing = Cat;
2341         }
2342       }
2343 
2344       // Add this category to the end of the chain.
2345       if (Tail)
2346         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2347       else
2348         Interface->setCategoryList(Cat);
2349       Tail = Cat;
2350     }
2351 
2352   public:
2353     ObjCCategoriesVisitor(ASTReader &Reader,
2354                           serialization::GlobalDeclID InterfaceID,
2355                           ObjCInterfaceDecl *Interface,
2356                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2357                           unsigned PreviousGeneration)
2358       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2359         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2360         Tail(0)
2361     {
2362       // Populate the name -> category map with the set of known categories.
2363       for (ObjCCategoryDecl *Cat = Interface->getCategoryList(); Cat;
2364            Cat = Cat->getNextClassCategory()) {
2365         if (Cat->getDeclName())
2366           NameCategoryMap[Cat->getDeclName()] = Cat;
2367 
2368         // Keep track of the tail of the category list.
2369         Tail = Cat;
2370       }
2371     }
2372 
2373     static bool visit(ModuleFile &M, void *UserData) {
2374       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2375     }
2376 
2377     bool visit(ModuleFile &M) {
2378       // If we've loaded all of the category information we care about from
2379       // this module file, we're done.
2380       if (M.Generation <= PreviousGeneration)
2381         return true;
2382 
2383       // Map global ID of the definition down to the local ID used in this
2384       // module file. If there is no such mapping, we'll find nothing here
2385       // (or in any module it imports).
2386       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2387       if (!LocalID)
2388         return true;
2389 
2390       // Perform a binary search to find the local redeclarations for this
2391       // declaration (if any).
2392       const ObjCCategoriesInfo *Result
2393         = std::lower_bound(M.ObjCCategoriesMap,
2394                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2395                            LocalID, CompareObjCCategoriesInfo());
2396       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2397           Result->DefinitionID != LocalID) {
2398         // We didn't find anything. If the class definition is in this module
2399         // file, then the module files it depends on cannot have any categories,
2400         // so suppress further lookup.
2401         return Reader.isDeclIDFromModule(InterfaceID, M);
2402       }
2403 
2404       // We found something. Dig out all of the categories.
2405       unsigned Offset = Result->Offset;
2406       unsigned N = M.ObjCCategories[Offset];
2407       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2408       for (unsigned I = 0; I != N; ++I)
2409         add(cast_or_null<ObjCCategoryDecl>(
2410               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2411       return true;
2412     }
2413   };
2414 }
2415 
2416 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2417                                    ObjCInterfaceDecl *D,
2418                                    unsigned PreviousGeneration) {
2419   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2420                                 PreviousGeneration);
2421   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2422 }
2423 
2424 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2425                                const RecordData &Record) {
2426   unsigned Idx = 0;
2427   while (Idx < Record.size()) {
2428     switch ((DeclUpdateKind)Record[Idx++]) {
2429     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2430       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2431       break;
2432 
2433     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2434       // It will be added to the template's specializations set when loaded.
2435       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2436       break;
2437 
2438     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2439       NamespaceDecl *Anon
2440         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2441 
2442       // Each module has its own anonymous namespace, which is disjoint from
2443       // any other module's anonymous namespaces, so don't attach the anonymous
2444       // namespace at all.
2445       if (ModuleFile.Kind != MK_Module) {
2446         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2447           TU->setAnonymousNamespace(Anon);
2448         else
2449           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2450       }
2451       break;
2452     }
2453 
2454     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2455       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2456           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2457       break;
2458     }
2459   }
2460 }
2461