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