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