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