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