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