1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
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 //  This file implements C++ template instantiation for declarations.
10 //
11 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/DeclVisitor.h"
17 #include "clang/AST/DependentDiagnostic.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
25 
26 using namespace clang;
27 
28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29                                               DeclaratorDecl *NewDecl) {
30   if (!OldDecl->getQualifierLoc())
31     return false;
32 
33   NestedNameSpecifierLoc NewQualifierLoc
34     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35                                           TemplateArgs);
36 
37   if (!NewQualifierLoc)
38     return true;
39 
40   NewDecl->setQualifierInfo(NewQualifierLoc);
41   return false;
42 }
43 
44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45                                               TagDecl *NewDecl) {
46   if (!OldDecl->getQualifierLoc())
47     return false;
48 
49   NestedNameSpecifierLoc NewQualifierLoc
50   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51                                         TemplateArgs);
52 
53   if (!NewQualifierLoc)
54     return true;
55 
56   NewDecl->setQualifierInfo(NewQualifierLoc);
57   return false;
58 }
59 
60 // Include attribute instantiation code.
61 #include "clang/Sema/AttrTemplateInstantiate.inc"
62 
63 static void instantiateDependentAlignedAttr(
64     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66   if (Aligned->isAlignmentExpr()) {
67     // The alignment expression is a constant expression.
68     EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70     if (!Result.isInvalid())
71       S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72                        Aligned->getSpellingListIndex(), IsPackExpansion);
73   } else {
74     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75                                          TemplateArgs, Aligned->getLocation(),
76                                          DeclarationName());
77     if (Result)
78       S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79                        Aligned->getSpellingListIndex(), IsPackExpansion);
80   }
81 }
82 
83 static void instantiateDependentAlignedAttr(
84     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85     const AlignedAttr *Aligned, Decl *New) {
86   if (!Aligned->isPackExpansion()) {
87     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
88     return;
89   }
90 
91   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92   if (Aligned->isAlignmentExpr())
93     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
94                                       Unexpanded);
95   else
96     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
97                                       Unexpanded);
98   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
99 
100   // Determine whether we can expand this attribute pack yet.
101   bool Expand = true, RetainExpansion = false;
102   Optional<unsigned> NumExpansions;
103   // FIXME: Use the actual location of the ellipsis.
104   SourceLocation EllipsisLoc = Aligned->getLocation();
105   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106                                         Unexpanded, TemplateArgs, Expand,
107                                         RetainExpansion, NumExpansions))
108     return;
109 
110   if (!Expand) {
111     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
113   } else {
114     for (unsigned I = 0; I != *NumExpansions; ++I) {
115       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
117     }
118   }
119 }
120 
121 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
122                             const Decl *Tmpl, Decl *New,
123                             LateInstantiatedAttrVec *LateAttrs,
124                             LocalInstantiationScope *OuterMostScope) {
125   for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
126        i != e; ++i) {
127     const Attr *TmplAttr = *i;
128 
129     // FIXME: This should be generalized to more than just the AlignedAttr.
130     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131     if (Aligned && Aligned->isAlignmentDependent()) {
132       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
133       continue;
134     }
135 
136     assert(!TmplAttr->isPackExpansion());
137     if (TmplAttr->isLateParsed() && LateAttrs) {
138       // Late parsed attributes must be instantiated and attached after the
139       // enclosing class has been instantiated.  See Sema::InstantiateClass.
140       LocalInstantiationScope *Saved = 0;
141       if (CurrentInstantiationScope)
142         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
144     } else {
145       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
146                                                          *this, TemplateArgs);
147       if (NewAttr)
148         New->addAttr(NewAttr);
149     }
150   }
151 }
152 
153 Decl *
154 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
155   llvm_unreachable("Translation units cannot be instantiated");
156 }
157 
158 Decl *
159 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
160   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
161                                       D->getIdentifier());
162   Owner->addDecl(Inst);
163   return Inst;
164 }
165 
166 Decl *
167 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
168   llvm_unreachable("Namespaces cannot be instantiated");
169 }
170 
171 Decl *
172 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
173   NamespaceAliasDecl *Inst
174     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
175                                  D->getNamespaceLoc(),
176                                  D->getAliasLoc(),
177                                  D->getIdentifier(),
178                                  D->getQualifierLoc(),
179                                  D->getTargetNameLoc(),
180                                  D->getNamespace());
181   Owner->addDecl(Inst);
182   return Inst;
183 }
184 
185 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
186                                                            bool IsTypeAlias) {
187   bool Invalid = false;
188   TypeSourceInfo *DI = D->getTypeSourceInfo();
189   if (DI->getType()->isInstantiationDependentType() ||
190       DI->getType()->isVariablyModifiedType()) {
191     DI = SemaRef.SubstType(DI, TemplateArgs,
192                            D->getLocation(), D->getDeclName());
193     if (!DI) {
194       Invalid = true;
195       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
196     }
197   } else {
198     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
199   }
200 
201   // HACK: g++ has a bug where it gets the value kind of ?: wrong.
202   // libstdc++ relies upon this bug in its implementation of common_type.
203   // If we happen to be processing that implementation, fake up the g++ ?:
204   // semantics. See LWG issue 2141 for more information on the bug.
205   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
206   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
207   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
208       DT->isReferenceType() &&
209       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
210       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
211       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
212       SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
213     // Fold it to the (non-reference) type which g++ would have produced.
214     DI = SemaRef.Context.getTrivialTypeSourceInfo(
215       DI->getType().getNonReferenceType());
216 
217   // Create the new typedef
218   TypedefNameDecl *Typedef;
219   if (IsTypeAlias)
220     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
221                                     D->getLocation(), D->getIdentifier(), DI);
222   else
223     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
224                                   D->getLocation(), D->getIdentifier(), DI);
225   if (Invalid)
226     Typedef->setInvalidDecl();
227 
228   // If the old typedef was the name for linkage purposes of an anonymous
229   // tag decl, re-establish that relationship for the new typedef.
230   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
231     TagDecl *oldTag = oldTagType->getDecl();
232     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
233       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
234       assert(!newTag->hasNameForLinkage());
235       newTag->setTypedefNameForAnonDecl(Typedef);
236     }
237   }
238 
239   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
240     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
241                                                        TemplateArgs);
242     if (!InstPrev)
243       return 0;
244 
245     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
246 
247     // If the typedef types are not identical, reject them.
248     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
249 
250     Typedef->setPreviousDeclaration(InstPrevTypedef);
251   }
252 
253   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
254 
255   Typedef->setAccess(D->getAccess());
256 
257   return Typedef;
258 }
259 
260 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
261   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
262   Owner->addDecl(Typedef);
263   return Typedef;
264 }
265 
266 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
267   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
268   Owner->addDecl(Typedef);
269   return Typedef;
270 }
271 
272 Decl *
273 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
274   // Create a local instantiation scope for this type alias template, which
275   // will contain the instantiations of the template parameters.
276   LocalInstantiationScope Scope(SemaRef);
277 
278   TemplateParameterList *TempParams = D->getTemplateParameters();
279   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
280   if (!InstParams)
281     return 0;
282 
283   TypeAliasDecl *Pattern = D->getTemplatedDecl();
284 
285   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
286   if (Pattern->getPreviousDecl()) {
287     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
288     if (!Found.empty()) {
289       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
290     }
291   }
292 
293   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
294     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
295   if (!AliasInst)
296     return 0;
297 
298   TypeAliasTemplateDecl *Inst
299     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
300                                     D->getDeclName(), InstParams, AliasInst);
301   if (PrevAliasTemplate)
302     Inst->setPreviousDeclaration(PrevAliasTemplate);
303 
304   Inst->setAccess(D->getAccess());
305 
306   if (!PrevAliasTemplate)
307     Inst->setInstantiatedFromMemberTemplate(D);
308 
309   Owner->addDecl(Inst);
310 
311   return Inst;
312 }
313 
314 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
315   // If this is the variable for an anonymous struct or union,
316   // instantiate the anonymous struct/union type first.
317   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
318     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
319       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
320         return 0;
321 
322   // Do substitution on the type of the declaration
323   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
324                                          TemplateArgs,
325                                          D->getTypeSpecStartLoc(),
326                                          D->getDeclName());
327   if (!DI)
328     return 0;
329 
330   if (DI->getType()->isFunctionType()) {
331     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
332       << D->isStaticDataMember() << DI->getType();
333     return 0;
334   }
335 
336   // Build the instantiated declaration
337   VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
338                                  D->getInnerLocStart(),
339                                  D->getLocation(), D->getIdentifier(),
340                                  DI->getType(), DI,
341                                  D->getStorageClass());
342   Var->setTSCSpec(D->getTSCSpec());
343   Var->setInitStyle(D->getInitStyle());
344   Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
345   Var->setConstexpr(D->isConstexpr());
346 
347   // Substitute the nested name specifier, if any.
348   if (SubstQualifier(D, Var))
349     return 0;
350 
351   // If we are instantiating a static data member defined
352   // out-of-line, the instantiation will have the same lexical
353   // context (which will be a namespace scope) as the template.
354   if (D->isOutOfLine())
355     Var->setLexicalDeclContext(D->getLexicalDeclContext());
356 
357   Var->setAccess(D->getAccess());
358 
359   if (!D->isStaticDataMember()) {
360     Var->setUsed(D->isUsed(false));
361     Var->setReferenced(D->isReferenced());
362   }
363 
364   SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
365 
366   if (Var->hasAttrs())
367     SemaRef.CheckAlignasUnderalignment(Var);
368 
369   // FIXME: In theory, we could have a previous declaration for variables that
370   // are not static data members.
371   // FIXME: having to fake up a LookupResult is dumb.
372   LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
373                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
374   if (D->isStaticDataMember())
375     SemaRef.LookupQualifiedName(Previous, Owner, false);
376 
377   // In ARC, infer 'retaining' for variables of retainable type.
378   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
379       SemaRef.inferObjCARCLifetime(Var))
380     Var->setInvalidDecl();
381 
382   SemaRef.CheckVariableDeclaration(Var, Previous);
383 
384   if (D->isOutOfLine()) {
385     D->getLexicalDeclContext()->addDecl(Var);
386     Owner->makeDeclVisibleInContext(Var);
387   } else {
388     Owner->addDecl(Var);
389     if (Owner->isFunctionOrMethod())
390       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
391   }
392 
393   // Link instantiations of static data members back to the template from
394   // which they were instantiated.
395   if (Var->isStaticDataMember())
396     SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
397                                                      TSK_ImplicitInstantiation);
398 
399   if (Var->getAnyInitializer()) {
400     // We already have an initializer in the class.
401   } else if (D->getInit()) {
402     if (Var->isStaticDataMember() && !D->isOutOfLine())
403       SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
404     else
405       SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
406 
407     // Instantiate the initializer.
408     ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
409                                         D->getInitStyle() == VarDecl::CallInit);
410     if (!Init.isInvalid()) {
411       bool TypeMayContainAuto = true;
412       if (Init.get()) {
413         bool DirectInit = D->isDirectInit();
414         SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
415                                      TypeMayContainAuto);
416       } else
417         SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
418     } else {
419       // FIXME: Not too happy about invalidating the declaration
420       // because of a bogus initializer.
421       Var->setInvalidDecl();
422     }
423 
424     SemaRef.PopExpressionEvaluationContext();
425   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
426              !Var->isCXXForRangeDecl())
427     SemaRef.ActOnUninitializedDecl(Var, false);
428 
429   // Diagnose unused local variables with dependent types, where the diagnostic
430   // will have been deferred.
431   if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
432       D->getType()->isDependentType())
433     SemaRef.DiagnoseUnusedDecl(Var);
434 
435   return Var;
436 }
437 
438 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
439   AccessSpecDecl* AD
440     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
441                              D->getAccessSpecifierLoc(), D->getColonLoc());
442   Owner->addHiddenDecl(AD);
443   return AD;
444 }
445 
446 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
447   bool Invalid = false;
448   TypeSourceInfo *DI = D->getTypeSourceInfo();
449   if (DI->getType()->isInstantiationDependentType() ||
450       DI->getType()->isVariablyModifiedType())  {
451     DI = SemaRef.SubstType(DI, TemplateArgs,
452                            D->getLocation(), D->getDeclName());
453     if (!DI) {
454       DI = D->getTypeSourceInfo();
455       Invalid = true;
456     } else if (DI->getType()->isFunctionType()) {
457       // C++ [temp.arg.type]p3:
458       //   If a declaration acquires a function type through a type
459       //   dependent on a template-parameter and this causes a
460       //   declaration that does not use the syntactic form of a
461       //   function declarator to have function type, the program is
462       //   ill-formed.
463       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
464         << DI->getType();
465       Invalid = true;
466     }
467   } else {
468     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
469   }
470 
471   Expr *BitWidth = D->getBitWidth();
472   if (Invalid)
473     BitWidth = 0;
474   else if (BitWidth) {
475     // The bit-width expression is a constant expression.
476     EnterExpressionEvaluationContext Unevaluated(SemaRef,
477                                                  Sema::ConstantEvaluated);
478 
479     ExprResult InstantiatedBitWidth
480       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
481     if (InstantiatedBitWidth.isInvalid()) {
482       Invalid = true;
483       BitWidth = 0;
484     } else
485       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
486   }
487 
488   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
489                                             DI->getType(), DI,
490                                             cast<RecordDecl>(Owner),
491                                             D->getLocation(),
492                                             D->isMutable(),
493                                             BitWidth,
494                                             D->getInClassInitStyle(),
495                                             D->getInnerLocStart(),
496                                             D->getAccess(),
497                                             0);
498   if (!Field) {
499     cast<Decl>(Owner)->setInvalidDecl();
500     return 0;
501   }
502 
503   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
504 
505   if (Field->hasAttrs())
506     SemaRef.CheckAlignasUnderalignment(Field);
507 
508   if (Invalid)
509     Field->setInvalidDecl();
510 
511   if (!Field->getDeclName()) {
512     // Keep track of where this decl came from.
513     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
514   }
515   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
516     if (Parent->isAnonymousStructOrUnion() &&
517         Parent->getRedeclContext()->isFunctionOrMethod())
518       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
519   }
520 
521   Field->setImplicit(D->isImplicit());
522   Field->setAccess(D->getAccess());
523   Owner->addDecl(Field);
524 
525   return Field;
526 }
527 
528 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
529   bool Invalid = false;
530   TypeSourceInfo *DI = D->getTypeSourceInfo();
531 
532   if (DI->getType()->isVariablyModifiedType()) {
533     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
534     << D->getName();
535     Invalid = true;
536   } else if (DI->getType()->isInstantiationDependentType())  {
537     DI = SemaRef.SubstType(DI, TemplateArgs,
538                            D->getLocation(), D->getDeclName());
539     if (!DI) {
540       DI = D->getTypeSourceInfo();
541       Invalid = true;
542     } else if (DI->getType()->isFunctionType()) {
543       // C++ [temp.arg.type]p3:
544       //   If a declaration acquires a function type through a type
545       //   dependent on a template-parameter and this causes a
546       //   declaration that does not use the syntactic form of a
547       //   function declarator to have function type, the program is
548       //   ill-formed.
549       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
550       << DI->getType();
551       Invalid = true;
552     }
553   } else {
554     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
555   }
556 
557   MSPropertyDecl *Property = new (SemaRef.Context)
558       MSPropertyDecl(Owner, D->getLocation(),
559                      D->getDeclName(), DI->getType(), DI,
560                      D->getLocStart(),
561                      D->getGetterId(), D->getSetterId());
562 
563   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
564                            StartingScope);
565 
566   if (Invalid)
567     Property->setInvalidDecl();
568 
569   Property->setAccess(D->getAccess());
570   Owner->addDecl(Property);
571 
572   return Property;
573 }
574 
575 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
576   NamedDecl **NamedChain =
577     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
578 
579   int i = 0;
580   for (IndirectFieldDecl::chain_iterator PI =
581        D->chain_begin(), PE = D->chain_end();
582        PI != PE; ++PI) {
583     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
584                                               TemplateArgs);
585     if (!Next)
586       return 0;
587 
588     NamedChain[i++] = Next;
589   }
590 
591   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
592   IndirectFieldDecl* IndirectField
593     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
594                                 D->getIdentifier(), T,
595                                 NamedChain, D->getChainingSize());
596 
597 
598   IndirectField->setImplicit(D->isImplicit());
599   IndirectField->setAccess(D->getAccess());
600   Owner->addDecl(IndirectField);
601   return IndirectField;
602 }
603 
604 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
605   // Handle friend type expressions by simply substituting template
606   // parameters into the pattern type and checking the result.
607   if (TypeSourceInfo *Ty = D->getFriendType()) {
608     TypeSourceInfo *InstTy;
609     // If this is an unsupported friend, don't bother substituting template
610     // arguments into it. The actual type referred to won't be used by any
611     // parts of Clang, and may not be valid for instantiating. Just use the
612     // same info for the instantiated friend.
613     if (D->isUnsupportedFriend()) {
614       InstTy = Ty;
615     } else {
616       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
617                                  D->getLocation(), DeclarationName());
618     }
619     if (!InstTy)
620       return 0;
621 
622     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
623                                                  D->getFriendLoc(), InstTy);
624     if (!FD)
625       return 0;
626 
627     FD->setAccess(AS_public);
628     FD->setUnsupportedFriend(D->isUnsupportedFriend());
629     Owner->addDecl(FD);
630     return FD;
631   }
632 
633   NamedDecl *ND = D->getFriendDecl();
634   assert(ND && "friend decl must be a decl or a type!");
635 
636   // All of the Visit implementations for the various potential friend
637   // declarations have to be carefully written to work for friend
638   // objects, with the most important detail being that the target
639   // decl should almost certainly not be placed in Owner.
640   Decl *NewND = Visit(ND);
641   if (!NewND) return 0;
642 
643   FriendDecl *FD =
644     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
645                        cast<NamedDecl>(NewND), D->getFriendLoc());
646   FD->setAccess(AS_public);
647   FD->setUnsupportedFriend(D->isUnsupportedFriend());
648   Owner->addDecl(FD);
649   return FD;
650 }
651 
652 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
653   Expr *AssertExpr = D->getAssertExpr();
654 
655   // The expression in a static assertion is a constant expression.
656   EnterExpressionEvaluationContext Unevaluated(SemaRef,
657                                                Sema::ConstantEvaluated);
658 
659   ExprResult InstantiatedAssertExpr
660     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
661   if (InstantiatedAssertExpr.isInvalid())
662     return 0;
663 
664   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
665                                               InstantiatedAssertExpr.get(),
666                                               D->getMessage(),
667                                               D->getRParenLoc(),
668                                               D->isFailed());
669 }
670 
671 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
672   EnumDecl *PrevDecl = 0;
673   if (D->getPreviousDecl()) {
674     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
675                                                    D->getPreviousDecl(),
676                                                    TemplateArgs);
677     if (!Prev) return 0;
678     PrevDecl = cast<EnumDecl>(Prev);
679   }
680 
681   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
682                                     D->getLocation(), D->getIdentifier(),
683                                     PrevDecl, D->isScoped(),
684                                     D->isScopedUsingClassTag(), D->isFixed());
685   if (D->isFixed()) {
686     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
687       // If we have type source information for the underlying type, it means it
688       // has been explicitly set by the user. Perform substitution on it before
689       // moving on.
690       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
691       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
692                                                 DeclarationName());
693       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
694         Enum->setIntegerType(SemaRef.Context.IntTy);
695       else
696         Enum->setIntegerTypeSourceInfo(NewTI);
697     } else {
698       assert(!D->getIntegerType()->isDependentType()
699              && "Dependent type without type source info");
700       Enum->setIntegerType(D->getIntegerType());
701     }
702   }
703 
704   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
705 
706   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
707   Enum->setAccess(D->getAccess());
708   if (SubstQualifier(D, Enum)) return 0;
709   Owner->addDecl(Enum);
710 
711   EnumDecl *Def = D->getDefinition();
712   if (Def && Def != D) {
713     // If this is an out-of-line definition of an enum member template, check
714     // that the underlying types match in the instantiation of both
715     // declarations.
716     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
717       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
718       QualType DefnUnderlying =
719         SemaRef.SubstType(TI->getType(), TemplateArgs,
720                           UnderlyingLoc, DeclarationName());
721       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
722                                      DefnUnderlying, Enum);
723     }
724   }
725 
726   if (D->getDeclContext()->isFunctionOrMethod())
727     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
728 
729   // C++11 [temp.inst]p1: The implicit instantiation of a class template
730   // specialization causes the implicit instantiation of the declarations, but
731   // not the definitions of scoped member enumerations.
732   // FIXME: There appears to be no wording for what happens for an enum defined
733   // within a block scope, but we treat that much like a member template. Only
734   // instantiate the definition when visiting the definition in that case, since
735   // we will visit all redeclarations.
736   if (!Enum->isScoped() && Def &&
737       (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
738     InstantiateEnumDefinition(Enum, Def);
739 
740   return Enum;
741 }
742 
743 void TemplateDeclInstantiator::InstantiateEnumDefinition(
744     EnumDecl *Enum, EnumDecl *Pattern) {
745   Enum->startDefinition();
746 
747   // Update the location to refer to the definition.
748   Enum->setLocation(Pattern->getLocation());
749 
750   SmallVector<Decl*, 4> Enumerators;
751 
752   EnumConstantDecl *LastEnumConst = 0;
753   for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
754          ECEnd = Pattern->enumerator_end();
755        EC != ECEnd; ++EC) {
756     // The specified value for the enumerator.
757     ExprResult Value = SemaRef.Owned((Expr *)0);
758     if (Expr *UninstValue = EC->getInitExpr()) {
759       // The enumerator's value expression is a constant expression.
760       EnterExpressionEvaluationContext Unevaluated(SemaRef,
761                                                    Sema::ConstantEvaluated);
762 
763       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
764     }
765 
766     // Drop the initial value and continue.
767     bool isInvalid = false;
768     if (Value.isInvalid()) {
769       Value = SemaRef.Owned((Expr *)0);
770       isInvalid = true;
771     }
772 
773     EnumConstantDecl *EnumConst
774       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
775                                   EC->getLocation(), EC->getIdentifier(),
776                                   Value.get());
777 
778     if (isInvalid) {
779       if (EnumConst)
780         EnumConst->setInvalidDecl();
781       Enum->setInvalidDecl();
782     }
783 
784     if (EnumConst) {
785       SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
786 
787       EnumConst->setAccess(Enum->getAccess());
788       Enum->addDecl(EnumConst);
789       Enumerators.push_back(EnumConst);
790       LastEnumConst = EnumConst;
791 
792       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
793           !Enum->isScoped()) {
794         // If the enumeration is within a function or method, record the enum
795         // constant as a local.
796         SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
797       }
798     }
799   }
800 
801   // FIXME: Fixup LBraceLoc
802   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
803                         Enum->getRBraceLoc(), Enum,
804                         Enumerators,
805                         0, 0);
806 }
807 
808 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
809   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
810 }
811 
812 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
813   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
814 
815   // Create a local instantiation scope for this class template, which
816   // will contain the instantiations of the template parameters.
817   LocalInstantiationScope Scope(SemaRef);
818   TemplateParameterList *TempParams = D->getTemplateParameters();
819   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
820   if (!InstParams)
821     return NULL;
822 
823   CXXRecordDecl *Pattern = D->getTemplatedDecl();
824 
825   // Instantiate the qualifier.  We have to do this first in case
826   // we're a friend declaration, because if we are then we need to put
827   // the new declaration in the appropriate context.
828   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
829   if (QualifierLoc) {
830     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
831                                                        TemplateArgs);
832     if (!QualifierLoc)
833       return 0;
834   }
835 
836   CXXRecordDecl *PrevDecl = 0;
837   ClassTemplateDecl *PrevClassTemplate = 0;
838 
839   if (!isFriend && Pattern->getPreviousDecl()) {
840     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
841     if (!Found.empty()) {
842       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
843       if (PrevClassTemplate)
844         PrevDecl = PrevClassTemplate->getTemplatedDecl();
845     }
846   }
847 
848   // If this isn't a friend, then it's a member template, in which
849   // case we just want to build the instantiation in the
850   // specialization.  If it is a friend, we want to build it in
851   // the appropriate context.
852   DeclContext *DC = Owner;
853   if (isFriend) {
854     if (QualifierLoc) {
855       CXXScopeSpec SS;
856       SS.Adopt(QualifierLoc);
857       DC = SemaRef.computeDeclContext(SS);
858       if (!DC) return 0;
859     } else {
860       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
861                                            Pattern->getDeclContext(),
862                                            TemplateArgs);
863     }
864 
865     // Look for a previous declaration of the template in the owning
866     // context.
867     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
868                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
869     SemaRef.LookupQualifiedName(R, DC);
870 
871     if (R.isSingleResult()) {
872       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
873       if (PrevClassTemplate)
874         PrevDecl = PrevClassTemplate->getTemplatedDecl();
875     }
876 
877     if (!PrevClassTemplate && QualifierLoc) {
878       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
879         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
880         << QualifierLoc.getSourceRange();
881       return 0;
882     }
883 
884     bool AdoptedPreviousTemplateParams = false;
885     if (PrevClassTemplate) {
886       bool Complain = true;
887 
888       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
889       // template for struct std::tr1::__detail::_Map_base, where the
890       // template parameters of the friend declaration don't match the
891       // template parameters of the original declaration. In this one
892       // case, we don't complain about the ill-formed friend
893       // declaration.
894       if (isFriend && Pattern->getIdentifier() &&
895           Pattern->getIdentifier()->isStr("_Map_base") &&
896           DC->isNamespace() &&
897           cast<NamespaceDecl>(DC)->getIdentifier() &&
898           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
899         DeclContext *DCParent = DC->getParent();
900         if (DCParent->isNamespace() &&
901             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
902             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
903           DeclContext *DCParent2 = DCParent->getParent();
904           if (DCParent2->isNamespace() &&
905               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
906               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
907               DCParent2->getParent()->isTranslationUnit())
908             Complain = false;
909         }
910       }
911 
912       TemplateParameterList *PrevParams
913         = PrevClassTemplate->getTemplateParameters();
914 
915       // Make sure the parameter lists match.
916       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
917                                                   Complain,
918                                                   Sema::TPL_TemplateMatch)) {
919         if (Complain)
920           return 0;
921 
922         AdoptedPreviousTemplateParams = true;
923         InstParams = PrevParams;
924       }
925 
926       // Do some additional validation, then merge default arguments
927       // from the existing declarations.
928       if (!AdoptedPreviousTemplateParams &&
929           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
930                                              Sema::TPC_ClassTemplate))
931         return 0;
932     }
933   }
934 
935   CXXRecordDecl *RecordInst
936     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
937                             Pattern->getLocStart(), Pattern->getLocation(),
938                             Pattern->getIdentifier(), PrevDecl,
939                             /*DelayTypeCreation=*/true);
940 
941   if (QualifierLoc)
942     RecordInst->setQualifierInfo(QualifierLoc);
943 
944   ClassTemplateDecl *Inst
945     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
946                                 D->getIdentifier(), InstParams, RecordInst,
947                                 PrevClassTemplate);
948   RecordInst->setDescribedClassTemplate(Inst);
949 
950   if (isFriend) {
951     if (PrevClassTemplate)
952       Inst->setAccess(PrevClassTemplate->getAccess());
953     else
954       Inst->setAccess(D->getAccess());
955 
956     Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
957     // TODO: do we want to track the instantiation progeny of this
958     // friend target decl?
959   } else {
960     Inst->setAccess(D->getAccess());
961     if (!PrevClassTemplate)
962       Inst->setInstantiatedFromMemberTemplate(D);
963   }
964 
965   // Trigger creation of the type for the instantiation.
966   SemaRef.Context.getInjectedClassNameType(RecordInst,
967                                     Inst->getInjectedClassNameSpecialization());
968 
969   // Finish handling of friends.
970   if (isFriend) {
971     DC->makeDeclVisibleInContext(Inst);
972     Inst->setLexicalDeclContext(Owner);
973     RecordInst->setLexicalDeclContext(Owner);
974     return Inst;
975   }
976 
977   if (D->isOutOfLine()) {
978     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
979     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
980   }
981 
982   Owner->addDecl(Inst);
983 
984   if (!PrevClassTemplate) {
985     // Queue up any out-of-line partial specializations of this member
986     // class template; the client will force their instantiation once
987     // the enclosing class has been instantiated.
988     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
989     D->getPartialSpecializations(PartialSpecs);
990     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
991       if (PartialSpecs[I]->isOutOfLine())
992         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
993   }
994 
995   return Inst;
996 }
997 
998 Decl *
999 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1000                                    ClassTemplatePartialSpecializationDecl *D) {
1001   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1002 
1003   // Lookup the already-instantiated declaration in the instantiation
1004   // of the class template and return that.
1005   DeclContext::lookup_result Found
1006     = Owner->lookup(ClassTemplate->getDeclName());
1007   if (Found.empty())
1008     return 0;
1009 
1010   ClassTemplateDecl *InstClassTemplate
1011     = dyn_cast<ClassTemplateDecl>(Found.front());
1012   if (!InstClassTemplate)
1013     return 0;
1014 
1015   if (ClassTemplatePartialSpecializationDecl *Result
1016         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1017     return Result;
1018 
1019   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1020 }
1021 
1022 Decl *
1023 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1024   // Create a local instantiation scope for this function template, which
1025   // will contain the instantiations of the template parameters and then get
1026   // merged with the local instantiation scope for the function template
1027   // itself.
1028   LocalInstantiationScope Scope(SemaRef);
1029 
1030   TemplateParameterList *TempParams = D->getTemplateParameters();
1031   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1032   if (!InstParams)
1033     return NULL;
1034 
1035   FunctionDecl *Instantiated = 0;
1036   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1037     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1038                                                                  InstParams));
1039   else
1040     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1041                                                           D->getTemplatedDecl(),
1042                                                                 InstParams));
1043 
1044   if (!Instantiated)
1045     return 0;
1046 
1047   // Link the instantiated function template declaration to the function
1048   // template from which it was instantiated.
1049   FunctionTemplateDecl *InstTemplate
1050     = Instantiated->getDescribedFunctionTemplate();
1051   InstTemplate->setAccess(D->getAccess());
1052   assert(InstTemplate &&
1053          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1054 
1055   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1056 
1057   // Link the instantiation back to the pattern *unless* this is a
1058   // non-definition friend declaration.
1059   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1060       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1061     InstTemplate->setInstantiatedFromMemberTemplate(D);
1062 
1063   // Make declarations visible in the appropriate context.
1064   if (!isFriend) {
1065     Owner->addDecl(InstTemplate);
1066   } else if (InstTemplate->getDeclContext()->isRecord() &&
1067              !D->getPreviousDecl()) {
1068     SemaRef.CheckFriendAccess(InstTemplate);
1069   }
1070 
1071   return InstTemplate;
1072 }
1073 
1074 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1075   CXXRecordDecl *PrevDecl = 0;
1076   if (D->isInjectedClassName())
1077     PrevDecl = cast<CXXRecordDecl>(Owner);
1078   else if (D->getPreviousDecl()) {
1079     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1080                                                    D->getPreviousDecl(),
1081                                                    TemplateArgs);
1082     if (!Prev) return 0;
1083     PrevDecl = cast<CXXRecordDecl>(Prev);
1084   }
1085 
1086   CXXRecordDecl *Record
1087     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1088                             D->getLocStart(), D->getLocation(),
1089                             D->getIdentifier(), PrevDecl);
1090 
1091   // Substitute the nested name specifier, if any.
1092   if (SubstQualifier(D, Record))
1093     return 0;
1094 
1095   Record->setImplicit(D->isImplicit());
1096   // FIXME: Check against AS_none is an ugly hack to work around the issue that
1097   // the tag decls introduced by friend class declarations don't have an access
1098   // specifier. Remove once this area of the code gets sorted out.
1099   if (D->getAccess() != AS_none)
1100     Record->setAccess(D->getAccess());
1101   if (!D->isInjectedClassName())
1102     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1103 
1104   // If the original function was part of a friend declaration,
1105   // inherit its namespace state.
1106   if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1107     Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1108 
1109   // Make sure that anonymous structs and unions are recorded.
1110   if (D->isAnonymousStructOrUnion()) {
1111     Record->setAnonymousStructOrUnion(true);
1112     if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
1113       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1114   }
1115 
1116   Owner->addDecl(Record);
1117   return Record;
1118 }
1119 
1120 /// \brief Adjust the given function type for an instantiation of the
1121 /// given declaration, to cope with modifications to the function's type that
1122 /// aren't reflected in the type-source information.
1123 ///
1124 /// \param D The declaration we're instantiating.
1125 /// \param TInfo The already-instantiated type.
1126 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1127                                                    FunctionDecl *D,
1128                                                    TypeSourceInfo *TInfo) {
1129   const FunctionProtoType *OrigFunc
1130     = D->getType()->castAs<FunctionProtoType>();
1131   const FunctionProtoType *NewFunc
1132     = TInfo->getType()->castAs<FunctionProtoType>();
1133   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1134     return TInfo->getType();
1135 
1136   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1137   NewEPI.ExtInfo = OrigFunc->getExtInfo();
1138   return Context.getFunctionType(NewFunc->getResultType(),
1139                                  ArrayRef<QualType>(NewFunc->arg_type_begin(),
1140                                                     NewFunc->getNumArgs()),
1141                                  NewEPI);
1142 }
1143 
1144 /// Normal class members are of more specific types and therefore
1145 /// don't make it here.  This function serves two purposes:
1146 ///   1) instantiating function templates
1147 ///   2) substituting friend declarations
1148 /// FIXME: preserve function definitions in case #2
1149 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1150                                        TemplateParameterList *TemplateParams) {
1151   // Check whether there is already a function template specialization for
1152   // this declaration.
1153   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1154   if (FunctionTemplate && !TemplateParams) {
1155     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1156 
1157     void *InsertPos = 0;
1158     FunctionDecl *SpecFunc
1159       = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
1160                                              InsertPos);
1161 
1162     // If we already have a function template specialization, return it.
1163     if (SpecFunc)
1164       return SpecFunc;
1165   }
1166 
1167   bool isFriend;
1168   if (FunctionTemplate)
1169     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1170   else
1171     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1172 
1173   bool MergeWithParentScope = (TemplateParams != 0) ||
1174     Owner->isFunctionOrMethod() ||
1175     !(isa<Decl>(Owner) &&
1176       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1177   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1178 
1179   SmallVector<ParmVarDecl *, 4> Params;
1180   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1181   if (!TInfo)
1182     return 0;
1183   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1184 
1185   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1186   if (QualifierLoc) {
1187     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1188                                                        TemplateArgs);
1189     if (!QualifierLoc)
1190       return 0;
1191   }
1192 
1193   // If we're instantiating a local function declaration, put the result
1194   // in the owner;  otherwise we need to find the instantiated context.
1195   DeclContext *DC;
1196   if (D->getDeclContext()->isFunctionOrMethod())
1197     DC = Owner;
1198   else if (isFriend && QualifierLoc) {
1199     CXXScopeSpec SS;
1200     SS.Adopt(QualifierLoc);
1201     DC = SemaRef.computeDeclContext(SS);
1202     if (!DC) return 0;
1203   } else {
1204     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1205                                          TemplateArgs);
1206   }
1207 
1208   FunctionDecl *Function =
1209       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1210                            D->getNameInfo(), T, TInfo,
1211                            D->getCanonicalDecl()->getStorageClass(),
1212                            D->isInlineSpecified(), D->hasWrittenPrototype(),
1213                            D->isConstexpr());
1214 
1215   if (D->isInlined())
1216     Function->setImplicitlyInline();
1217 
1218   if (QualifierLoc)
1219     Function->setQualifierInfo(QualifierLoc);
1220 
1221   DeclContext *LexicalDC = Owner;
1222   if (!isFriend && D->isOutOfLine()) {
1223     assert(D->getDeclContext()->isFileContext());
1224     LexicalDC = D->getDeclContext();
1225   }
1226 
1227   Function->setLexicalDeclContext(LexicalDC);
1228 
1229   // Attach the parameters
1230   if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
1231     // Adopt the already-instantiated parameters into our own context.
1232     for (unsigned P = 0; P < Params.size(); ++P)
1233       if (Params[P])
1234         Params[P]->setOwningFunction(Function);
1235   } else {
1236     // Since we were instantiated via a typedef of a function type, create
1237     // new parameters.
1238     const FunctionProtoType *Proto
1239       = Function->getType()->getAs<FunctionProtoType>();
1240     assert(Proto && "No function prototype in template instantiation?");
1241     for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1242          AE = Proto->arg_type_end(); AI != AE; ++AI) {
1243       ParmVarDecl *Param
1244         = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1245                                              *AI);
1246       Param->setScopeInfo(0, Params.size());
1247       Params.push_back(Param);
1248     }
1249   }
1250   Function->setParams(Params);
1251 
1252   SourceLocation InstantiateAtPOI;
1253   if (TemplateParams) {
1254     // Our resulting instantiation is actually a function template, since we
1255     // are substituting only the outer template parameters. For example, given
1256     //
1257     //   template<typename T>
1258     //   struct X {
1259     //     template<typename U> friend void f(T, U);
1260     //   };
1261     //
1262     //   X<int> x;
1263     //
1264     // We are instantiating the friend function template "f" within X<int>,
1265     // which means substituting int for T, but leaving "f" as a friend function
1266     // template.
1267     // Build the function template itself.
1268     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1269                                                     Function->getLocation(),
1270                                                     Function->getDeclName(),
1271                                                     TemplateParams, Function);
1272     Function->setDescribedFunctionTemplate(FunctionTemplate);
1273 
1274     FunctionTemplate->setLexicalDeclContext(LexicalDC);
1275 
1276     if (isFriend && D->isThisDeclarationADefinition()) {
1277       // TODO: should we remember this connection regardless of whether
1278       // the friend declaration provided a body?
1279       FunctionTemplate->setInstantiatedFromMemberTemplate(
1280                                            D->getDescribedFunctionTemplate());
1281     }
1282   } else if (FunctionTemplate) {
1283     // Record this function template specialization.
1284     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1285     Function->setFunctionTemplateSpecialization(FunctionTemplate,
1286                             TemplateArgumentList::CreateCopy(SemaRef.Context,
1287                                                              Innermost.begin(),
1288                                                              Innermost.size()),
1289                                                 /*InsertPos=*/0);
1290   } else if (isFriend) {
1291     // Note, we need this connection even if the friend doesn't have a body.
1292     // Its body may exist but not have been attached yet due to deferred
1293     // parsing.
1294     // FIXME: It might be cleaner to set this when attaching the body to the
1295     // friend function declaration, however that would require finding all the
1296     // instantiations and modifying them.
1297     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1298   }
1299 
1300   if (InitFunctionInstantiation(Function, D))
1301     Function->setInvalidDecl();
1302 
1303   bool isExplicitSpecialization = false;
1304 
1305   LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1306                         Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1307 
1308   if (DependentFunctionTemplateSpecializationInfo *Info
1309         = D->getDependentSpecializationInfo()) {
1310     assert(isFriend && "non-friend has dependent specialization info?");
1311 
1312     // This needs to be set now for future sanity.
1313     Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1314 
1315     // Instantiate the explicit template arguments.
1316     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1317                                           Info->getRAngleLoc());
1318     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1319                       ExplicitArgs, TemplateArgs))
1320       return 0;
1321 
1322     // Map the candidate templates to their instantiations.
1323     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1324       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1325                                                 Info->getTemplate(I),
1326                                                 TemplateArgs);
1327       if (!Temp) return 0;
1328 
1329       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1330     }
1331 
1332     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1333                                                     &ExplicitArgs,
1334                                                     Previous))
1335       Function->setInvalidDecl();
1336 
1337     isExplicitSpecialization = true;
1338 
1339   } else if (TemplateParams || !FunctionTemplate) {
1340     // Look only into the namespace where the friend would be declared to
1341     // find a previous declaration. This is the innermost enclosing namespace,
1342     // as described in ActOnFriendFunctionDecl.
1343     SemaRef.LookupQualifiedName(Previous, DC);
1344 
1345     // In C++, the previous declaration we find might be a tag type
1346     // (class or enum). In this case, the new declaration will hide the
1347     // tag type. Note that this does does not apply if we're declaring a
1348     // typedef (C++ [dcl.typedef]p4).
1349     if (Previous.isSingleTagDecl())
1350       Previous.clear();
1351   }
1352 
1353   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1354                                    isExplicitSpecialization);
1355 
1356   NamedDecl *PrincipalDecl = (TemplateParams
1357                               ? cast<NamedDecl>(FunctionTemplate)
1358                               : Function);
1359 
1360   // If the original function was part of a friend declaration,
1361   // inherit its namespace state and add it to the owner.
1362   if (isFriend) {
1363     NamedDecl *PrevDecl;
1364     if (TemplateParams)
1365       PrevDecl = FunctionTemplate->getPreviousDecl();
1366     else
1367       PrevDecl = Function->getPreviousDecl();
1368 
1369     PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1370     DC->makeDeclVisibleInContext(PrincipalDecl);
1371 
1372     bool queuedInstantiation = false;
1373 
1374     // C++98 [temp.friend]p5: When a function is defined in a friend function
1375     //   declaration in a class template, the function is defined at each
1376     //   instantiation of the class template. The function is defined even if it
1377     //   is never used.
1378     // C++11 [temp.friend]p4: When a function is defined in a friend function
1379     //   declaration in a class template, the function is instantiated when the
1380     //   function is odr-used.
1381     //
1382     // If -Wc++98-compat is enabled, we go through the motions of checking for a
1383     // redefinition, but don't instantiate the function.
1384     if ((!SemaRef.getLangOpts().CPlusPlus11 ||
1385          SemaRef.Diags.getDiagnosticLevel(
1386              diag::warn_cxx98_compat_friend_redefinition,
1387              Function->getLocation())
1388            != DiagnosticsEngine::Ignored) &&
1389         D->isThisDeclarationADefinition()) {
1390       // Check for a function body.
1391       const FunctionDecl *Definition = 0;
1392       if (Function->isDefined(Definition) &&
1393           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1394         SemaRef.Diag(Function->getLocation(),
1395                      SemaRef.getLangOpts().CPlusPlus11 ?
1396                        diag::warn_cxx98_compat_friend_redefinition :
1397                        diag::err_redefinition) << Function->getDeclName();
1398         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1399         if (!SemaRef.getLangOpts().CPlusPlus11)
1400           Function->setInvalidDecl();
1401       }
1402       // Check for redefinitions due to other instantiations of this or
1403       // a similar friend function.
1404       else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1405                                            REnd = Function->redecls_end();
1406                 R != REnd; ++R) {
1407         if (*R == Function)
1408           continue;
1409         switch (R->getFriendObjectKind()) {
1410         case Decl::FOK_None:
1411           if (!SemaRef.getLangOpts().CPlusPlus11 &&
1412               !queuedInstantiation && R->isUsed(false)) {
1413             if (MemberSpecializationInfo *MSInfo
1414                 = Function->getMemberSpecializationInfo()) {
1415               if (MSInfo->getPointOfInstantiation().isInvalid()) {
1416                 SourceLocation Loc = R->getLocation(); // FIXME
1417                 MSInfo->setPointOfInstantiation(Loc);
1418                 SemaRef.PendingLocalImplicitInstantiations.push_back(
1419                                                  std::make_pair(Function, Loc));
1420                 queuedInstantiation = true;
1421               }
1422             }
1423           }
1424           break;
1425         default:
1426           if (const FunctionDecl *RPattern
1427               = R->getTemplateInstantiationPattern())
1428             if (RPattern->isDefined(RPattern)) {
1429               SemaRef.Diag(Function->getLocation(),
1430                            SemaRef.getLangOpts().CPlusPlus11 ?
1431                              diag::warn_cxx98_compat_friend_redefinition :
1432                              diag::err_redefinition)
1433                 << Function->getDeclName();
1434               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1435               if (!SemaRef.getLangOpts().CPlusPlus11)
1436                 Function->setInvalidDecl();
1437               break;
1438             }
1439         }
1440       }
1441     }
1442   }
1443 
1444   if (Function->isOverloadedOperator() && !DC->isRecord() &&
1445       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1446     PrincipalDecl->setNonMemberOperator();
1447 
1448   assert(!D->isDefaulted() && "only methods should be defaulted");
1449   return Function;
1450 }
1451 
1452 Decl *
1453 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1454                                       TemplateParameterList *TemplateParams,
1455                                       bool IsClassScopeSpecialization) {
1456   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1457   if (FunctionTemplate && !TemplateParams) {
1458     // We are creating a function template specialization from a function
1459     // template. Check whether there is already a function template
1460     // specialization for this particular set of template arguments.
1461     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1462 
1463     void *InsertPos = 0;
1464     FunctionDecl *SpecFunc
1465       = FunctionTemplate->findSpecialization(Innermost.begin(),
1466                                              Innermost.size(),
1467                                              InsertPos);
1468 
1469     // If we already have a function template specialization, return it.
1470     if (SpecFunc)
1471       return SpecFunc;
1472   }
1473 
1474   bool isFriend;
1475   if (FunctionTemplate)
1476     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1477   else
1478     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1479 
1480   bool MergeWithParentScope = (TemplateParams != 0) ||
1481     !(isa<Decl>(Owner) &&
1482       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1483   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1484 
1485   // Instantiate enclosing template arguments for friends.
1486   SmallVector<TemplateParameterList *, 4> TempParamLists;
1487   unsigned NumTempParamLists = 0;
1488   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1489     TempParamLists.set_size(NumTempParamLists);
1490     for (unsigned I = 0; I != NumTempParamLists; ++I) {
1491       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1492       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1493       if (!InstParams)
1494         return NULL;
1495       TempParamLists[I] = InstParams;
1496     }
1497   }
1498 
1499   SmallVector<ParmVarDecl *, 4> Params;
1500   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1501   if (!TInfo)
1502     return 0;
1503   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1504 
1505   // \brief If the type of this function, after ignoring parentheses,
1506   // is not *directly* a function type, then we're instantiating a function
1507   // that was declared via a typedef, e.g.,
1508   //
1509   //   typedef int functype(int, int);
1510   //   functype func;
1511   //
1512   // In this case, we'll just go instantiate the ParmVarDecls that we
1513   // synthesized in the method declaration.
1514   if (!isa<FunctionProtoType>(T.IgnoreParens())) {
1515     assert(!Params.size() && "Instantiating type could not yield parameters");
1516     SmallVector<QualType, 4> ParamTypes;
1517     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1518                                D->getNumParams(), TemplateArgs, ParamTypes,
1519                                &Params))
1520       return 0;
1521   }
1522 
1523   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1524   if (QualifierLoc) {
1525     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1526                                                  TemplateArgs);
1527     if (!QualifierLoc)
1528       return 0;
1529   }
1530 
1531   DeclContext *DC = Owner;
1532   if (isFriend) {
1533     if (QualifierLoc) {
1534       CXXScopeSpec SS;
1535       SS.Adopt(QualifierLoc);
1536       DC = SemaRef.computeDeclContext(SS);
1537 
1538       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1539         return 0;
1540     } else {
1541       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1542                                            D->getDeclContext(),
1543                                            TemplateArgs);
1544     }
1545     if (!DC) return 0;
1546   }
1547 
1548   // Build the instantiated method declaration.
1549   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1550   CXXMethodDecl *Method = 0;
1551 
1552   SourceLocation StartLoc = D->getInnerLocStart();
1553   DeclarationNameInfo NameInfo
1554     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1555   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1556     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1557                                         StartLoc, NameInfo, T, TInfo,
1558                                         Constructor->isExplicit(),
1559                                         Constructor->isInlineSpecified(),
1560                                         false, Constructor->isConstexpr());
1561     // Claim that the instantiation of a constructor or constructor template
1562     // inherits the same constructor that the template does.
1563     if (const CXXConstructorDecl *Inh = Constructor->getInheritedConstructor())
1564       cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1565   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1566     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1567                                        StartLoc, NameInfo, T, TInfo,
1568                                        Destructor->isInlineSpecified(),
1569                                        false);
1570   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1571     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1572                                        StartLoc, NameInfo, T, TInfo,
1573                                        Conversion->isInlineSpecified(),
1574                                        Conversion->isExplicit(),
1575                                        Conversion->isConstexpr(),
1576                                        Conversion->getLocEnd());
1577   } else {
1578     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1579     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1580                                    StartLoc, NameInfo, T, TInfo,
1581                                    SC, D->isInlineSpecified(),
1582                                    D->isConstexpr(), D->getLocEnd());
1583   }
1584 
1585   if (D->isInlined())
1586     Method->setImplicitlyInline();
1587 
1588   if (QualifierLoc)
1589     Method->setQualifierInfo(QualifierLoc);
1590 
1591   if (TemplateParams) {
1592     // Our resulting instantiation is actually a function template, since we
1593     // are substituting only the outer template parameters. For example, given
1594     //
1595     //   template<typename T>
1596     //   struct X {
1597     //     template<typename U> void f(T, U);
1598     //   };
1599     //
1600     //   X<int> x;
1601     //
1602     // We are instantiating the member template "f" within X<int>, which means
1603     // substituting int for T, but leaving "f" as a member function template.
1604     // Build the function template itself.
1605     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1606                                                     Method->getLocation(),
1607                                                     Method->getDeclName(),
1608                                                     TemplateParams, Method);
1609     if (isFriend) {
1610       FunctionTemplate->setLexicalDeclContext(Owner);
1611       FunctionTemplate->setObjectOfFriendDecl(true);
1612     } else if (D->isOutOfLine())
1613       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1614     Method->setDescribedFunctionTemplate(FunctionTemplate);
1615   } else if (FunctionTemplate) {
1616     // Record this function template specialization.
1617     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1618     Method->setFunctionTemplateSpecialization(FunctionTemplate,
1619                          TemplateArgumentList::CreateCopy(SemaRef.Context,
1620                                                           Innermost.begin(),
1621                                                           Innermost.size()),
1622                                               /*InsertPos=*/0);
1623   } else if (!isFriend) {
1624     // Record that this is an instantiation of a member function.
1625     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1626   }
1627 
1628   // If we are instantiating a member function defined
1629   // out-of-line, the instantiation will have the same lexical
1630   // context (which will be a namespace scope) as the template.
1631   if (isFriend) {
1632     if (NumTempParamLists)
1633       Method->setTemplateParameterListsInfo(SemaRef.Context,
1634                                             NumTempParamLists,
1635                                             TempParamLists.data());
1636 
1637     Method->setLexicalDeclContext(Owner);
1638     Method->setObjectOfFriendDecl(true);
1639   } else if (D->isOutOfLine())
1640     Method->setLexicalDeclContext(D->getLexicalDeclContext());
1641 
1642   // Attach the parameters
1643   for (unsigned P = 0; P < Params.size(); ++P)
1644     Params[P]->setOwningFunction(Method);
1645   Method->setParams(Params);
1646 
1647   if (InitMethodInstantiation(Method, D))
1648     Method->setInvalidDecl();
1649 
1650   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1651                         Sema::ForRedeclaration);
1652 
1653   if (!FunctionTemplate || TemplateParams || isFriend) {
1654     SemaRef.LookupQualifiedName(Previous, Record);
1655 
1656     // In C++, the previous declaration we find might be a tag type
1657     // (class or enum). In this case, the new declaration will hide the
1658     // tag type. Note that this does does not apply if we're declaring a
1659     // typedef (C++ [dcl.typedef]p4).
1660     if (Previous.isSingleTagDecl())
1661       Previous.clear();
1662   }
1663 
1664   if (!IsClassScopeSpecialization)
1665     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1666 
1667   if (D->isPure())
1668     SemaRef.CheckPureMethod(Method, SourceRange());
1669 
1670   // Propagate access.  For a non-friend declaration, the access is
1671   // whatever we're propagating from.  For a friend, it should be the
1672   // previous declaration we just found.
1673   if (isFriend && Method->getPreviousDecl())
1674     Method->setAccess(Method->getPreviousDecl()->getAccess());
1675   else
1676     Method->setAccess(D->getAccess());
1677   if (FunctionTemplate)
1678     FunctionTemplate->setAccess(Method->getAccess());
1679 
1680   SemaRef.CheckOverrideControl(Method);
1681 
1682   // If a function is defined as defaulted or deleted, mark it as such now.
1683   if (D->isExplicitlyDefaulted())
1684     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1685   if (D->isDeletedAsWritten())
1686     SemaRef.SetDeclDeleted(Method, Method->getLocation());
1687 
1688   // If there's a function template, let our caller handle it.
1689   if (FunctionTemplate) {
1690     // do nothing
1691 
1692   // Don't hide a (potentially) valid declaration with an invalid one.
1693   } else if (Method->isInvalidDecl() && !Previous.empty()) {
1694     // do nothing
1695 
1696   // Otherwise, check access to friends and make them visible.
1697   } else if (isFriend) {
1698     // We only need to re-check access for methods which we didn't
1699     // manage to match during parsing.
1700     if (!D->getPreviousDecl())
1701       SemaRef.CheckFriendAccess(Method);
1702 
1703     Record->makeDeclVisibleInContext(Method);
1704 
1705   // Otherwise, add the declaration.  We don't need to do this for
1706   // class-scope specializations because we'll have matched them with
1707   // the appropriate template.
1708   } else if (!IsClassScopeSpecialization) {
1709     Owner->addDecl(Method);
1710   }
1711 
1712   return Method;
1713 }
1714 
1715 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1716   return VisitCXXMethodDecl(D);
1717 }
1718 
1719 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1720   return VisitCXXMethodDecl(D);
1721 }
1722 
1723 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1724   return VisitCXXMethodDecl(D);
1725 }
1726 
1727 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1728   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1729                                   /*ExpectParameterPack=*/ false);
1730 }
1731 
1732 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1733                                                     TemplateTypeParmDecl *D) {
1734   // TODO: don't always clone when decls are refcounted.
1735   assert(D->getTypeForDecl()->isTemplateTypeParmType());
1736 
1737   TemplateTypeParmDecl *Inst =
1738     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1739                                  D->getLocStart(), D->getLocation(),
1740                                  D->getDepth() - TemplateArgs.getNumLevels(),
1741                                  D->getIndex(), D->getIdentifier(),
1742                                  D->wasDeclaredWithTypename(),
1743                                  D->isParameterPack());
1744   Inst->setAccess(AS_public);
1745 
1746   if (D->hasDefaultArgument())
1747     Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1748 
1749   // Introduce this template parameter's instantiation into the instantiation
1750   // scope.
1751   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1752 
1753   return Inst;
1754 }
1755 
1756 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1757                                                  NonTypeTemplateParmDecl *D) {
1758   // Substitute into the type of the non-type template parameter.
1759   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1760   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1761   SmallVector<QualType, 4> ExpandedParameterPackTypes;
1762   bool IsExpandedParameterPack = false;
1763   TypeSourceInfo *DI;
1764   QualType T;
1765   bool Invalid = false;
1766 
1767   if (D->isExpandedParameterPack()) {
1768     // The non-type template parameter pack is an already-expanded pack
1769     // expansion of types. Substitute into each of the expanded types.
1770     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1771     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1772     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1773       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1774                                                TemplateArgs,
1775                                                D->getLocation(),
1776                                                D->getDeclName());
1777       if (!NewDI)
1778         return 0;
1779 
1780       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1781       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1782                                                               D->getLocation());
1783       if (NewT.isNull())
1784         return 0;
1785       ExpandedParameterPackTypes.push_back(NewT);
1786     }
1787 
1788     IsExpandedParameterPack = true;
1789     DI = D->getTypeSourceInfo();
1790     T = DI->getType();
1791   } else if (D->isPackExpansion()) {
1792     // The non-type template parameter pack's type is a pack expansion of types.
1793     // Determine whether we need to expand this parameter pack into separate
1794     // types.
1795     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1796     TypeLoc Pattern = Expansion.getPatternLoc();
1797     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1798     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1799 
1800     // Determine whether the set of unexpanded parameter packs can and should
1801     // be expanded.
1802     bool Expand = true;
1803     bool RetainExpansion = false;
1804     Optional<unsigned> OrigNumExpansions
1805       = Expansion.getTypePtr()->getNumExpansions();
1806     Optional<unsigned> NumExpansions = OrigNumExpansions;
1807     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1808                                                 Pattern.getSourceRange(),
1809                                                 Unexpanded,
1810                                                 TemplateArgs,
1811                                                 Expand, RetainExpansion,
1812                                                 NumExpansions))
1813       return 0;
1814 
1815     if (Expand) {
1816       for (unsigned I = 0; I != *NumExpansions; ++I) {
1817         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1818         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1819                                                   D->getLocation(),
1820                                                   D->getDeclName());
1821         if (!NewDI)
1822           return 0;
1823 
1824         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1825         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1826                                                               NewDI->getType(),
1827                                                               D->getLocation());
1828         if (NewT.isNull())
1829           return 0;
1830         ExpandedParameterPackTypes.push_back(NewT);
1831       }
1832 
1833       // Note that we have an expanded parameter pack. The "type" of this
1834       // expanded parameter pack is the original expansion type, but callers
1835       // will end up using the expanded parameter pack types for type-checking.
1836       IsExpandedParameterPack = true;
1837       DI = D->getTypeSourceInfo();
1838       T = DI->getType();
1839     } else {
1840       // We cannot fully expand the pack expansion now, so substitute into the
1841       // pattern and create a new pack expansion type.
1842       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1843       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1844                                                      D->getLocation(),
1845                                                      D->getDeclName());
1846       if (!NewPattern)
1847         return 0;
1848 
1849       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1850                                       NumExpansions);
1851       if (!DI)
1852         return 0;
1853 
1854       T = DI->getType();
1855     }
1856   } else {
1857     // Simple case: substitution into a parameter that is not a parameter pack.
1858     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1859                            D->getLocation(), D->getDeclName());
1860     if (!DI)
1861       return 0;
1862 
1863     // Check that this type is acceptable for a non-type template parameter.
1864     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1865                                                   D->getLocation());
1866     if (T.isNull()) {
1867       T = SemaRef.Context.IntTy;
1868       Invalid = true;
1869     }
1870   }
1871 
1872   NonTypeTemplateParmDecl *Param;
1873   if (IsExpandedParameterPack)
1874     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1875                                             D->getInnerLocStart(),
1876                                             D->getLocation(),
1877                                     D->getDepth() - TemplateArgs.getNumLevels(),
1878                                             D->getPosition(),
1879                                             D->getIdentifier(), T,
1880                                             DI,
1881                                             ExpandedParameterPackTypes.data(),
1882                                             ExpandedParameterPackTypes.size(),
1883                                     ExpandedParameterPackTypesAsWritten.data());
1884   else
1885     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1886                                             D->getInnerLocStart(),
1887                                             D->getLocation(),
1888                                     D->getDepth() - TemplateArgs.getNumLevels(),
1889                                             D->getPosition(),
1890                                             D->getIdentifier(), T,
1891                                             D->isParameterPack(), DI);
1892 
1893   Param->setAccess(AS_public);
1894   if (Invalid)
1895     Param->setInvalidDecl();
1896 
1897   Param->setDefaultArgument(D->getDefaultArgument(), false);
1898 
1899   // Introduce this template parameter's instantiation into the instantiation
1900   // scope.
1901   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1902   return Param;
1903 }
1904 
1905 static void collectUnexpandedParameterPacks(
1906     Sema &S,
1907     TemplateParameterList *Params,
1908     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1909   for (TemplateParameterList::const_iterator I = Params->begin(),
1910                                              E = Params->end(); I != E; ++I) {
1911     if ((*I)->isTemplateParameterPack())
1912       continue;
1913     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1914       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1915                                         Unexpanded);
1916     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1917       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1918                                       Unexpanded);
1919   }
1920 }
1921 
1922 Decl *
1923 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1924                                                   TemplateTemplateParmDecl *D) {
1925   // Instantiate the template parameter list of the template template parameter.
1926   TemplateParameterList *TempParams = D->getTemplateParameters();
1927   TemplateParameterList *InstParams;
1928   SmallVector<TemplateParameterList*, 8> ExpandedParams;
1929 
1930   bool IsExpandedParameterPack = false;
1931 
1932   if (D->isExpandedParameterPack()) {
1933     // The template template parameter pack is an already-expanded pack
1934     // expansion of template parameters. Substitute into each of the expanded
1935     // parameters.
1936     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1937     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1938          I != N; ++I) {
1939       LocalInstantiationScope Scope(SemaRef);
1940       TemplateParameterList *Expansion =
1941         SubstTemplateParams(D->getExpansionTemplateParameters(I));
1942       if (!Expansion)
1943         return 0;
1944       ExpandedParams.push_back(Expansion);
1945     }
1946 
1947     IsExpandedParameterPack = true;
1948     InstParams = TempParams;
1949   } else if (D->isPackExpansion()) {
1950     // The template template parameter pack expands to a pack of template
1951     // template parameters. Determine whether we need to expand this parameter
1952     // pack into separate parameters.
1953     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1954     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1955                                     Unexpanded);
1956 
1957     // Determine whether the set of unexpanded parameter packs can and should
1958     // be expanded.
1959     bool Expand = true;
1960     bool RetainExpansion = false;
1961     Optional<unsigned> NumExpansions;
1962     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1963                                                 TempParams->getSourceRange(),
1964                                                 Unexpanded,
1965                                                 TemplateArgs,
1966                                                 Expand, RetainExpansion,
1967                                                 NumExpansions))
1968       return 0;
1969 
1970     if (Expand) {
1971       for (unsigned I = 0; I != *NumExpansions; ++I) {
1972         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1973         LocalInstantiationScope Scope(SemaRef);
1974         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1975         if (!Expansion)
1976           return 0;
1977         ExpandedParams.push_back(Expansion);
1978       }
1979 
1980       // Note that we have an expanded parameter pack. The "type" of this
1981       // expanded parameter pack is the original expansion type, but callers
1982       // will end up using the expanded parameter pack types for type-checking.
1983       IsExpandedParameterPack = true;
1984       InstParams = TempParams;
1985     } else {
1986       // We cannot fully expand the pack expansion now, so just substitute
1987       // into the pattern.
1988       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1989 
1990       LocalInstantiationScope Scope(SemaRef);
1991       InstParams = SubstTemplateParams(TempParams);
1992       if (!InstParams)
1993         return 0;
1994     }
1995   } else {
1996     // Perform the actual substitution of template parameters within a new,
1997     // local instantiation scope.
1998     LocalInstantiationScope Scope(SemaRef);
1999     InstParams = SubstTemplateParams(TempParams);
2000     if (!InstParams)
2001       return 0;
2002   }
2003 
2004   // Build the template template parameter.
2005   TemplateTemplateParmDecl *Param;
2006   if (IsExpandedParameterPack)
2007     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2008                                              D->getLocation(),
2009                                    D->getDepth() - TemplateArgs.getNumLevels(),
2010                                              D->getPosition(),
2011                                              D->getIdentifier(), InstParams,
2012                                              ExpandedParams);
2013   else
2014     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2015                                              D->getLocation(),
2016                                    D->getDepth() - TemplateArgs.getNumLevels(),
2017                                              D->getPosition(),
2018                                              D->isParameterPack(),
2019                                              D->getIdentifier(), InstParams);
2020   Param->setDefaultArgument(D->getDefaultArgument(), false);
2021   Param->setAccess(AS_public);
2022 
2023   // Introduce this template parameter's instantiation into the instantiation
2024   // scope.
2025   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2026 
2027   return Param;
2028 }
2029 
2030 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2031   // Using directives are never dependent (and never contain any types or
2032   // expressions), so they require no explicit instantiation work.
2033 
2034   UsingDirectiveDecl *Inst
2035     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2036                                  D->getNamespaceKeyLocation(),
2037                                  D->getQualifierLoc(),
2038                                  D->getIdentLocation(),
2039                                  D->getNominatedNamespace(),
2040                                  D->getCommonAncestor());
2041 
2042   // Add the using directive to its declaration context
2043   // only if this is not a function or method.
2044   if (!Owner->isFunctionOrMethod())
2045     Owner->addDecl(Inst);
2046 
2047   return Inst;
2048 }
2049 
2050 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2051 
2052   // The nested name specifier may be dependent, for example
2053   //     template <typename T> struct t {
2054   //       struct s1 { T f1(); };
2055   //       struct s2 : s1 { using s1::f1; };
2056   //     };
2057   //     template struct t<int>;
2058   // Here, in using s1::f1, s1 refers to t<T>::s1;
2059   // we need to substitute for t<int>::s1.
2060   NestedNameSpecifierLoc QualifierLoc
2061     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2062                                           TemplateArgs);
2063   if (!QualifierLoc)
2064     return 0;
2065 
2066   // The name info is non-dependent, so no transformation
2067   // is required.
2068   DeclarationNameInfo NameInfo = D->getNameInfo();
2069 
2070   // We only need to do redeclaration lookups if we're in a class
2071   // scope (in fact, it's not really even possible in non-class
2072   // scopes).
2073   bool CheckRedeclaration = Owner->isRecord();
2074 
2075   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2076                     Sema::ForRedeclaration);
2077 
2078   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2079                                        D->getUsingLocation(),
2080                                        QualifierLoc,
2081                                        NameInfo,
2082                                        D->isTypeName());
2083 
2084   CXXScopeSpec SS;
2085   SS.Adopt(QualifierLoc);
2086   if (CheckRedeclaration) {
2087     Prev.setHideTags(false);
2088     SemaRef.LookupQualifiedName(Prev, Owner);
2089 
2090     // Check for invalid redeclarations.
2091     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2092                                             D->isTypeName(), SS,
2093                                             D->getLocation(), Prev))
2094       NewUD->setInvalidDecl();
2095 
2096   }
2097 
2098   if (!NewUD->isInvalidDecl() &&
2099       SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
2100                                       D->getLocation()))
2101     NewUD->setInvalidDecl();
2102 
2103   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2104   NewUD->setAccess(D->getAccess());
2105   Owner->addDecl(NewUD);
2106 
2107   // Don't process the shadow decls for an invalid decl.
2108   if (NewUD->isInvalidDecl())
2109     return NewUD;
2110 
2111   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2112     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2113       NewUD->setInvalidDecl();
2114     return NewUD;
2115   }
2116 
2117   bool isFunctionScope = Owner->isFunctionOrMethod();
2118 
2119   // Process the shadow decls.
2120   for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2121          I != E; ++I) {
2122     UsingShadowDecl *Shadow = *I;
2123     NamedDecl *InstTarget =
2124       cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2125                                                           Shadow->getLocation(),
2126                                                         Shadow->getTargetDecl(),
2127                                                            TemplateArgs));
2128     if (!InstTarget)
2129       return 0;
2130 
2131     if (CheckRedeclaration &&
2132         SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2133       continue;
2134 
2135     UsingShadowDecl *InstShadow
2136       = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2137     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2138 
2139     if (isFunctionScope)
2140       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2141   }
2142 
2143   return NewUD;
2144 }
2145 
2146 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2147   // Ignore these;  we handle them in bulk when processing the UsingDecl.
2148   return 0;
2149 }
2150 
2151 Decl * TemplateDeclInstantiator
2152     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2153   NestedNameSpecifierLoc QualifierLoc
2154     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2155                                           TemplateArgs);
2156   if (!QualifierLoc)
2157     return 0;
2158 
2159   CXXScopeSpec SS;
2160   SS.Adopt(QualifierLoc);
2161 
2162   // Since NameInfo refers to a typename, it cannot be a C++ special name.
2163   // Hence, no transformation is required for it.
2164   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2165   NamedDecl *UD =
2166     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2167                                   D->getUsingLoc(), SS, NameInfo, 0,
2168                                   /*instantiation*/ true,
2169                                   /*typename*/ true, D->getTypenameLoc());
2170   if (UD)
2171     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2172 
2173   return UD;
2174 }
2175 
2176 Decl * TemplateDeclInstantiator
2177     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2178   NestedNameSpecifierLoc QualifierLoc
2179       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2180   if (!QualifierLoc)
2181     return 0;
2182 
2183   CXXScopeSpec SS;
2184   SS.Adopt(QualifierLoc);
2185 
2186   DeclarationNameInfo NameInfo
2187     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2188 
2189   NamedDecl *UD =
2190     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2191                                   D->getUsingLoc(), SS, NameInfo, 0,
2192                                   /*instantiation*/ true,
2193                                   /*typename*/ false, SourceLocation());
2194   if (UD)
2195     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2196 
2197   return UD;
2198 }
2199 
2200 
2201 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2202                                      ClassScopeFunctionSpecializationDecl *Decl) {
2203   CXXMethodDecl *OldFD = Decl->getSpecialization();
2204   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2205                                                                 0, true));
2206 
2207   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2208                         Sema::ForRedeclaration);
2209 
2210   TemplateArgumentListInfo TemplateArgs;
2211   TemplateArgumentListInfo* TemplateArgsPtr = 0;
2212   if (Decl->hasExplicitTemplateArgs()) {
2213     TemplateArgs = Decl->templateArgs();
2214     TemplateArgsPtr = &TemplateArgs;
2215   }
2216 
2217   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2218   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2219                                                   Previous)) {
2220     NewFD->setInvalidDecl();
2221     return NewFD;
2222   }
2223 
2224   // Associate the specialization with the pattern.
2225   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2226   assert(Specialization && "Class scope Specialization is null");
2227   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2228 
2229   return NewFD;
2230 }
2231 
2232 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2233                                      OMPThreadPrivateDecl *D) {
2234   SmallVector<DeclRefExpr *, 5> Vars;
2235   for (ArrayRef<DeclRefExpr *>::iterator I = D->varlist_begin(),
2236                                          E = D->varlist_end();
2237        I != E; ++I) {
2238     Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2239     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2240     Vars.push_back(cast<DeclRefExpr>(Var));
2241   }
2242 
2243   OMPThreadPrivateDecl *TD =
2244     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2245 
2246   return TD;
2247 }
2248 
2249 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2250                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2251   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2252   if (D->isInvalidDecl())
2253     return 0;
2254 
2255   return Instantiator.Visit(D);
2256 }
2257 
2258 /// \brief Instantiates a nested template parameter list in the current
2259 /// instantiation context.
2260 ///
2261 /// \param L The parameter list to instantiate
2262 ///
2263 /// \returns NULL if there was an error
2264 TemplateParameterList *
2265 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2266   // Get errors for all the parameters before bailing out.
2267   bool Invalid = false;
2268 
2269   unsigned N = L->size();
2270   typedef SmallVector<NamedDecl *, 8> ParamVector;
2271   ParamVector Params;
2272   Params.reserve(N);
2273   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2274        PI != PE; ++PI) {
2275     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2276     Params.push_back(D);
2277     Invalid = Invalid || !D || D->isInvalidDecl();
2278   }
2279 
2280   // Clean up if we had an error.
2281   if (Invalid)
2282     return NULL;
2283 
2284   TemplateParameterList *InstL
2285     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2286                                     L->getLAngleLoc(), &Params.front(), N,
2287                                     L->getRAngleLoc());
2288   return InstL;
2289 }
2290 
2291 /// \brief Instantiate the declaration of a class template partial
2292 /// specialization.
2293 ///
2294 /// \param ClassTemplate the (instantiated) class template that is partially
2295 // specialized by the instantiation of \p PartialSpec.
2296 ///
2297 /// \param PartialSpec the (uninstantiated) class template partial
2298 /// specialization that we are instantiating.
2299 ///
2300 /// \returns The instantiated partial specialization, if successful; otherwise,
2301 /// NULL to indicate an error.
2302 ClassTemplatePartialSpecializationDecl *
2303 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2304                                             ClassTemplateDecl *ClassTemplate,
2305                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
2306   // Create a local instantiation scope for this class template partial
2307   // specialization, which will contain the instantiations of the template
2308   // parameters.
2309   LocalInstantiationScope Scope(SemaRef);
2310 
2311   // Substitute into the template parameters of the class template partial
2312   // specialization.
2313   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2314   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2315   if (!InstParams)
2316     return 0;
2317 
2318   // Substitute into the template arguments of the class template partial
2319   // specialization.
2320   TemplateArgumentListInfo InstTemplateArgs; // no angle locations
2321   if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2322                     PartialSpec->getNumTemplateArgsAsWritten(),
2323                     InstTemplateArgs, TemplateArgs))
2324     return 0;
2325 
2326   // Check that the template argument list is well-formed for this
2327   // class template.
2328   SmallVector<TemplateArgument, 4> Converted;
2329   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2330                                         PartialSpec->getLocation(),
2331                                         InstTemplateArgs,
2332                                         false,
2333                                         Converted))
2334     return 0;
2335 
2336   // Figure out where to insert this class template partial specialization
2337   // in the member template's set of class template partial specializations.
2338   void *InsertPos = 0;
2339   ClassTemplateSpecializationDecl *PrevDecl
2340     = ClassTemplate->findPartialSpecialization(Converted.data(),
2341                                                Converted.size(), InsertPos);
2342 
2343   // Build the canonical type that describes the converted template
2344   // arguments of the class template partial specialization.
2345   QualType CanonType
2346     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2347                                                     Converted.data(),
2348                                                     Converted.size());
2349 
2350   // Build the fully-sugared type for this class template
2351   // specialization as the user wrote in the specialization
2352   // itself. This means that we'll pretty-print the type retrieved
2353   // from the specialization's declaration the way that the user
2354   // actually wrote the specialization, rather than formatting the
2355   // name based on the "canonical" representation used to store the
2356   // template arguments in the specialization.
2357   TypeSourceInfo *WrittenTy
2358     = SemaRef.Context.getTemplateSpecializationTypeInfo(
2359                                                     TemplateName(ClassTemplate),
2360                                                     PartialSpec->getLocation(),
2361                                                     InstTemplateArgs,
2362                                                     CanonType);
2363 
2364   if (PrevDecl) {
2365     // We've already seen a partial specialization with the same template
2366     // parameters and template arguments. This can happen, for example, when
2367     // substituting the outer template arguments ends up causing two
2368     // class template partial specializations of a member class template
2369     // to have identical forms, e.g.,
2370     //
2371     //   template<typename T, typename U>
2372     //   struct Outer {
2373     //     template<typename X, typename Y> struct Inner;
2374     //     template<typename Y> struct Inner<T, Y>;
2375     //     template<typename Y> struct Inner<U, Y>;
2376     //   };
2377     //
2378     //   Outer<int, int> outer; // error: the partial specializations of Inner
2379     //                          // have the same signature.
2380     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2381       << WrittenTy->getType();
2382     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2383       << SemaRef.Context.getTypeDeclType(PrevDecl);
2384     return 0;
2385   }
2386 
2387 
2388   // Create the class template partial specialization declaration.
2389   ClassTemplatePartialSpecializationDecl *InstPartialSpec
2390     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2391                                                      PartialSpec->getTagKind(),
2392                                                      Owner,
2393                                                      PartialSpec->getLocStart(),
2394                                                      PartialSpec->getLocation(),
2395                                                      InstParams,
2396                                                      ClassTemplate,
2397                                                      Converted.data(),
2398                                                      Converted.size(),
2399                                                      InstTemplateArgs,
2400                                                      CanonType,
2401                                                      0,
2402                              ClassTemplate->getNextPartialSpecSequenceNumber());
2403   // Substitute the nested name specifier, if any.
2404   if (SubstQualifier(PartialSpec, InstPartialSpec))
2405     return 0;
2406 
2407   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2408   InstPartialSpec->setTypeAsWritten(WrittenTy);
2409 
2410   // Add this partial specialization to the set of class template partial
2411   // specializations.
2412   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2413   return InstPartialSpec;
2414 }
2415 
2416 TypeSourceInfo*
2417 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2418                               SmallVectorImpl<ParmVarDecl *> &Params) {
2419   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2420   assert(OldTInfo && "substituting function without type source info");
2421   assert(Params.empty() && "parameter vector is non-empty at start");
2422 
2423   CXXRecordDecl *ThisContext = 0;
2424   unsigned ThisTypeQuals = 0;
2425   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2426     ThisContext = Method->getParent();
2427     ThisTypeQuals = Method->getTypeQualifiers();
2428   }
2429 
2430   TypeSourceInfo *NewTInfo
2431     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2432                                     D->getTypeSpecStartLoc(),
2433                                     D->getDeclName(),
2434                                     ThisContext, ThisTypeQuals);
2435   if (!NewTInfo)
2436     return 0;
2437 
2438   if (NewTInfo != OldTInfo) {
2439     // Get parameters from the new type info.
2440     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2441     if (FunctionProtoTypeLoc OldProtoLoc =
2442             OldTL.getAs<FunctionProtoTypeLoc>()) {
2443       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2444       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2445       unsigned NewIdx = 0;
2446       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
2447            OldIdx != NumOldParams; ++OldIdx) {
2448         ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
2449         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2450 
2451         Optional<unsigned> NumArgumentsInExpansion;
2452         if (OldParam->isParameterPack())
2453           NumArgumentsInExpansion =
2454               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2455                                                  TemplateArgs);
2456         if (!NumArgumentsInExpansion) {
2457           // Simple case: normal parameter, or a parameter pack that's
2458           // instantiated to a (still-dependent) parameter pack.
2459           ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2460           Params.push_back(NewParam);
2461           Scope->InstantiatedLocal(OldParam, NewParam);
2462         } else {
2463           // Parameter pack expansion: make the instantiation an argument pack.
2464           Scope->MakeInstantiatedLocalArgPack(OldParam);
2465           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2466             ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
2467             Params.push_back(NewParam);
2468             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2469           }
2470         }
2471       }
2472     }
2473   } else {
2474     // The function type itself was not dependent and therefore no
2475     // substitution occurred. However, we still need to instantiate
2476     // the function parameters themselves.
2477     TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2478     if (FunctionProtoTypeLoc OldProtoLoc =
2479             OldTL.getAs<FunctionProtoTypeLoc>()) {
2480       for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
2481         ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc.getArg(i));
2482         if (!Parm)
2483           return 0;
2484         Params.push_back(Parm);
2485       }
2486     }
2487   }
2488   return NewTInfo;
2489 }
2490 
2491 /// Introduce the instantiated function parameters into the local
2492 /// instantiation scope, and set the parameter names to those used
2493 /// in the template.
2494 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2495                                              const FunctionDecl *PatternDecl,
2496                                              LocalInstantiationScope &Scope,
2497                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2498   unsigned FParamIdx = 0;
2499   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2500     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2501     if (!PatternParam->isParameterPack()) {
2502       // Simple case: not a parameter pack.
2503       assert(FParamIdx < Function->getNumParams());
2504       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2505       FunctionParam->setDeclName(PatternParam->getDeclName());
2506       Scope.InstantiatedLocal(PatternParam, FunctionParam);
2507       ++FParamIdx;
2508       continue;
2509     }
2510 
2511     // Expand the parameter pack.
2512     Scope.MakeInstantiatedLocalArgPack(PatternParam);
2513     Optional<unsigned> NumArgumentsInExpansion
2514       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
2515     assert(NumArgumentsInExpansion &&
2516            "should only be called when all template arguments are known");
2517     for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
2518       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2519       FunctionParam->setDeclName(PatternParam->getDeclName());
2520       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2521       ++FParamIdx;
2522     }
2523   }
2524 }
2525 
2526 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2527                                      const FunctionProtoType *Proto,
2528                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2529   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2530 
2531   // C++11 [expr.prim.general]p3:
2532   //   If a declaration declares a member function or member function
2533   //   template of a class X, the expression this is a prvalue of type
2534   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2535   //   and the end of the function-definition, member-declarator, or
2536   //   declarator.
2537   CXXRecordDecl *ThisContext = 0;
2538   unsigned ThisTypeQuals = 0;
2539   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2540     ThisContext = Method->getParent();
2541     ThisTypeQuals = Method->getTypeQualifiers();
2542   }
2543   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2544                                    SemaRef.getLangOpts().CPlusPlus11);
2545 
2546   // The function has an exception specification or a "noreturn"
2547   // attribute. Substitute into each of the exception types.
2548   SmallVector<QualType, 4> Exceptions;
2549   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2550     // FIXME: Poor location information!
2551     if (const PackExpansionType *PackExpansion
2552           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2553       // We have a pack expansion. Instantiate it.
2554       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2555       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2556                                               Unexpanded);
2557       assert(!Unexpanded.empty() &&
2558              "Pack expansion without parameter packs?");
2559 
2560       bool Expand = false;
2561       bool RetainExpansion = false;
2562       Optional<unsigned> NumExpansions
2563                                         = PackExpansion->getNumExpansions();
2564       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2565                                                   SourceRange(),
2566                                                   Unexpanded,
2567                                                   TemplateArgs,
2568                                                   Expand,
2569                                                   RetainExpansion,
2570                                                   NumExpansions))
2571         break;
2572 
2573       if (!Expand) {
2574         // We can't expand this pack expansion into separate arguments yet;
2575         // just substitute into the pattern and create a new pack expansion
2576         // type.
2577         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2578         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2579                                        TemplateArgs,
2580                                      New->getLocation(), New->getDeclName());
2581         if (T.isNull())
2582           break;
2583 
2584         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2585         Exceptions.push_back(T);
2586         continue;
2587       }
2588 
2589       // Substitute into the pack expansion pattern for each template
2590       bool Invalid = false;
2591       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2592         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2593 
2594         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2595                                        TemplateArgs,
2596                                      New->getLocation(), New->getDeclName());
2597         if (T.isNull()) {
2598           Invalid = true;
2599           break;
2600         }
2601 
2602         Exceptions.push_back(T);
2603       }
2604 
2605       if (Invalid)
2606         break;
2607 
2608       continue;
2609     }
2610 
2611     QualType T
2612       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2613                           New->getLocation(), New->getDeclName());
2614     if (T.isNull() ||
2615         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2616       continue;
2617 
2618     Exceptions.push_back(T);
2619   }
2620   Expr *NoexceptExpr = 0;
2621   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2622     EnterExpressionEvaluationContext Unevaluated(SemaRef,
2623                                                  Sema::ConstantEvaluated);
2624     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2625     if (E.isUsable())
2626       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2627 
2628     if (E.isUsable()) {
2629       NoexceptExpr = E.take();
2630       if (!NoexceptExpr->isTypeDependent() &&
2631           !NoexceptExpr->isValueDependent())
2632         NoexceptExpr
2633           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2634               0, diag::err_noexcept_needs_constant_expression,
2635               /*AllowFold*/ false).take();
2636     }
2637   }
2638 
2639   // Rebuild the function type
2640   const FunctionProtoType *NewProto
2641     = New->getType()->getAs<FunctionProtoType>();
2642   assert(NewProto && "Template instantiation without function prototype?");
2643 
2644   FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2645   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2646   EPI.NumExceptions = Exceptions.size();
2647   EPI.Exceptions = Exceptions.data();
2648   EPI.NoexceptExpr = NoexceptExpr;
2649 
2650   New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2651                                   ArrayRef<QualType>(NewProto->arg_type_begin(),
2652                                                      NewProto->getNumArgs()),
2653                                                EPI));
2654 }
2655 
2656 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2657                                     FunctionDecl *Decl) {
2658   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2659   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
2660     return;
2661 
2662   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2663                              InstantiatingTemplate::ExceptionSpecification());
2664   if (Inst) {
2665     // We hit the instantiation depth limit. Clear the exception specification
2666     // so that our callers don't have to cope with EST_Uninstantiated.
2667     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2668     EPI.ExceptionSpecType = EST_None;
2669     Decl->setType(Context.getFunctionType(Proto->getResultType(),
2670                                     ArrayRef<QualType>(Proto->arg_type_begin(),
2671                                                        Proto->getNumArgs()),
2672                                           EPI));
2673     return;
2674   }
2675 
2676   // Enter the scope of this instantiation. We don't use
2677   // PushDeclContext because we don't have a scope.
2678   Sema::ContextRAII savedContext(*this, Decl);
2679   LocalInstantiationScope Scope(*this);
2680 
2681   MultiLevelTemplateArgumentList TemplateArgs =
2682     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2683 
2684   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2685   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
2686 
2687   ::InstantiateExceptionSpec(*this, Decl,
2688                              Template->getType()->castAs<FunctionProtoType>(),
2689                              TemplateArgs);
2690 }
2691 
2692 /// \brief Initializes the common fields of an instantiation function
2693 /// declaration (New) from the corresponding fields of its template (Tmpl).
2694 ///
2695 /// \returns true if there was an error
2696 bool
2697 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
2698                                                     FunctionDecl *Tmpl) {
2699   if (Tmpl->isDeleted())
2700     New->setDeletedAsWritten();
2701 
2702   // If we are performing substituting explicitly-specified template arguments
2703   // or deduced template arguments into a function template and we reach this
2704   // point, we are now past the point where SFINAE applies and have committed
2705   // to keeping the new function template specialization. We therefore
2706   // convert the active template instantiation for the function template
2707   // into a template instantiation for this specific function template
2708   // specialization, which is not a SFINAE context, so that we diagnose any
2709   // further errors in the declaration itself.
2710   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2711   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2712   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2713       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
2714     if (FunctionTemplateDecl *FunTmpl
2715           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
2716       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
2717              "Deduction from the wrong function template?");
2718       (void) FunTmpl;
2719       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2720       ActiveInst.Entity = New;
2721     }
2722   }
2723 
2724   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2725   assert(Proto && "Function template without prototype?");
2726 
2727   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
2728     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2729 
2730     // DR1330: In C++11, defer instantiation of a non-trivial
2731     // exception specification.
2732     if (SemaRef.getLangOpts().CPlusPlus11 &&
2733         EPI.ExceptionSpecType != EST_None &&
2734         EPI.ExceptionSpecType != EST_DynamicNone &&
2735         EPI.ExceptionSpecType != EST_BasicNoexcept) {
2736       FunctionDecl *ExceptionSpecTemplate = Tmpl;
2737       if (EPI.ExceptionSpecType == EST_Uninstantiated)
2738         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
2739       ExceptionSpecificationType NewEST = EST_Uninstantiated;
2740       if (EPI.ExceptionSpecType == EST_Unevaluated)
2741         NewEST = EST_Unevaluated;
2742 
2743       // Mark the function has having an uninstantiated exception specification.
2744       const FunctionProtoType *NewProto
2745         = New->getType()->getAs<FunctionProtoType>();
2746       assert(NewProto && "Template instantiation without function prototype?");
2747       EPI = NewProto->getExtProtoInfo();
2748       EPI.ExceptionSpecType = NewEST;
2749       EPI.ExceptionSpecDecl = New;
2750       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
2751       New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2752                                   ArrayRef<QualType>(NewProto->arg_type_begin(),
2753                                                      NewProto->getNumArgs()),
2754                                                    EPI));
2755     } else {
2756       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2757     }
2758   }
2759 
2760   // Get the definition. Leaves the variable unchanged if undefined.
2761   const FunctionDecl *Definition = Tmpl;
2762   Tmpl->isDefined(Definition);
2763 
2764   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2765                            LateAttrs, StartingScope);
2766 
2767   return false;
2768 }
2769 
2770 /// \brief Initializes common fields of an instantiated method
2771 /// declaration (New) from the corresponding fields of its template
2772 /// (Tmpl).
2773 ///
2774 /// \returns true if there was an error
2775 bool
2776 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
2777                                                   CXXMethodDecl *Tmpl) {
2778   if (InitFunctionInstantiation(New, Tmpl))
2779     return true;
2780 
2781   New->setAccess(Tmpl->getAccess());
2782   if (Tmpl->isVirtualAsWritten())
2783     New->setVirtualAsWritten(true);
2784 
2785   // FIXME: New needs a pointer to Tmpl
2786   return false;
2787 }
2788 
2789 /// \brief Instantiate the definition of the given function from its
2790 /// template.
2791 ///
2792 /// \param PointOfInstantiation the point at which the instantiation was
2793 /// required. Note that this is not precisely a "point of instantiation"
2794 /// for the function, but it's close.
2795 ///
2796 /// \param Function the already-instantiated declaration of a
2797 /// function template specialization or member function of a class template
2798 /// specialization.
2799 ///
2800 /// \param Recursive if true, recursively instantiates any functions that
2801 /// are required by this instantiation.
2802 ///
2803 /// \param DefinitionRequired if true, then we are performing an explicit
2804 /// instantiation where the body of the function is required. Complain if
2805 /// there is no such body.
2806 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
2807                                          FunctionDecl *Function,
2808                                          bool Recursive,
2809                                          bool DefinitionRequired) {
2810   if (Function->isInvalidDecl() || Function->isDefined())
2811     return;
2812 
2813   // Never instantiate an explicit specialization except if it is a class scope
2814   // explicit specialization.
2815   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2816       !Function->getClassScopeSpecializationPattern())
2817     return;
2818 
2819   // Find the function body that we'll be substituting.
2820   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
2821   assert(PatternDecl && "instantiating a non-template");
2822 
2823   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2824   assert(PatternDecl && "template definition is not a template");
2825   if (!Pattern) {
2826     // Try to find a defaulted definition
2827     PatternDecl->isDefined(PatternDecl);
2828   }
2829   assert(PatternDecl && "template definition is not a template");
2830 
2831   // Postpone late parsed template instantiations.
2832   if (PatternDecl->isLateTemplateParsed() &&
2833       !LateTemplateParser) {
2834     PendingInstantiations.push_back(
2835       std::make_pair(Function, PointOfInstantiation));
2836     return;
2837   }
2838 
2839   // Call the LateTemplateParser callback if there a need to late parse
2840   // a templated function definition.
2841   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
2842       LateTemplateParser) {
2843     LateTemplateParser(OpaqueParser, PatternDecl);
2844     Pattern = PatternDecl->getBody(PatternDecl);
2845   }
2846 
2847   if (!Pattern && !PatternDecl->isDefaulted()) {
2848     if (DefinitionRequired) {
2849       if (Function->getPrimaryTemplate())
2850         Diag(PointOfInstantiation,
2851              diag::err_explicit_instantiation_undefined_func_template)
2852           << Function->getPrimaryTemplate();
2853       else
2854         Diag(PointOfInstantiation,
2855              diag::err_explicit_instantiation_undefined_member)
2856           << 1 << Function->getDeclName() << Function->getDeclContext();
2857 
2858       if (PatternDecl)
2859         Diag(PatternDecl->getLocation(),
2860              diag::note_explicit_instantiation_here);
2861       Function->setInvalidDecl();
2862     } else if (Function->getTemplateSpecializationKind()
2863                  == TSK_ExplicitInstantiationDefinition) {
2864       PendingInstantiations.push_back(
2865         std::make_pair(Function, PointOfInstantiation));
2866     }
2867 
2868     return;
2869   }
2870 
2871   // C++1y [temp.explicit]p10:
2872   //   Except for inline functions, declarations with types deduced from their
2873   //   initializer or return value, and class template specializations, other
2874   //   explicit instantiation declarations have the effect of suppressing the
2875   //   implicit instantiation of the entity to which they refer.
2876   if (Function->getTemplateSpecializationKind()
2877         == TSK_ExplicitInstantiationDeclaration &&
2878       !PatternDecl->isInlined() &&
2879       !PatternDecl->getResultType()->isUndeducedType())
2880     return;
2881 
2882   if (PatternDecl->isInlined())
2883     Function->setImplicitlyInline();
2884 
2885   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2886   if (Inst)
2887     return;
2888 
2889   // Copy the inner loc start from the pattern.
2890   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2891 
2892   // If we're performing recursive template instantiation, create our own
2893   // queue of pending implicit instantiations that we will instantiate later,
2894   // while we're still within our own instantiation context.
2895   SmallVector<VTableUse, 16> SavedVTableUses;
2896   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
2897   if (Recursive) {
2898     VTableUses.swap(SavedVTableUses);
2899     PendingInstantiations.swap(SavedPendingInstantiations);
2900   }
2901 
2902   EnterExpressionEvaluationContext EvalContext(*this,
2903                                                Sema::PotentiallyEvaluated);
2904 
2905   // Introduce a new scope where local variable instantiations will be
2906   // recorded, unless we're actually a member function within a local
2907   // class, in which case we need to merge our results with the parent
2908   // scope (of the enclosing function).
2909   bool MergeWithParentScope = false;
2910   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2911     MergeWithParentScope = Rec->isLocalClass();
2912 
2913   LocalInstantiationScope Scope(*this, MergeWithParentScope);
2914 
2915   if (PatternDecl->isDefaulted())
2916     SetDeclDefaulted(Function, PatternDecl->getLocation());
2917   else {
2918     ActOnStartOfFunctionDef(0, Function);
2919 
2920     // Enter the scope of this instantiation. We don't use
2921     // PushDeclContext because we don't have a scope.
2922     Sema::ContextRAII savedContext(*this, Function);
2923 
2924     MultiLevelTemplateArgumentList TemplateArgs =
2925       getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2926 
2927     addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2928                                      TemplateArgs);
2929 
2930     // If this is a constructor, instantiate the member initializers.
2931     if (const CXXConstructorDecl *Ctor =
2932           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2933       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2934                                  TemplateArgs);
2935     }
2936 
2937     // Instantiate the function body.
2938     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2939 
2940     if (Body.isInvalid())
2941       Function->setInvalidDecl();
2942 
2943     ActOnFinishFunctionBody(Function, Body.get(),
2944                             /*IsInstantiation=*/true);
2945 
2946     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2947 
2948     savedContext.pop();
2949   }
2950 
2951   DeclGroupRef DG(Function);
2952   Consumer.HandleTopLevelDecl(DG);
2953 
2954   // This class may have local implicit instantiations that need to be
2955   // instantiation within this scope.
2956   PerformPendingInstantiations(/*LocalOnly=*/true);
2957   Scope.Exit();
2958 
2959   if (Recursive) {
2960     // Define any pending vtables.
2961     DefineUsedVTables();
2962 
2963     // Instantiate any pending implicit instantiations found during the
2964     // instantiation of this template.
2965     PerformPendingInstantiations();
2966 
2967     // Restore the set of pending vtables.
2968     assert(VTableUses.empty() &&
2969            "VTableUses should be empty before it is discarded.");
2970     VTableUses.swap(SavedVTableUses);
2971 
2972     // Restore the set of pending implicit instantiations.
2973     assert(PendingInstantiations.empty() &&
2974            "PendingInstantiations should be empty before it is discarded.");
2975     PendingInstantiations.swap(SavedPendingInstantiations);
2976   }
2977 }
2978 
2979 /// \brief Instantiate the definition of the given variable from its
2980 /// template.
2981 ///
2982 /// \param PointOfInstantiation the point at which the instantiation was
2983 /// required. Note that this is not precisely a "point of instantiation"
2984 /// for the function, but it's close.
2985 ///
2986 /// \param Var the already-instantiated declaration of a static member
2987 /// variable of a class template specialization.
2988 ///
2989 /// \param Recursive if true, recursively instantiates any functions that
2990 /// are required by this instantiation.
2991 ///
2992 /// \param DefinitionRequired if true, then we are performing an explicit
2993 /// instantiation where an out-of-line definition of the member variable
2994 /// is required. Complain if there is no such definition.
2995 void Sema::InstantiateStaticDataMemberDefinition(
2996                                           SourceLocation PointOfInstantiation,
2997                                                  VarDecl *Var,
2998                                                  bool Recursive,
2999                                                  bool DefinitionRequired) {
3000   if (Var->isInvalidDecl())
3001     return;
3002 
3003   // Find the out-of-line definition of this static data member.
3004   VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
3005   assert(Def && "This data member was not instantiated from a template?");
3006   assert(Def->isStaticDataMember() && "Not a static data member?");
3007   Def = Def->getOutOfLineDefinition();
3008 
3009   if (!Def) {
3010     // We did not find an out-of-line definition of this static data member,
3011     // so we won't perform any instantiation. Rather, we rely on the user to
3012     // instantiate this definition (or provide a specialization for it) in
3013     // another translation unit.
3014     if (DefinitionRequired) {
3015       Def = Var->getInstantiatedFromStaticDataMember();
3016       Diag(PointOfInstantiation,
3017            diag::err_explicit_instantiation_undefined_member)
3018         << 2 << Var->getDeclName() << Var->getDeclContext();
3019       Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
3020     } else if (Var->getTemplateSpecializationKind()
3021                  == TSK_ExplicitInstantiationDefinition) {
3022       PendingInstantiations.push_back(
3023         std::make_pair(Var, PointOfInstantiation));
3024     }
3025 
3026     return;
3027   }
3028 
3029   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3030 
3031   // Never instantiate an explicit specialization.
3032   if (TSK == TSK_ExplicitSpecialization)
3033     return;
3034 
3035   // C++0x [temp.explicit]p9:
3036   //   Except for inline functions, other explicit instantiation declarations
3037   //   have the effect of suppressing the implicit instantiation of the entity
3038   //   to which they refer.
3039   if (TSK == TSK_ExplicitInstantiationDeclaration)
3040     return;
3041 
3042   // Make sure to pass the instantiated variable to the consumer at the end.
3043   struct PassToConsumerRAII {
3044     ASTConsumer &Consumer;
3045     VarDecl *Var;
3046 
3047     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3048       : Consumer(Consumer), Var(Var) { }
3049 
3050     ~PassToConsumerRAII() {
3051       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3052     }
3053   } PassToConsumerRAII(Consumer, Var);
3054 
3055   // If we already have a definition, we're done.
3056   if (VarDecl *Def = Var->getDefinition()) {
3057     // We may be explicitly instantiating something we've already implicitly
3058     // instantiated.
3059     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3060                                        PointOfInstantiation);
3061     return;
3062   }
3063 
3064   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3065   if (Inst)
3066     return;
3067 
3068   // If we're performing recursive template instantiation, create our own
3069   // queue of pending implicit instantiations that we will instantiate later,
3070   // while we're still within our own instantiation context.
3071   SmallVector<VTableUse, 16> SavedVTableUses;
3072   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3073   if (Recursive) {
3074     VTableUses.swap(SavedVTableUses);
3075     PendingInstantiations.swap(SavedPendingInstantiations);
3076   }
3077 
3078   // Enter the scope of this instantiation. We don't use
3079   // PushDeclContext because we don't have a scope.
3080   ContextRAII previousContext(*this, Var->getDeclContext());
3081   LocalInstantiationScope Local(*this);
3082 
3083   VarDecl *OldVar = Var;
3084   Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3085                                         getTemplateInstantiationArgs(Var)));
3086 
3087   previousContext.pop();
3088 
3089   if (Var) {
3090     PassToConsumerRAII.Var = Var;
3091     MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3092     assert(MSInfo && "Missing member specialization information?");
3093     Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3094                                        MSInfo->getPointOfInstantiation());
3095   }
3096   Local.Exit();
3097 
3098   if (Recursive) {
3099     // Define any newly required vtables.
3100     DefineUsedVTables();
3101 
3102     // Instantiate any pending implicit instantiations found during the
3103     // instantiation of this template.
3104     PerformPendingInstantiations();
3105 
3106     // Restore the set of pending vtables.
3107     assert(VTableUses.empty() &&
3108            "VTableUses should be empty before it is discarded, "
3109            "while instantiating static data member.");
3110     VTableUses.swap(SavedVTableUses);
3111 
3112     // Restore the set of pending implicit instantiations.
3113     assert(PendingInstantiations.empty() &&
3114            "PendingInstantiations should be empty before it is discarded, "
3115            "while instantiating static data member.");
3116     PendingInstantiations.swap(SavedPendingInstantiations);
3117   }
3118 }
3119 
3120 void
3121 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3122                                  const CXXConstructorDecl *Tmpl,
3123                            const MultiLevelTemplateArgumentList &TemplateArgs) {
3124 
3125   SmallVector<CXXCtorInitializer*, 4> NewInits;
3126   bool AnyErrors = Tmpl->isInvalidDecl();
3127 
3128   // Instantiate all the initializers.
3129   for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
3130                                             InitsEnd = Tmpl->init_end();
3131        Inits != InitsEnd; ++Inits) {
3132     CXXCtorInitializer *Init = *Inits;
3133 
3134     // Only instantiate written initializers, let Sema re-construct implicit
3135     // ones.
3136     if (!Init->isWritten())
3137       continue;
3138 
3139     SourceLocation EllipsisLoc;
3140 
3141     if (Init->isPackExpansion()) {
3142       // This is a pack expansion. We should expand it now.
3143       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
3144       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3145       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3146       bool ShouldExpand = false;
3147       bool RetainExpansion = false;
3148       Optional<unsigned> NumExpansions;
3149       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
3150                                           BaseTL.getSourceRange(),
3151                                           Unexpanded,
3152                                           TemplateArgs, ShouldExpand,
3153                                           RetainExpansion,
3154                                           NumExpansions)) {
3155         AnyErrors = true;
3156         New->setInvalidDecl();
3157         continue;
3158       }
3159       assert(ShouldExpand && "Partial instantiation of base initializer?");
3160 
3161       // Loop over all of the arguments in the argument pack(s),
3162       for (unsigned I = 0; I != *NumExpansions; ++I) {
3163         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3164 
3165         // Instantiate the initializer.
3166         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3167                                                /*CXXDirectInit=*/true);
3168         if (TempInit.isInvalid()) {
3169           AnyErrors = true;
3170           break;
3171         }
3172 
3173         // Instantiate the base type.
3174         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
3175                                               TemplateArgs,
3176                                               Init->getSourceLocation(),
3177                                               New->getDeclName());
3178         if (!BaseTInfo) {
3179           AnyErrors = true;
3180           break;
3181         }
3182 
3183         // Build the initializer.
3184         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
3185                                                      BaseTInfo, TempInit.take(),
3186                                                      New->getParent(),
3187                                                      SourceLocation());
3188         if (NewInit.isInvalid()) {
3189           AnyErrors = true;
3190           break;
3191         }
3192 
3193         NewInits.push_back(NewInit.get());
3194       }
3195 
3196       continue;
3197     }
3198 
3199     // Instantiate the initializer.
3200     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3201                                            /*CXXDirectInit=*/true);
3202     if (TempInit.isInvalid()) {
3203       AnyErrors = true;
3204       continue;
3205     }
3206 
3207     MemInitResult NewInit;
3208     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3209       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3210                                         TemplateArgs,
3211                                         Init->getSourceLocation(),
3212                                         New->getDeclName());
3213       if (!TInfo) {
3214         AnyErrors = true;
3215         New->setInvalidDecl();
3216         continue;
3217       }
3218 
3219       if (Init->isBaseInitializer())
3220         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
3221                                        New->getParent(), EllipsisLoc);
3222       else
3223         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
3224                                   cast<CXXRecordDecl>(CurContext->getParent()));
3225     } else if (Init->isMemberInitializer()) {
3226       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
3227                                                      Init->getMemberLocation(),
3228                                                      Init->getMember(),
3229                                                      TemplateArgs));
3230       if (!Member) {
3231         AnyErrors = true;
3232         New->setInvalidDecl();
3233         continue;
3234       }
3235 
3236       NewInit = BuildMemberInitializer(Member, TempInit.take(),
3237                                        Init->getSourceLocation());
3238     } else if (Init->isIndirectMemberInitializer()) {
3239       IndirectFieldDecl *IndirectMember =
3240          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
3241                                  Init->getMemberLocation(),
3242                                  Init->getIndirectMember(), TemplateArgs));
3243 
3244       if (!IndirectMember) {
3245         AnyErrors = true;
3246         New->setInvalidDecl();
3247         continue;
3248       }
3249 
3250       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
3251                                        Init->getSourceLocation());
3252     }
3253 
3254     if (NewInit.isInvalid()) {
3255       AnyErrors = true;
3256       New->setInvalidDecl();
3257     } else {
3258       NewInits.push_back(NewInit.get());
3259     }
3260   }
3261 
3262   // Assign all the initializers to the new constructor.
3263   ActOnMemInitializers(New,
3264                        /*FIXME: ColonLoc */
3265                        SourceLocation(),
3266                        NewInits,
3267                        AnyErrors);
3268 }
3269 
3270 // TODO: this could be templated if the various decl types used the
3271 // same method name.
3272 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3273                               ClassTemplateDecl *Instance) {
3274   Pattern = Pattern->getCanonicalDecl();
3275 
3276   do {
3277     Instance = Instance->getCanonicalDecl();
3278     if (Pattern == Instance) return true;
3279     Instance = Instance->getInstantiatedFromMemberTemplate();
3280   } while (Instance);
3281 
3282   return false;
3283 }
3284 
3285 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3286                               FunctionTemplateDecl *Instance) {
3287   Pattern = Pattern->getCanonicalDecl();
3288 
3289   do {
3290     Instance = Instance->getCanonicalDecl();
3291     if (Pattern == Instance) return true;
3292     Instance = Instance->getInstantiatedFromMemberTemplate();
3293   } while (Instance);
3294 
3295   return false;
3296 }
3297 
3298 static bool
3299 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3300                   ClassTemplatePartialSpecializationDecl *Instance) {
3301   Pattern
3302     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3303   do {
3304     Instance = cast<ClassTemplatePartialSpecializationDecl>(
3305                                                 Instance->getCanonicalDecl());
3306     if (Pattern == Instance)
3307       return true;
3308     Instance = Instance->getInstantiatedFromMember();
3309   } while (Instance);
3310 
3311   return false;
3312 }
3313 
3314 static bool isInstantiationOf(CXXRecordDecl *Pattern,
3315                               CXXRecordDecl *Instance) {
3316   Pattern = Pattern->getCanonicalDecl();
3317 
3318   do {
3319     Instance = Instance->getCanonicalDecl();
3320     if (Pattern == Instance) return true;
3321     Instance = Instance->getInstantiatedFromMemberClass();
3322   } while (Instance);
3323 
3324   return false;
3325 }
3326 
3327 static bool isInstantiationOf(FunctionDecl *Pattern,
3328                               FunctionDecl *Instance) {
3329   Pattern = Pattern->getCanonicalDecl();
3330 
3331   do {
3332     Instance = Instance->getCanonicalDecl();
3333     if (Pattern == Instance) return true;
3334     Instance = Instance->getInstantiatedFromMemberFunction();
3335   } while (Instance);
3336 
3337   return false;
3338 }
3339 
3340 static bool isInstantiationOf(EnumDecl *Pattern,
3341                               EnumDecl *Instance) {
3342   Pattern = Pattern->getCanonicalDecl();
3343 
3344   do {
3345     Instance = Instance->getCanonicalDecl();
3346     if (Pattern == Instance) return true;
3347     Instance = Instance->getInstantiatedFromMemberEnum();
3348   } while (Instance);
3349 
3350   return false;
3351 }
3352 
3353 static bool isInstantiationOf(UsingShadowDecl *Pattern,
3354                               UsingShadowDecl *Instance,
3355                               ASTContext &C) {
3356   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3357 }
3358 
3359 static bool isInstantiationOf(UsingDecl *Pattern,
3360                               UsingDecl *Instance,
3361                               ASTContext &C) {
3362   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3363 }
3364 
3365 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3366                               UsingDecl *Instance,
3367                               ASTContext &C) {
3368   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3369 }
3370 
3371 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
3372                               UsingDecl *Instance,
3373                               ASTContext &C) {
3374   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3375 }
3376 
3377 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3378                                               VarDecl *Instance) {
3379   assert(Instance->isStaticDataMember());
3380 
3381   Pattern = Pattern->getCanonicalDecl();
3382 
3383   do {
3384     Instance = Instance->getCanonicalDecl();
3385     if (Pattern == Instance) return true;
3386     Instance = Instance->getInstantiatedFromStaticDataMember();
3387   } while (Instance);
3388 
3389   return false;
3390 }
3391 
3392 // Other is the prospective instantiation
3393 // D is the prospective pattern
3394 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
3395   if (D->getKind() != Other->getKind()) {
3396     if (UnresolvedUsingTypenameDecl *UUD
3397           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3398       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3399         return isInstantiationOf(UUD, UD, Ctx);
3400       }
3401     }
3402 
3403     if (UnresolvedUsingValueDecl *UUD
3404           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3405       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3406         return isInstantiationOf(UUD, UD, Ctx);
3407       }
3408     }
3409 
3410     return false;
3411   }
3412 
3413   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3414     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
3415 
3416   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3417     return isInstantiationOf(cast<FunctionDecl>(D), Function);
3418 
3419   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3420     return isInstantiationOf(cast<EnumDecl>(D), Enum);
3421 
3422   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
3423     if (Var->isStaticDataMember())
3424       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3425 
3426   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3427     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
3428 
3429   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3430     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3431 
3432   if (ClassTemplatePartialSpecializationDecl *PartialSpec
3433         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3434     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3435                              PartialSpec);
3436 
3437   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3438     if (!Field->getDeclName()) {
3439       // This is an unnamed field.
3440       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
3441         cast<FieldDecl>(D);
3442     }
3443   }
3444 
3445   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3446     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3447 
3448   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3449     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3450 
3451   return D->getDeclName() && isa<NamedDecl>(Other) &&
3452     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3453 }
3454 
3455 template<typename ForwardIterator>
3456 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
3457                                       NamedDecl *D,
3458                                       ForwardIterator first,
3459                                       ForwardIterator last) {
3460   for (; first != last; ++first)
3461     if (isInstantiationOf(Ctx, D, *first))
3462       return cast<NamedDecl>(*first);
3463 
3464   return 0;
3465 }
3466 
3467 /// \brief Finds the instantiation of the given declaration context
3468 /// within the current instantiation.
3469 ///
3470 /// \returns NULL if there was an error
3471 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
3472                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3473   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
3474     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
3475     return cast_or_null<DeclContext>(ID);
3476   } else return DC;
3477 }
3478 
3479 /// \brief Find the instantiation of the given declaration within the
3480 /// current instantiation.
3481 ///
3482 /// This routine is intended to be used when \p D is a declaration
3483 /// referenced from within a template, that needs to mapped into the
3484 /// corresponding declaration within an instantiation. For example,
3485 /// given:
3486 ///
3487 /// \code
3488 /// template<typename T>
3489 /// struct X {
3490 ///   enum Kind {
3491 ///     KnownValue = sizeof(T)
3492 ///   };
3493 ///
3494 ///   bool getKind() const { return KnownValue; }
3495 /// };
3496 ///
3497 /// template struct X<int>;
3498 /// \endcode
3499 ///
3500 /// In the instantiation of X<int>::getKind(), we need to map the
3501 /// EnumConstantDecl for KnownValue (which refers to
3502 /// X<T>::\<Kind>\::KnownValue) to its instantiation
3503 /// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
3504 /// this mapping from within the instantiation of X<int>.
3505 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
3506                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3507   DeclContext *ParentDC = D->getDeclContext();
3508   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
3509       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
3510       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3511       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
3512     // D is a local of some kind. Look into the map of local
3513     // declarations to their instantiations.
3514     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3515     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3516       = CurrentInstantiationScope->findInstantiationOf(D);
3517 
3518     if (Found) {
3519       if (Decl *FD = Found->dyn_cast<Decl *>())
3520         return cast<NamedDecl>(FD);
3521 
3522       int PackIdx = ArgumentPackSubstitutionIndex;
3523       assert(PackIdx != -1 && "found declaration pack but not pack expanding");
3524       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3525     }
3526 
3527     // If we didn't find the decl, then we must have a label decl that hasn't
3528     // been found yet.  Lazily instantiate it and return it now.
3529     assert(isa<LabelDecl>(D));
3530 
3531     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3532     assert(Inst && "Failed to instantiate label??");
3533 
3534     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3535     return cast<LabelDecl>(Inst);
3536   }
3537 
3538   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3539     if (!Record->isDependentContext())
3540       return D;
3541 
3542     // Determine whether this record is the "templated" declaration describing
3543     // a class template or class template partial specialization.
3544     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
3545     if (ClassTemplate)
3546       ClassTemplate = ClassTemplate->getCanonicalDecl();
3547     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3548                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3549       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3550 
3551     // Walk the current context to find either the record or an instantiation of
3552     // it.
3553     DeclContext *DC = CurContext;
3554     while (!DC->isFileContext()) {
3555       // If we're performing substitution while we're inside the template
3556       // definition, we'll find our own context. We're done.
3557       if (DC->Equals(Record))
3558         return Record;
3559 
3560       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3561         // Check whether we're in the process of instantiating a class template
3562         // specialization of the template we're mapping.
3563         if (ClassTemplateSpecializationDecl *InstSpec
3564                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3565           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3566           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3567             return InstRecord;
3568         }
3569 
3570         // Check whether we're in the process of instantiating a member class.
3571         if (isInstantiationOf(Record, InstRecord))
3572           return InstRecord;
3573       }
3574 
3575 
3576       // Move to the outer template scope.
3577       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3578         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3579           DC = FD->getLexicalDeclContext();
3580           continue;
3581         }
3582       }
3583 
3584       DC = DC->getParent();
3585     }
3586 
3587     // Fall through to deal with other dependent record types (e.g.,
3588     // anonymous unions in class templates).
3589   }
3590 
3591   if (!ParentDC->isDependentContext())
3592     return D;
3593 
3594   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
3595   if (!ParentDC)
3596     return 0;
3597 
3598   if (ParentDC != D->getDeclContext()) {
3599     // We performed some kind of instantiation in the parent context,
3600     // so now we need to look into the instantiated parent context to
3601     // find the instantiation of the declaration D.
3602 
3603     // If our context used to be dependent, we may need to instantiate
3604     // it before performing lookup into that context.
3605     bool IsBeingInstantiated = false;
3606     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
3607       if (!Spec->isDependentContext()) {
3608         QualType T = Context.getTypeDeclType(Spec);
3609         const RecordType *Tag = T->getAs<RecordType>();
3610         assert(Tag && "type of non-dependent record is not a RecordType");
3611         if (Tag->isBeingDefined())
3612           IsBeingInstantiated = true;
3613         if (!Tag->isBeingDefined() &&
3614             RequireCompleteType(Loc, T, diag::err_incomplete_type))
3615           return 0;
3616 
3617         ParentDC = Tag->getDecl();
3618       }
3619     }
3620 
3621     NamedDecl *Result = 0;
3622     if (D->getDeclName()) {
3623       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
3624       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
3625     } else {
3626       // Since we don't have a name for the entity we're looking for,
3627       // our only option is to walk through all of the declarations to
3628       // find that name. This will occur in a few cases:
3629       //
3630       //   - anonymous struct/union within a template
3631       //   - unnamed class/struct/union/enum within a template
3632       //
3633       // FIXME: Find a better way to find these instantiations!
3634       Result = findInstantiationOf(Context, D,
3635                                    ParentDC->decls_begin(),
3636                                    ParentDC->decls_end());
3637     }
3638 
3639     if (!Result) {
3640       if (isa<UsingShadowDecl>(D)) {
3641         // UsingShadowDecls can instantiate to nothing because of using hiding.
3642       } else if (Diags.hasErrorOccurred()) {
3643         // We've already complained about something, so most likely this
3644         // declaration failed to instantiate. There's no point in complaining
3645         // further, since this is normal in invalid code.
3646       } else if (IsBeingInstantiated) {
3647         // The class in which this member exists is currently being
3648         // instantiated, and we haven't gotten around to instantiating this
3649         // member yet. This can happen when the code uses forward declarations
3650         // of member classes, and introduces ordering dependencies via
3651         // template instantiation.
3652         Diag(Loc, diag::err_member_not_yet_instantiated)
3653           << D->getDeclName()
3654           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3655         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3656       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3657         // This enumeration constant was found when the template was defined,
3658         // but can't be found in the instantiation. This can happen if an
3659         // unscoped enumeration member is explicitly specialized.
3660         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3661         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3662                                                              TemplateArgs));
3663         assert(Spec->getTemplateSpecializationKind() ==
3664                  TSK_ExplicitSpecialization);
3665         Diag(Loc, diag::err_enumerator_does_not_exist)
3666           << D->getDeclName()
3667           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3668         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3669           << Context.getTypeDeclType(Spec);
3670       } else {
3671         // We should have found something, but didn't.
3672         llvm_unreachable("Unable to find instantiation of declaration!");
3673       }
3674     }
3675 
3676     D = Result;
3677   }
3678 
3679   return D;
3680 }
3681 
3682 /// \brief Performs template instantiation for all implicit template
3683 /// instantiations we have seen until this point.
3684 void Sema::PerformPendingInstantiations(bool LocalOnly) {
3685   // Load pending instantiations from the external source.
3686   if (!LocalOnly && ExternalSource) {
3687     SmallVector<PendingImplicitInstantiation, 4> Pending;
3688     ExternalSource->ReadPendingInstantiations(Pending);
3689     PendingInstantiations.insert(PendingInstantiations.begin(),
3690                                  Pending.begin(), Pending.end());
3691   }
3692 
3693   while (!PendingLocalImplicitInstantiations.empty() ||
3694          (!LocalOnly && !PendingInstantiations.empty())) {
3695     PendingImplicitInstantiation Inst;
3696 
3697     if (PendingLocalImplicitInstantiations.empty()) {
3698       Inst = PendingInstantiations.front();
3699       PendingInstantiations.pop_front();
3700     } else {
3701       Inst = PendingLocalImplicitInstantiations.front();
3702       PendingLocalImplicitInstantiations.pop_front();
3703     }
3704 
3705     // Instantiate function definitions
3706     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
3707       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3708                                           "instantiating function definition");
3709       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3710                                 TSK_ExplicitInstantiationDefinition;
3711       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3712                                     DefinitionRequired);
3713       continue;
3714     }
3715 
3716     // Instantiate static data member definitions.
3717     VarDecl *Var = cast<VarDecl>(Inst.first);
3718     assert(Var->isStaticDataMember() && "Not a static data member?");
3719 
3720     // Don't try to instantiate declarations if the most recent redeclaration
3721     // is invalid.
3722     if (Var->getMostRecentDecl()->isInvalidDecl())
3723       continue;
3724 
3725     // Check if the most recent declaration has changed the specialization kind
3726     // and removed the need for implicit instantiation.
3727     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
3728     case TSK_Undeclared:
3729       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
3730     case TSK_ExplicitInstantiationDeclaration:
3731     case TSK_ExplicitSpecialization:
3732       continue;  // No longer need to instantiate this type.
3733     case TSK_ExplicitInstantiationDefinition:
3734       // We only need an instantiation if the pending instantiation *is* the
3735       // explicit instantiation.
3736       if (Var != Var->getMostRecentDecl()) continue;
3737     case TSK_ImplicitInstantiation:
3738       break;
3739     }
3740 
3741     PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3742                                         "instantiating static data member "
3743                                         "definition");
3744 
3745     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3746                               TSK_ExplicitInstantiationDefinition;
3747     InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3748                                           DefinitionRequired);
3749   }
3750 }
3751 
3752 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3753                        const MultiLevelTemplateArgumentList &TemplateArgs) {
3754   for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3755          E = Pattern->ddiag_end(); I != E; ++I) {
3756     DependentDiagnostic *DD = *I;
3757 
3758     switch (DD->getKind()) {
3759     case DependentDiagnostic::Access:
3760       HandleDependentAccessCheck(*DD, TemplateArgs);
3761       break;
3762     }
3763   }
3764 }
3765