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