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/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.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 static bool isDeclWithinFunction(const Decl *D) {
29   const DeclContext *DC = D->getDeclContext();
30   if (DC->isFunctionOrMethod())
31     return true;
32 
33   if (DC->isRecord())
34     return cast<CXXRecordDecl>(DC)->isLocalClass();
35 
36   return false;
37 }
38 
39 template<typename DeclT>
40 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41                            const MultiLevelTemplateArgumentList &TemplateArgs) {
42   if (!OldDecl->getQualifierLoc())
43     return false;
44 
45   assert((NewDecl->getFriendObjectKind() ||
46           !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47          "non-friend with qualified name defined in dependent context");
48   Sema::ContextRAII SavedContext(
49       SemaRef,
50       const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51                                     ? NewDecl->getLexicalDeclContext()
52                                     : OldDecl->getLexicalDeclContext()));
53 
54   NestedNameSpecifierLoc NewQualifierLoc
55       = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56                                             TemplateArgs);
57 
58   if (!NewQualifierLoc)
59     return true;
60 
61   NewDecl->setQualifierInfo(NewQualifierLoc);
62   return false;
63 }
64 
65 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66                                               DeclaratorDecl *NewDecl) {
67   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
68 }
69 
70 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
71                                               TagDecl *NewDecl) {
72   return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
73 }
74 
75 // Include attribute instantiation code.
76 #include "clang/Sema/AttrTemplateInstantiate.inc"
77 
78 static void instantiateDependentAlignedAttr(
79     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81   if (Aligned->isAlignmentExpr()) {
82     // The alignment expression is a constant expression.
83     EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85     if (!Result.isInvalid())
86       S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
87                        Aligned->getSpellingListIndex(), IsPackExpansion);
88   } else {
89     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90                                          TemplateArgs, Aligned->getLocation(),
91                                          DeclarationName());
92     if (Result)
93       S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94                        Aligned->getSpellingListIndex(), IsPackExpansion);
95   }
96 }
97 
98 static void instantiateDependentAlignedAttr(
99     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100     const AlignedAttr *Aligned, Decl *New) {
101   if (!Aligned->isPackExpansion()) {
102     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
103     return;
104   }
105 
106   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107   if (Aligned->isAlignmentExpr())
108     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
109                                       Unexpanded);
110   else
111     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
112                                       Unexpanded);
113   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
114 
115   // Determine whether we can expand this attribute pack yet.
116   bool Expand = true, RetainExpansion = false;
117   Optional<unsigned> NumExpansions;
118   // FIXME: Use the actual location of the ellipsis.
119   SourceLocation EllipsisLoc = Aligned->getLocation();
120   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121                                         Unexpanded, TemplateArgs, Expand,
122                                         RetainExpansion, NumExpansions))
123     return;
124 
125   if (!Expand) {
126     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
128   } else {
129     for (unsigned I = 0; I != *NumExpansions; ++I) {
130       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132     }
133   }
134 }
135 
136 static void instantiateDependentAssumeAlignedAttr(
137     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138     const AssumeAlignedAttr *Aligned, Decl *New) {
139   // The alignment expression is a constant expression.
140   EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
141 
142   Expr *E, *OE = nullptr;
143   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144   if (Result.isInvalid())
145     return;
146   E = Result.getAs<Expr>();
147 
148   if (Aligned->getOffset()) {
149     Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150     if (Result.isInvalid())
151       return;
152     OE = Result.getAs<Expr>();
153   }
154 
155   S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156                          Aligned->getSpellingListIndex());
157 }
158 
159 static void instantiateDependentAlignValueAttr(
160     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161     const AlignValueAttr *Aligned, Decl *New) {
162   // The alignment expression is a constant expression.
163   EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164   ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165   if (!Result.isInvalid())
166     S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167                         Aligned->getSpellingListIndex());
168 }
169 
170 static void instantiateDependentEnableIfAttr(
171     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172     const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
173   Expr *Cond = nullptr;
174   {
175     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176     ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177     if (Result.isInvalid())
178       return;
179     Cond = Result.getAs<Expr>();
180   }
181   if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183     if (Converted.isInvalid())
184       return;
185     Cond = Converted.get();
186   }
187 
188   SmallVector<PartialDiagnosticAt, 8> Diags;
189   if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
191                                                 Diags)) {
192     S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193     for (int I = 0, N = Diags.size(); I != N; ++I)
194       S.Diag(Diags[I].first, Diags[I].second);
195     return;
196   }
197 
198   EnableIfAttr *EIA = new (S.getASTContext())
199                         EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
200                                      A->getMessage(),
201                                      A->getSpellingListIndex());
202   New->addAttr(EIA);
203 }
204 
205 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
206 // template A as the base and arguments from TemplateArgs.
207 static void instantiateDependentCUDALaunchBoundsAttr(
208     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
209     const CUDALaunchBoundsAttr &Attr, Decl *New) {
210   // The alignment expression is a constant expression.
211   EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
212 
213   ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
214   if (Result.isInvalid())
215     return;
216   Expr *MaxThreads = Result.getAs<Expr>();
217 
218   Expr *MinBlocks = nullptr;
219   if (Attr.getMinBlocks()) {
220     Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
221     if (Result.isInvalid())
222       return;
223     MinBlocks = Result.getAs<Expr>();
224   }
225 
226   S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks,
227                         Attr.getSpellingListIndex());
228 }
229 
230 static void
231 instantiateDependentModeAttr(Sema &S,
232                              const MultiLevelTemplateArgumentList &TemplateArgs,
233                              const ModeAttr &Attr, Decl *New) {
234   S.AddModeAttr(Attr.getRange(), New, Attr.getMode(),
235                 Attr.getSpellingListIndex(), /*InInstantiation=*/true);
236 }
237 
238 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
239                             const Decl *Tmpl, Decl *New,
240                             LateInstantiatedAttrVec *LateAttrs,
241                             LocalInstantiationScope *OuterMostScope) {
242   for (const auto *TmplAttr : Tmpl->attrs()) {
243     // FIXME: This should be generalized to more than just the AlignedAttr.
244     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
245     if (Aligned && Aligned->isAlignmentDependent()) {
246       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
247       continue;
248     }
249 
250     const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
251     if (AssumeAligned) {
252       instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
253       continue;
254     }
255 
256     const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
257     if (AlignValue) {
258       instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
259       continue;
260     }
261 
262     const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
263     if (EnableIf && EnableIf->getCond()->isValueDependent()) {
264       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
265                                        New);
266       continue;
267     }
268 
269     if (const CUDALaunchBoundsAttr *CUDALaunchBounds =
270             dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
271       instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
272                                                *CUDALaunchBounds, New);
273       continue;
274     }
275 
276     if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
277       instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
278       continue;
279     }
280 
281     // Existing DLL attribute on the instantiation takes precedence.
282     if (TmplAttr->getKind() == attr::DLLExport ||
283         TmplAttr->getKind() == attr::DLLImport) {
284       if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
285         continue;
286       }
287     }
288 
289     if (isa<NSConsumedAttr>(TmplAttr) || isa<CFConsumedAttr>(TmplAttr)) {
290       AddNSConsumedAttr(TmplAttr->getRange(), New,
291                         TmplAttr->getSpellingListIndex(),
292                         isa<NSConsumedAttr>(TmplAttr),
293                         /*template instantiation*/ true);
294       continue;
295     }
296 
297     assert(!TmplAttr->isPackExpansion());
298     if (TmplAttr->isLateParsed() && LateAttrs) {
299       // Late parsed attributes must be instantiated and attached after the
300       // enclosing class has been instantiated.  See Sema::InstantiateClass.
301       LocalInstantiationScope *Saved = nullptr;
302       if (CurrentInstantiationScope)
303         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
304       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
305     } else {
306       // Allow 'this' within late-parsed attributes.
307       NamedDecl *ND = dyn_cast<NamedDecl>(New);
308       CXXRecordDecl *ThisContext =
309           dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
310       CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
311                                  ND && ND->isCXXInstanceMember());
312 
313       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
314                                                          *this, TemplateArgs);
315       if (NewAttr)
316         New->addAttr(NewAttr);
317     }
318   }
319 }
320 
321 /// Get the previous declaration of a declaration for the purposes of template
322 /// instantiation. If this finds a previous declaration, then the previous
323 /// declaration of the instantiation of D should be an instantiation of the
324 /// result of this function.
325 template<typename DeclT>
326 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
327   DeclT *Result = D->getPreviousDecl();
328 
329   // If the declaration is within a class, and the previous declaration was
330   // merged from a different definition of that class, then we don't have a
331   // previous declaration for the purpose of template instantiation.
332   if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
333       D->getLexicalDeclContext() != Result->getLexicalDeclContext())
334     return nullptr;
335 
336   return Result;
337 }
338 
339 Decl *
340 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
341   llvm_unreachable("Translation units cannot be instantiated");
342 }
343 
344 Decl *
345 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
346   llvm_unreachable("pragma comment cannot be instantiated");
347 }
348 
349 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
350     PragmaDetectMismatchDecl *D) {
351   llvm_unreachable("pragma comment cannot be instantiated");
352 }
353 
354 Decl *
355 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
356   llvm_unreachable("extern \"C\" context cannot be instantiated");
357 }
358 
359 Decl *
360 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
361   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
362                                       D->getIdentifier());
363   Owner->addDecl(Inst);
364   return Inst;
365 }
366 
367 Decl *
368 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
369   llvm_unreachable("Namespaces cannot be instantiated");
370 }
371 
372 Decl *
373 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
374   NamespaceAliasDecl *Inst
375     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
376                                  D->getNamespaceLoc(),
377                                  D->getAliasLoc(),
378                                  D->getIdentifier(),
379                                  D->getQualifierLoc(),
380                                  D->getTargetNameLoc(),
381                                  D->getNamespace());
382   Owner->addDecl(Inst);
383   return Inst;
384 }
385 
386 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
387                                                            bool IsTypeAlias) {
388   bool Invalid = false;
389   TypeSourceInfo *DI = D->getTypeSourceInfo();
390   if (DI->getType()->isInstantiationDependentType() ||
391       DI->getType()->isVariablyModifiedType()) {
392     DI = SemaRef.SubstType(DI, TemplateArgs,
393                            D->getLocation(), D->getDeclName());
394     if (!DI) {
395       Invalid = true;
396       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
397     }
398   } else {
399     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
400   }
401 
402   // HACK: g++ has a bug where it gets the value kind of ?: wrong.
403   // libstdc++ relies upon this bug in its implementation of common_type.
404   // If we happen to be processing that implementation, fake up the g++ ?:
405   // semantics. See LWG issue 2141 for more information on the bug.
406   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
407   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
408   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
409       DT->isReferenceType() &&
410       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
411       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
412       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
413       SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
414     // Fold it to the (non-reference) type which g++ would have produced.
415     DI = SemaRef.Context.getTrivialTypeSourceInfo(
416       DI->getType().getNonReferenceType());
417 
418   // Create the new typedef
419   TypedefNameDecl *Typedef;
420   if (IsTypeAlias)
421     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
422                                     D->getLocation(), D->getIdentifier(), DI);
423   else
424     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
425                                   D->getLocation(), D->getIdentifier(), DI);
426   if (Invalid)
427     Typedef->setInvalidDecl();
428 
429   // If the old typedef was the name for linkage purposes of an anonymous
430   // tag decl, re-establish that relationship for the new typedef.
431   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
432     TagDecl *oldTag = oldTagType->getDecl();
433     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
434       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
435       assert(!newTag->hasNameForLinkage());
436       newTag->setTypedefNameForAnonDecl(Typedef);
437     }
438   }
439 
440   if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
441     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
442                                                        TemplateArgs);
443     if (!InstPrev)
444       return nullptr;
445 
446     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
447 
448     // If the typedef types are not identical, reject them.
449     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
450 
451     Typedef->setPreviousDecl(InstPrevTypedef);
452   }
453 
454   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
455 
456   Typedef->setAccess(D->getAccess());
457 
458   return Typedef;
459 }
460 
461 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
462   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
463   if (Typedef)
464     Owner->addDecl(Typedef);
465   return Typedef;
466 }
467 
468 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
469   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
470   if (Typedef)
471     Owner->addDecl(Typedef);
472   return Typedef;
473 }
474 
475 Decl *
476 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
477   // Create a local instantiation scope for this type alias template, which
478   // will contain the instantiations of the template parameters.
479   LocalInstantiationScope Scope(SemaRef);
480 
481   TemplateParameterList *TempParams = D->getTemplateParameters();
482   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
483   if (!InstParams)
484     return nullptr;
485 
486   TypeAliasDecl *Pattern = D->getTemplatedDecl();
487 
488   TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
489   if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
490     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
491     if (!Found.empty()) {
492       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
493     }
494   }
495 
496   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
497     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
498   if (!AliasInst)
499     return nullptr;
500 
501   TypeAliasTemplateDecl *Inst
502     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
503                                     D->getDeclName(), InstParams, AliasInst);
504   AliasInst->setDescribedAliasTemplate(Inst);
505   if (PrevAliasTemplate)
506     Inst->setPreviousDecl(PrevAliasTemplate);
507 
508   Inst->setAccess(D->getAccess());
509 
510   if (!PrevAliasTemplate)
511     Inst->setInstantiatedFromMemberTemplate(D);
512 
513   Owner->addDecl(Inst);
514 
515   return Inst;
516 }
517 
518 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
519   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
520 }
521 
522 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
523                                              bool InstantiatingVarTemplate) {
524 
525   // Do substitution on the type of the declaration
526   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
527                                          TemplateArgs,
528                                          D->getTypeSpecStartLoc(),
529                                          D->getDeclName());
530   if (!DI)
531     return nullptr;
532 
533   if (DI->getType()->isFunctionType()) {
534     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
535       << D->isStaticDataMember() << DI->getType();
536     return nullptr;
537   }
538 
539   DeclContext *DC = Owner;
540   if (D->isLocalExternDecl())
541     SemaRef.adjustContextForLocalExternDecl(DC);
542 
543   // Build the instantiated declaration.
544   VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
545                                  D->getLocation(), D->getIdentifier(),
546                                  DI->getType(), DI, D->getStorageClass());
547 
548   // In ARC, infer 'retaining' for variables of retainable type.
549   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
550       SemaRef.inferObjCARCLifetime(Var))
551     Var->setInvalidDecl();
552 
553   // Substitute the nested name specifier, if any.
554   if (SubstQualifier(D, Var))
555     return nullptr;
556 
557   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
558                                      StartingScope, InstantiatingVarTemplate);
559 
560   if (D->isNRVOVariable()) {
561     QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
562     if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
563       Var->setNRVOVariable(true);
564   }
565 
566   Var->setImplicit(D->isImplicit());
567 
568   return Var;
569 }
570 
571 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
572   AccessSpecDecl* AD
573     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
574                              D->getAccessSpecifierLoc(), D->getColonLoc());
575   Owner->addHiddenDecl(AD);
576   return AD;
577 }
578 
579 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
580   bool Invalid = false;
581   TypeSourceInfo *DI = D->getTypeSourceInfo();
582   if (DI->getType()->isInstantiationDependentType() ||
583       DI->getType()->isVariablyModifiedType())  {
584     DI = SemaRef.SubstType(DI, TemplateArgs,
585                            D->getLocation(), D->getDeclName());
586     if (!DI) {
587       DI = D->getTypeSourceInfo();
588       Invalid = true;
589     } else if (DI->getType()->isFunctionType()) {
590       // C++ [temp.arg.type]p3:
591       //   If a declaration acquires a function type through a type
592       //   dependent on a template-parameter and this causes a
593       //   declaration that does not use the syntactic form of a
594       //   function declarator to have function type, the program is
595       //   ill-formed.
596       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
597         << DI->getType();
598       Invalid = true;
599     }
600   } else {
601     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
602   }
603 
604   Expr *BitWidth = D->getBitWidth();
605   if (Invalid)
606     BitWidth = nullptr;
607   else if (BitWidth) {
608     // The bit-width expression is a constant expression.
609     EnterExpressionEvaluationContext Unevaluated(SemaRef,
610                                                  Sema::ConstantEvaluated);
611 
612     ExprResult InstantiatedBitWidth
613       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
614     if (InstantiatedBitWidth.isInvalid()) {
615       Invalid = true;
616       BitWidth = nullptr;
617     } else
618       BitWidth = InstantiatedBitWidth.getAs<Expr>();
619   }
620 
621   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
622                                             DI->getType(), DI,
623                                             cast<RecordDecl>(Owner),
624                                             D->getLocation(),
625                                             D->isMutable(),
626                                             BitWidth,
627                                             D->getInClassInitStyle(),
628                                             D->getInnerLocStart(),
629                                             D->getAccess(),
630                                             nullptr);
631   if (!Field) {
632     cast<Decl>(Owner)->setInvalidDecl();
633     return nullptr;
634   }
635 
636   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
637 
638   if (Field->hasAttrs())
639     SemaRef.CheckAlignasUnderalignment(Field);
640 
641   if (Invalid)
642     Field->setInvalidDecl();
643 
644   if (!Field->getDeclName()) {
645     // Keep track of where this decl came from.
646     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
647   }
648   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
649     if (Parent->isAnonymousStructOrUnion() &&
650         Parent->getRedeclContext()->isFunctionOrMethod())
651       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
652   }
653 
654   Field->setImplicit(D->isImplicit());
655   Field->setAccess(D->getAccess());
656   Owner->addDecl(Field);
657 
658   return Field;
659 }
660 
661 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
662   bool Invalid = false;
663   TypeSourceInfo *DI = D->getTypeSourceInfo();
664 
665   if (DI->getType()->isVariablyModifiedType()) {
666     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
667       << D;
668     Invalid = true;
669   } else if (DI->getType()->isInstantiationDependentType())  {
670     DI = SemaRef.SubstType(DI, TemplateArgs,
671                            D->getLocation(), D->getDeclName());
672     if (!DI) {
673       DI = D->getTypeSourceInfo();
674       Invalid = true;
675     } else if (DI->getType()->isFunctionType()) {
676       // C++ [temp.arg.type]p3:
677       //   If a declaration acquires a function type through a type
678       //   dependent on a template-parameter and this causes a
679       //   declaration that does not use the syntactic form of a
680       //   function declarator to have function type, the program is
681       //   ill-formed.
682       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
683       << DI->getType();
684       Invalid = true;
685     }
686   } else {
687     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
688   }
689 
690   MSPropertyDecl *Property = MSPropertyDecl::Create(
691       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
692       DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
693 
694   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
695                            StartingScope);
696 
697   if (Invalid)
698     Property->setInvalidDecl();
699 
700   Property->setAccess(D->getAccess());
701   Owner->addDecl(Property);
702 
703   return Property;
704 }
705 
706 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
707   NamedDecl **NamedChain =
708     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
709 
710   int i = 0;
711   for (auto *PI : D->chain()) {
712     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
713                                               TemplateArgs);
714     if (!Next)
715       return nullptr;
716 
717     NamedChain[i++] = Next;
718   }
719 
720   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
721   IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
722       SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
723       NamedChain, D->getChainingSize());
724 
725   for (const auto *Attr : D->attrs())
726     IndirectField->addAttr(Attr->clone(SemaRef.Context));
727 
728   IndirectField->setImplicit(D->isImplicit());
729   IndirectField->setAccess(D->getAccess());
730   Owner->addDecl(IndirectField);
731   return IndirectField;
732 }
733 
734 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
735   // Handle friend type expressions by simply substituting template
736   // parameters into the pattern type and checking the result.
737   if (TypeSourceInfo *Ty = D->getFriendType()) {
738     TypeSourceInfo *InstTy;
739     // If this is an unsupported friend, don't bother substituting template
740     // arguments into it. The actual type referred to won't be used by any
741     // parts of Clang, and may not be valid for instantiating. Just use the
742     // same info for the instantiated friend.
743     if (D->isUnsupportedFriend()) {
744       InstTy = Ty;
745     } else {
746       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
747                                  D->getLocation(), DeclarationName());
748     }
749     if (!InstTy)
750       return nullptr;
751 
752     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
753                                                  D->getFriendLoc(), InstTy);
754     if (!FD)
755       return nullptr;
756 
757     FD->setAccess(AS_public);
758     FD->setUnsupportedFriend(D->isUnsupportedFriend());
759     Owner->addDecl(FD);
760     return FD;
761   }
762 
763   NamedDecl *ND = D->getFriendDecl();
764   assert(ND && "friend decl must be a decl or a type!");
765 
766   // All of the Visit implementations for the various potential friend
767   // declarations have to be carefully written to work for friend
768   // objects, with the most important detail being that the target
769   // decl should almost certainly not be placed in Owner.
770   Decl *NewND = Visit(ND);
771   if (!NewND) return nullptr;
772 
773   FriendDecl *FD =
774     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
775                        cast<NamedDecl>(NewND), D->getFriendLoc());
776   FD->setAccess(AS_public);
777   FD->setUnsupportedFriend(D->isUnsupportedFriend());
778   Owner->addDecl(FD);
779   return FD;
780 }
781 
782 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
783   Expr *AssertExpr = D->getAssertExpr();
784 
785   // The expression in a static assertion is a constant expression.
786   EnterExpressionEvaluationContext Unevaluated(SemaRef,
787                                                Sema::ConstantEvaluated);
788 
789   ExprResult InstantiatedAssertExpr
790     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
791   if (InstantiatedAssertExpr.isInvalid())
792     return nullptr;
793 
794   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
795                                               InstantiatedAssertExpr.get(),
796                                               D->getMessage(),
797                                               D->getRParenLoc(),
798                                               D->isFailed());
799 }
800 
801 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
802   EnumDecl *PrevDecl = nullptr;
803   if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
804     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
805                                                    PatternPrev,
806                                                    TemplateArgs);
807     if (!Prev) return nullptr;
808     PrevDecl = cast<EnumDecl>(Prev);
809   }
810 
811   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
812                                     D->getLocation(), D->getIdentifier(),
813                                     PrevDecl, D->isScoped(),
814                                     D->isScopedUsingClassTag(), D->isFixed());
815   if (D->isFixed()) {
816     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
817       // If we have type source information for the underlying type, it means it
818       // has been explicitly set by the user. Perform substitution on it before
819       // moving on.
820       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
821       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
822                                                 DeclarationName());
823       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
824         Enum->setIntegerType(SemaRef.Context.IntTy);
825       else
826         Enum->setIntegerTypeSourceInfo(NewTI);
827     } else {
828       assert(!D->getIntegerType()->isDependentType()
829              && "Dependent type without type source info");
830       Enum->setIntegerType(D->getIntegerType());
831     }
832   }
833 
834   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
835 
836   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
837   Enum->setAccess(D->getAccess());
838   // Forward the mangling number from the template to the instantiated decl.
839   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
840   // See if the old tag was defined along with a declarator.
841   // If it did, mark the new tag as being associated with that declarator.
842   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
843     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
844   // See if the old tag was defined along with a typedef.
845   // If it did, mark the new tag as being associated with that typedef.
846   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
847     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
848   if (SubstQualifier(D, Enum)) return nullptr;
849   Owner->addDecl(Enum);
850 
851   EnumDecl *Def = D->getDefinition();
852   if (Def && Def != D) {
853     // If this is an out-of-line definition of an enum member template, check
854     // that the underlying types match in the instantiation of both
855     // declarations.
856     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
857       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
858       QualType DefnUnderlying =
859         SemaRef.SubstType(TI->getType(), TemplateArgs,
860                           UnderlyingLoc, DeclarationName());
861       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
862                                      DefnUnderlying,
863                                      /*EnumUnderlyingIsImplicit=*/false, Enum);
864     }
865   }
866 
867   // C++11 [temp.inst]p1: The implicit instantiation of a class template
868   // specialization causes the implicit instantiation of the declarations, but
869   // not the definitions of scoped member enumerations.
870   //
871   // DR1484 clarifies that enumeration definitions inside of a template
872   // declaration aren't considered entities that can be separately instantiated
873   // from the rest of the entity they are declared inside of.
874   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
875     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
876     InstantiateEnumDefinition(Enum, Def);
877   }
878 
879   return Enum;
880 }
881 
882 void TemplateDeclInstantiator::InstantiateEnumDefinition(
883     EnumDecl *Enum, EnumDecl *Pattern) {
884   Enum->startDefinition();
885 
886   // Update the location to refer to the definition.
887   Enum->setLocation(Pattern->getLocation());
888 
889   SmallVector<Decl*, 4> Enumerators;
890 
891   EnumConstantDecl *LastEnumConst = nullptr;
892   for (auto *EC : Pattern->enumerators()) {
893     // The specified value for the enumerator.
894     ExprResult Value((Expr *)nullptr);
895     if (Expr *UninstValue = EC->getInitExpr()) {
896       // The enumerator's value expression is a constant expression.
897       EnterExpressionEvaluationContext Unevaluated(SemaRef,
898                                                    Sema::ConstantEvaluated);
899 
900       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
901     }
902 
903     // Drop the initial value and continue.
904     bool isInvalid = false;
905     if (Value.isInvalid()) {
906       Value = nullptr;
907       isInvalid = true;
908     }
909 
910     EnumConstantDecl *EnumConst
911       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
912                                   EC->getLocation(), EC->getIdentifier(),
913                                   Value.get());
914 
915     if (isInvalid) {
916       if (EnumConst)
917         EnumConst->setInvalidDecl();
918       Enum->setInvalidDecl();
919     }
920 
921     if (EnumConst) {
922       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
923 
924       EnumConst->setAccess(Enum->getAccess());
925       Enum->addDecl(EnumConst);
926       Enumerators.push_back(EnumConst);
927       LastEnumConst = EnumConst;
928 
929       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
930           !Enum->isScoped()) {
931         // If the enumeration is within a function or method, record the enum
932         // constant as a local.
933         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
934       }
935     }
936   }
937 
938   // FIXME: Fixup LBraceLoc
939   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
940                         Enum->getRBraceLoc(), Enum,
941                         Enumerators,
942                         nullptr, nullptr);
943 }
944 
945 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
946   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
947 }
948 
949 Decl *
950 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
951   llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
952 }
953 
954 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
955   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
956 
957   // Create a local instantiation scope for this class template, which
958   // will contain the instantiations of the template parameters.
959   LocalInstantiationScope Scope(SemaRef);
960   TemplateParameterList *TempParams = D->getTemplateParameters();
961   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
962   if (!InstParams)
963     return nullptr;
964 
965   CXXRecordDecl *Pattern = D->getTemplatedDecl();
966 
967   // Instantiate the qualifier.  We have to do this first in case
968   // we're a friend declaration, because if we are then we need to put
969   // the new declaration in the appropriate context.
970   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
971   if (QualifierLoc) {
972     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
973                                                        TemplateArgs);
974     if (!QualifierLoc)
975       return nullptr;
976   }
977 
978   CXXRecordDecl *PrevDecl = nullptr;
979   ClassTemplateDecl *PrevClassTemplate = nullptr;
980 
981   if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
982     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
983     if (!Found.empty()) {
984       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
985       if (PrevClassTemplate)
986         PrevDecl = PrevClassTemplate->getTemplatedDecl();
987     }
988   }
989 
990   // If this isn't a friend, then it's a member template, in which
991   // case we just want to build the instantiation in the
992   // specialization.  If it is a friend, we want to build it in
993   // the appropriate context.
994   DeclContext *DC = Owner;
995   if (isFriend) {
996     if (QualifierLoc) {
997       CXXScopeSpec SS;
998       SS.Adopt(QualifierLoc);
999       DC = SemaRef.computeDeclContext(SS);
1000       if (!DC) return nullptr;
1001     } else {
1002       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1003                                            Pattern->getDeclContext(),
1004                                            TemplateArgs);
1005     }
1006 
1007     // Look for a previous declaration of the template in the owning
1008     // context.
1009     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1010                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1011     SemaRef.LookupQualifiedName(R, DC);
1012 
1013     if (R.isSingleResult()) {
1014       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1015       if (PrevClassTemplate)
1016         PrevDecl = PrevClassTemplate->getTemplatedDecl();
1017     }
1018 
1019     if (!PrevClassTemplate && QualifierLoc) {
1020       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1021         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1022         << QualifierLoc.getSourceRange();
1023       return nullptr;
1024     }
1025 
1026     bool AdoptedPreviousTemplateParams = false;
1027     if (PrevClassTemplate) {
1028       bool Complain = true;
1029 
1030       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
1031       // template for struct std::tr1::__detail::_Map_base, where the
1032       // template parameters of the friend declaration don't match the
1033       // template parameters of the original declaration. In this one
1034       // case, we don't complain about the ill-formed friend
1035       // declaration.
1036       if (isFriend && Pattern->getIdentifier() &&
1037           Pattern->getIdentifier()->isStr("_Map_base") &&
1038           DC->isNamespace() &&
1039           cast<NamespaceDecl>(DC)->getIdentifier() &&
1040           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
1041         DeclContext *DCParent = DC->getParent();
1042         if (DCParent->isNamespace() &&
1043             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
1044             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
1045           if (cast<Decl>(DCParent)->isInStdNamespace())
1046             Complain = false;
1047         }
1048       }
1049 
1050       TemplateParameterList *PrevParams
1051         = PrevClassTemplate->getTemplateParameters();
1052 
1053       // Make sure the parameter lists match.
1054       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
1055                                                   Complain,
1056                                                   Sema::TPL_TemplateMatch)) {
1057         if (Complain)
1058           return nullptr;
1059 
1060         AdoptedPreviousTemplateParams = true;
1061         InstParams = PrevParams;
1062       }
1063 
1064       // Do some additional validation, then merge default arguments
1065       // from the existing declarations.
1066       if (!AdoptedPreviousTemplateParams &&
1067           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1068                                              Sema::TPC_ClassTemplate))
1069         return nullptr;
1070     }
1071   }
1072 
1073   CXXRecordDecl *RecordInst
1074     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
1075                             Pattern->getLocStart(), Pattern->getLocation(),
1076                             Pattern->getIdentifier(), PrevDecl,
1077                             /*DelayTypeCreation=*/true);
1078 
1079   if (QualifierLoc)
1080     RecordInst->setQualifierInfo(QualifierLoc);
1081 
1082   ClassTemplateDecl *Inst
1083     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1084                                 D->getIdentifier(), InstParams, RecordInst,
1085                                 PrevClassTemplate);
1086   RecordInst->setDescribedClassTemplate(Inst);
1087 
1088   if (isFriend) {
1089     if (PrevClassTemplate)
1090       Inst->setAccess(PrevClassTemplate->getAccess());
1091     else
1092       Inst->setAccess(D->getAccess());
1093 
1094     Inst->setObjectOfFriendDecl();
1095     // TODO: do we want to track the instantiation progeny of this
1096     // friend target decl?
1097   } else {
1098     Inst->setAccess(D->getAccess());
1099     if (!PrevClassTemplate)
1100       Inst->setInstantiatedFromMemberTemplate(D);
1101   }
1102 
1103   // Trigger creation of the type for the instantiation.
1104   SemaRef.Context.getInjectedClassNameType(RecordInst,
1105                                     Inst->getInjectedClassNameSpecialization());
1106 
1107   // Finish handling of friends.
1108   if (isFriend) {
1109     DC->makeDeclVisibleInContext(Inst);
1110     Inst->setLexicalDeclContext(Owner);
1111     RecordInst->setLexicalDeclContext(Owner);
1112     return Inst;
1113   }
1114 
1115   if (D->isOutOfLine()) {
1116     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1117     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1118   }
1119 
1120   Owner->addDecl(Inst);
1121 
1122   if (!PrevClassTemplate) {
1123     // Queue up any out-of-line partial specializations of this member
1124     // class template; the client will force their instantiation once
1125     // the enclosing class has been instantiated.
1126     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1127     D->getPartialSpecializations(PartialSpecs);
1128     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1129       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1130         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1131   }
1132 
1133   return Inst;
1134 }
1135 
1136 Decl *
1137 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1138                                    ClassTemplatePartialSpecializationDecl *D) {
1139   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1140 
1141   // Lookup the already-instantiated declaration in the instantiation
1142   // of the class template and return that.
1143   DeclContext::lookup_result Found
1144     = Owner->lookup(ClassTemplate->getDeclName());
1145   if (Found.empty())
1146     return nullptr;
1147 
1148   ClassTemplateDecl *InstClassTemplate
1149     = dyn_cast<ClassTemplateDecl>(Found.front());
1150   if (!InstClassTemplate)
1151     return nullptr;
1152 
1153   if (ClassTemplatePartialSpecializationDecl *Result
1154         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1155     return Result;
1156 
1157   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1158 }
1159 
1160 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1161   assert(D->getTemplatedDecl()->isStaticDataMember() &&
1162          "Only static data member templates are allowed.");
1163 
1164   // Create a local instantiation scope for this variable template, which
1165   // will contain the instantiations of the template parameters.
1166   LocalInstantiationScope Scope(SemaRef);
1167   TemplateParameterList *TempParams = D->getTemplateParameters();
1168   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1169   if (!InstParams)
1170     return nullptr;
1171 
1172   VarDecl *Pattern = D->getTemplatedDecl();
1173   VarTemplateDecl *PrevVarTemplate = nullptr;
1174 
1175   if (getPreviousDeclForInstantiation(Pattern)) {
1176     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1177     if (!Found.empty())
1178       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1179   }
1180 
1181   VarDecl *VarInst =
1182       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1183                                          /*InstantiatingVarTemplate=*/true));
1184   if (!VarInst) return nullptr;
1185 
1186   DeclContext *DC = Owner;
1187 
1188   VarTemplateDecl *Inst = VarTemplateDecl::Create(
1189       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1190       VarInst);
1191   VarInst->setDescribedVarTemplate(Inst);
1192   Inst->setPreviousDecl(PrevVarTemplate);
1193 
1194   Inst->setAccess(D->getAccess());
1195   if (!PrevVarTemplate)
1196     Inst->setInstantiatedFromMemberTemplate(D);
1197 
1198   if (D->isOutOfLine()) {
1199     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1200     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1201   }
1202 
1203   Owner->addDecl(Inst);
1204 
1205   if (!PrevVarTemplate) {
1206     // Queue up any out-of-line partial specializations of this member
1207     // variable template; the client will force their instantiation once
1208     // the enclosing class has been instantiated.
1209     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1210     D->getPartialSpecializations(PartialSpecs);
1211     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1212       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1213         OutOfLineVarPartialSpecs.push_back(
1214             std::make_pair(Inst, PartialSpecs[I]));
1215   }
1216 
1217   return Inst;
1218 }
1219 
1220 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1221     VarTemplatePartialSpecializationDecl *D) {
1222   assert(D->isStaticDataMember() &&
1223          "Only static data member templates are allowed.");
1224 
1225   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1226 
1227   // Lookup the already-instantiated declaration and return that.
1228   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1229   assert(!Found.empty() && "Instantiation found nothing?");
1230 
1231   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1232   assert(InstVarTemplate && "Instantiation did not find a variable template?");
1233 
1234   if (VarTemplatePartialSpecializationDecl *Result =
1235           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1236     return Result;
1237 
1238   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1239 }
1240 
1241 Decl *
1242 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1243   // Create a local instantiation scope for this function template, which
1244   // will contain the instantiations of the template parameters and then get
1245   // merged with the local instantiation scope for the function template
1246   // itself.
1247   LocalInstantiationScope Scope(SemaRef);
1248 
1249   TemplateParameterList *TempParams = D->getTemplateParameters();
1250   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1251   if (!InstParams)
1252     return nullptr;
1253 
1254   FunctionDecl *Instantiated = nullptr;
1255   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1256     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1257                                                                  InstParams));
1258   else
1259     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1260                                                           D->getTemplatedDecl(),
1261                                                                 InstParams));
1262 
1263   if (!Instantiated)
1264     return nullptr;
1265 
1266   // Link the instantiated function template declaration to the function
1267   // template from which it was instantiated.
1268   FunctionTemplateDecl *InstTemplate
1269     = Instantiated->getDescribedFunctionTemplate();
1270   InstTemplate->setAccess(D->getAccess());
1271   assert(InstTemplate &&
1272          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1273 
1274   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1275 
1276   // Link the instantiation back to the pattern *unless* this is a
1277   // non-definition friend declaration.
1278   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1279       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1280     InstTemplate->setInstantiatedFromMemberTemplate(D);
1281 
1282   // Make declarations visible in the appropriate context.
1283   if (!isFriend) {
1284     Owner->addDecl(InstTemplate);
1285   } else if (InstTemplate->getDeclContext()->isRecord() &&
1286              !getPreviousDeclForInstantiation(D)) {
1287     SemaRef.CheckFriendAccess(InstTemplate);
1288   }
1289 
1290   return InstTemplate;
1291 }
1292 
1293 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1294   CXXRecordDecl *PrevDecl = nullptr;
1295   if (D->isInjectedClassName())
1296     PrevDecl = cast<CXXRecordDecl>(Owner);
1297   else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1298     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1299                                                    PatternPrev,
1300                                                    TemplateArgs);
1301     if (!Prev) return nullptr;
1302     PrevDecl = cast<CXXRecordDecl>(Prev);
1303   }
1304 
1305   CXXRecordDecl *Record
1306     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1307                             D->getLocStart(), D->getLocation(),
1308                             D->getIdentifier(), PrevDecl);
1309 
1310   // Substitute the nested name specifier, if any.
1311   if (SubstQualifier(D, Record))
1312     return nullptr;
1313 
1314   Record->setImplicit(D->isImplicit());
1315   // FIXME: Check against AS_none is an ugly hack to work around the issue that
1316   // the tag decls introduced by friend class declarations don't have an access
1317   // specifier. Remove once this area of the code gets sorted out.
1318   if (D->getAccess() != AS_none)
1319     Record->setAccess(D->getAccess());
1320   if (!D->isInjectedClassName())
1321     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1322 
1323   // If the original function was part of a friend declaration,
1324   // inherit its namespace state.
1325   if (D->getFriendObjectKind())
1326     Record->setObjectOfFriendDecl();
1327 
1328   // Make sure that anonymous structs and unions are recorded.
1329   if (D->isAnonymousStructOrUnion())
1330     Record->setAnonymousStructOrUnion(true);
1331 
1332   if (D->isLocalClass())
1333     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1334 
1335   // Forward the mangling number from the template to the instantiated decl.
1336   SemaRef.Context.setManglingNumber(Record,
1337                                     SemaRef.Context.getManglingNumber(D));
1338 
1339   // See if the old tag was defined along with a declarator.
1340   // If it did, mark the new tag as being associated with that declarator.
1341   if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1342     SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1343 
1344   // See if the old tag was defined along with a typedef.
1345   // If it did, mark the new tag as being associated with that typedef.
1346   if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1347     SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1348 
1349   Owner->addDecl(Record);
1350 
1351   // DR1484 clarifies that the members of a local class are instantiated as part
1352   // of the instantiation of their enclosing entity.
1353   if (D->isCompleteDefinition() && D->isLocalClass()) {
1354     Sema::SavePendingLocalImplicitInstantiationsRAII
1355         SavedPendingLocalImplicitInstantiations(SemaRef);
1356 
1357     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1358                              TSK_ImplicitInstantiation,
1359                              /*Complain=*/true);
1360 
1361     SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1362                                     TSK_ImplicitInstantiation);
1363 
1364     // This class may have local implicit instantiations that need to be
1365     // performed within this scope.
1366     SemaRef.PerformPendingInstantiations(/*LocalOnly=*/true);
1367   }
1368 
1369   SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1370 
1371   return Record;
1372 }
1373 
1374 /// \brief Adjust the given function type for an instantiation of the
1375 /// given declaration, to cope with modifications to the function's type that
1376 /// aren't reflected in the type-source information.
1377 ///
1378 /// \param D The declaration we're instantiating.
1379 /// \param TInfo The already-instantiated type.
1380 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1381                                                    FunctionDecl *D,
1382                                                    TypeSourceInfo *TInfo) {
1383   const FunctionProtoType *OrigFunc
1384     = D->getType()->castAs<FunctionProtoType>();
1385   const FunctionProtoType *NewFunc
1386     = TInfo->getType()->castAs<FunctionProtoType>();
1387   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1388     return TInfo->getType();
1389 
1390   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1391   NewEPI.ExtInfo = OrigFunc->getExtInfo();
1392   return Context.getFunctionType(NewFunc->getReturnType(),
1393                                  NewFunc->getParamTypes(), NewEPI);
1394 }
1395 
1396 /// Normal class members are of more specific types and therefore
1397 /// don't make it here.  This function serves two purposes:
1398 ///   1) instantiating function templates
1399 ///   2) substituting friend declarations
1400 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1401                                        TemplateParameterList *TemplateParams) {
1402   // Check whether there is already a function template specialization for
1403   // this declaration.
1404   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1405   if (FunctionTemplate && !TemplateParams) {
1406     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1407 
1408     void *InsertPos = nullptr;
1409     FunctionDecl *SpecFunc
1410       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1411 
1412     // If we already have a function template specialization, return it.
1413     if (SpecFunc)
1414       return SpecFunc;
1415   }
1416 
1417   bool isFriend;
1418   if (FunctionTemplate)
1419     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1420   else
1421     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1422 
1423   bool MergeWithParentScope = (TemplateParams != nullptr) ||
1424     Owner->isFunctionOrMethod() ||
1425     !(isa<Decl>(Owner) &&
1426       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1427   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1428 
1429   SmallVector<ParmVarDecl *, 4> Params;
1430   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1431   if (!TInfo)
1432     return nullptr;
1433   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1434 
1435   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1436   if (QualifierLoc) {
1437     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1438                                                        TemplateArgs);
1439     if (!QualifierLoc)
1440       return nullptr;
1441   }
1442 
1443   // If we're instantiating a local function declaration, put the result
1444   // in the enclosing namespace; otherwise we need to find the instantiated
1445   // context.
1446   DeclContext *DC;
1447   if (D->isLocalExternDecl()) {
1448     DC = Owner;
1449     SemaRef.adjustContextForLocalExternDecl(DC);
1450   } else if (isFriend && QualifierLoc) {
1451     CXXScopeSpec SS;
1452     SS.Adopt(QualifierLoc);
1453     DC = SemaRef.computeDeclContext(SS);
1454     if (!DC) return nullptr;
1455   } else {
1456     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1457                                          TemplateArgs);
1458   }
1459 
1460   FunctionDecl *Function =
1461       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1462                            D->getNameInfo(), T, TInfo,
1463                            D->getCanonicalDecl()->getStorageClass(),
1464                            D->isInlineSpecified(), D->hasWrittenPrototype(),
1465                            D->isConstexpr());
1466   Function->setRangeEnd(D->getSourceRange().getEnd());
1467 
1468   if (D->isInlined())
1469     Function->setImplicitlyInline();
1470 
1471   if (QualifierLoc)
1472     Function->setQualifierInfo(QualifierLoc);
1473 
1474   if (D->isLocalExternDecl())
1475     Function->setLocalExternDecl();
1476 
1477   DeclContext *LexicalDC = Owner;
1478   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1479     assert(D->getDeclContext()->isFileContext());
1480     LexicalDC = D->getDeclContext();
1481   }
1482 
1483   Function->setLexicalDeclContext(LexicalDC);
1484 
1485   // Attach the parameters
1486   for (unsigned P = 0; P < Params.size(); ++P)
1487     if (Params[P])
1488       Params[P]->setOwningFunction(Function);
1489   Function->setParams(Params);
1490 
1491   SourceLocation InstantiateAtPOI;
1492   if (TemplateParams) {
1493     // Our resulting instantiation is actually a function template, since we
1494     // are substituting only the outer template parameters. For example, given
1495     //
1496     //   template<typename T>
1497     //   struct X {
1498     //     template<typename U> friend void f(T, U);
1499     //   };
1500     //
1501     //   X<int> x;
1502     //
1503     // We are instantiating the friend function template "f" within X<int>,
1504     // which means substituting int for T, but leaving "f" as a friend function
1505     // template.
1506     // Build the function template itself.
1507     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1508                                                     Function->getLocation(),
1509                                                     Function->getDeclName(),
1510                                                     TemplateParams, Function);
1511     Function->setDescribedFunctionTemplate(FunctionTemplate);
1512 
1513     FunctionTemplate->setLexicalDeclContext(LexicalDC);
1514 
1515     if (isFriend && D->isThisDeclarationADefinition()) {
1516       // TODO: should we remember this connection regardless of whether
1517       // the friend declaration provided a body?
1518       FunctionTemplate->setInstantiatedFromMemberTemplate(
1519                                            D->getDescribedFunctionTemplate());
1520     }
1521   } else if (FunctionTemplate) {
1522     // Record this function template specialization.
1523     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1524     Function->setFunctionTemplateSpecialization(FunctionTemplate,
1525                             TemplateArgumentList::CreateCopy(SemaRef.Context,
1526                                                              Innermost.begin(),
1527                                                              Innermost.size()),
1528                                                 /*InsertPos=*/nullptr);
1529   } else if (isFriend) {
1530     // Note, we need this connection even if the friend doesn't have a body.
1531     // Its body may exist but not have been attached yet due to deferred
1532     // parsing.
1533     // FIXME: It might be cleaner to set this when attaching the body to the
1534     // friend function declaration, however that would require finding all the
1535     // instantiations and modifying them.
1536     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1537   }
1538 
1539   if (InitFunctionInstantiation(Function, D))
1540     Function->setInvalidDecl();
1541 
1542   bool isExplicitSpecialization = false;
1543 
1544   LookupResult Previous(
1545       SemaRef, Function->getDeclName(), SourceLocation(),
1546       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1547                              : Sema::LookupOrdinaryName,
1548       Sema::ForRedeclaration);
1549 
1550   if (DependentFunctionTemplateSpecializationInfo *Info
1551         = D->getDependentSpecializationInfo()) {
1552     assert(isFriend && "non-friend has dependent specialization info?");
1553 
1554     // This needs to be set now for future sanity.
1555     Function->setObjectOfFriendDecl();
1556 
1557     // Instantiate the explicit template arguments.
1558     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1559                                           Info->getRAngleLoc());
1560     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1561                       ExplicitArgs, TemplateArgs))
1562       return nullptr;
1563 
1564     // Map the candidate templates to their instantiations.
1565     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1566       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1567                                                 Info->getTemplate(I),
1568                                                 TemplateArgs);
1569       if (!Temp) return nullptr;
1570 
1571       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1572     }
1573 
1574     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1575                                                     &ExplicitArgs,
1576                                                     Previous))
1577       Function->setInvalidDecl();
1578 
1579     isExplicitSpecialization = true;
1580 
1581   } else if (TemplateParams || !FunctionTemplate) {
1582     // Look only into the namespace where the friend would be declared to
1583     // find a previous declaration. This is the innermost enclosing namespace,
1584     // as described in ActOnFriendFunctionDecl.
1585     SemaRef.LookupQualifiedName(Previous, DC);
1586 
1587     // In C++, the previous declaration we find might be a tag type
1588     // (class or enum). In this case, the new declaration will hide the
1589     // tag type. Note that this does does not apply if we're declaring a
1590     // typedef (C++ [dcl.typedef]p4).
1591     if (Previous.isSingleTagDecl())
1592       Previous.clear();
1593   }
1594 
1595   SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1596                                    isExplicitSpecialization);
1597 
1598   NamedDecl *PrincipalDecl = (TemplateParams
1599                               ? cast<NamedDecl>(FunctionTemplate)
1600                               : Function);
1601 
1602   // If the original function was part of a friend declaration,
1603   // inherit its namespace state and add it to the owner.
1604   if (isFriend) {
1605     PrincipalDecl->setObjectOfFriendDecl();
1606     DC->makeDeclVisibleInContext(PrincipalDecl);
1607 
1608     bool QueuedInstantiation = false;
1609 
1610     // C++11 [temp.friend]p4 (DR329):
1611     //   When a function is defined in a friend function declaration in a class
1612     //   template, the function is instantiated when the function is odr-used.
1613     //   The same restrictions on multiple declarations and definitions that
1614     //   apply to non-template function declarations and definitions also apply
1615     //   to these implicit definitions.
1616     if (D->isThisDeclarationADefinition()) {
1617       // Check for a function body.
1618       const FunctionDecl *Definition = nullptr;
1619       if (Function->isDefined(Definition) &&
1620           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1621         SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1622             << Function->getDeclName();
1623         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1624       }
1625       // Check for redefinitions due to other instantiations of this or
1626       // a similar friend function.
1627       else for (auto R : Function->redecls()) {
1628         if (R == Function)
1629           continue;
1630 
1631         // If some prior declaration of this function has been used, we need
1632         // to instantiate its definition.
1633         if (!QueuedInstantiation && R->isUsed(false)) {
1634           if (MemberSpecializationInfo *MSInfo =
1635                   Function->getMemberSpecializationInfo()) {
1636             if (MSInfo->getPointOfInstantiation().isInvalid()) {
1637               SourceLocation Loc = R->getLocation(); // FIXME
1638               MSInfo->setPointOfInstantiation(Loc);
1639               SemaRef.PendingLocalImplicitInstantiations.push_back(
1640                                                std::make_pair(Function, Loc));
1641               QueuedInstantiation = true;
1642             }
1643           }
1644         }
1645 
1646         // If some prior declaration of this function was a friend with an
1647         // uninstantiated definition, reject it.
1648         if (R->getFriendObjectKind()) {
1649           if (const FunctionDecl *RPattern =
1650                   R->getTemplateInstantiationPattern()) {
1651             if (RPattern->isDefined(RPattern)) {
1652               SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1653                 << Function->getDeclName();
1654               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1655               break;
1656             }
1657           }
1658         }
1659       }
1660     }
1661   }
1662 
1663   if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1664     DC->makeDeclVisibleInContext(PrincipalDecl);
1665 
1666   if (Function->isOverloadedOperator() && !DC->isRecord() &&
1667       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1668     PrincipalDecl->setNonMemberOperator();
1669 
1670   assert(!D->isDefaulted() && "only methods should be defaulted");
1671   return Function;
1672 }
1673 
1674 Decl *
1675 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1676                                       TemplateParameterList *TemplateParams,
1677                                       bool IsClassScopeSpecialization) {
1678   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1679   if (FunctionTemplate && !TemplateParams) {
1680     // We are creating a function template specialization from a function
1681     // template. Check whether there is already a function template
1682     // specialization for this particular set of template arguments.
1683     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1684 
1685     void *InsertPos = nullptr;
1686     FunctionDecl *SpecFunc
1687       = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1688 
1689     // If we already have a function template specialization, return it.
1690     if (SpecFunc)
1691       return SpecFunc;
1692   }
1693 
1694   bool isFriend;
1695   if (FunctionTemplate)
1696     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1697   else
1698     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1699 
1700   bool MergeWithParentScope = (TemplateParams != nullptr) ||
1701     !(isa<Decl>(Owner) &&
1702       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1703   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1704 
1705   // Instantiate enclosing template arguments for friends.
1706   SmallVector<TemplateParameterList *, 4> TempParamLists;
1707   unsigned NumTempParamLists = 0;
1708   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1709     TempParamLists.resize(NumTempParamLists);
1710     for (unsigned I = 0; I != NumTempParamLists; ++I) {
1711       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1712       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1713       if (!InstParams)
1714         return nullptr;
1715       TempParamLists[I] = InstParams;
1716     }
1717   }
1718 
1719   SmallVector<ParmVarDecl *, 4> Params;
1720   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1721   if (!TInfo)
1722     return nullptr;
1723   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1724 
1725   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1726   if (QualifierLoc) {
1727     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1728                                                  TemplateArgs);
1729     if (!QualifierLoc)
1730       return nullptr;
1731   }
1732 
1733   DeclContext *DC = Owner;
1734   if (isFriend) {
1735     if (QualifierLoc) {
1736       CXXScopeSpec SS;
1737       SS.Adopt(QualifierLoc);
1738       DC = SemaRef.computeDeclContext(SS);
1739 
1740       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1741         return nullptr;
1742     } else {
1743       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1744                                            D->getDeclContext(),
1745                                            TemplateArgs);
1746     }
1747     if (!DC) return nullptr;
1748   }
1749 
1750   // Build the instantiated method declaration.
1751   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1752   CXXMethodDecl *Method = nullptr;
1753 
1754   SourceLocation StartLoc = D->getInnerLocStart();
1755   DeclarationNameInfo NameInfo
1756     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1757   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1758     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1759                                         StartLoc, NameInfo, T, TInfo,
1760                                         Constructor->isExplicit(),
1761                                         Constructor->isInlineSpecified(),
1762                                         false, Constructor->isConstexpr());
1763 
1764     // Claim that the instantiation of a constructor or constructor template
1765     // inherits the same constructor that the template does.
1766     if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1767             Constructor->getInheritedConstructor())) {
1768       // If we're instantiating a specialization of a function template, our
1769       // "inherited constructor" will actually itself be a function template.
1770       // Instantiate a declaration of it, too.
1771       if (FunctionTemplate) {
1772         assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1773                !Inh->getParent()->isDependentContext() &&
1774                "inheriting constructor template in dependent context?");
1775         Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1776                                          Inh);
1777         if (Inst.isInvalid())
1778           return nullptr;
1779         Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1780         LocalInstantiationScope LocalScope(SemaRef);
1781 
1782         // Use the same template arguments that we deduced for the inheriting
1783         // constructor. There's no way they could be deduced differently.
1784         MultiLevelTemplateArgumentList InheritedArgs;
1785         InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1786         Inh = cast_or_null<CXXConstructorDecl>(
1787             SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1788         if (!Inh)
1789           return nullptr;
1790       }
1791       cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1792     }
1793   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1794     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1795                                        StartLoc, NameInfo, T, TInfo,
1796                                        Destructor->isInlineSpecified(),
1797                                        false);
1798   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1799     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1800                                        StartLoc, NameInfo, T, TInfo,
1801                                        Conversion->isInlineSpecified(),
1802                                        Conversion->isExplicit(),
1803                                        Conversion->isConstexpr(),
1804                                        Conversion->getLocEnd());
1805   } else {
1806     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1807     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1808                                    StartLoc, NameInfo, T, TInfo,
1809                                    SC, D->isInlineSpecified(),
1810                                    D->isConstexpr(), D->getLocEnd());
1811   }
1812 
1813   if (D->isInlined())
1814     Method->setImplicitlyInline();
1815 
1816   if (QualifierLoc)
1817     Method->setQualifierInfo(QualifierLoc);
1818 
1819   if (TemplateParams) {
1820     // Our resulting instantiation is actually a function template, since we
1821     // are substituting only the outer template parameters. For example, given
1822     //
1823     //   template<typename T>
1824     //   struct X {
1825     //     template<typename U> void f(T, U);
1826     //   };
1827     //
1828     //   X<int> x;
1829     //
1830     // We are instantiating the member template "f" within X<int>, which means
1831     // substituting int for T, but leaving "f" as a member function template.
1832     // Build the function template itself.
1833     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1834                                                     Method->getLocation(),
1835                                                     Method->getDeclName(),
1836                                                     TemplateParams, Method);
1837     if (isFriend) {
1838       FunctionTemplate->setLexicalDeclContext(Owner);
1839       FunctionTemplate->setObjectOfFriendDecl();
1840     } else if (D->isOutOfLine())
1841       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1842     Method->setDescribedFunctionTemplate(FunctionTemplate);
1843   } else if (FunctionTemplate) {
1844     // Record this function template specialization.
1845     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1846     Method->setFunctionTemplateSpecialization(FunctionTemplate,
1847                          TemplateArgumentList::CreateCopy(SemaRef.Context,
1848                                                           Innermost.begin(),
1849                                                           Innermost.size()),
1850                                               /*InsertPos=*/nullptr);
1851   } else if (!isFriend) {
1852     // Record that this is an instantiation of a member function.
1853     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1854   }
1855 
1856   // If we are instantiating a member function defined
1857   // out-of-line, the instantiation will have the same lexical
1858   // context (which will be a namespace scope) as the template.
1859   if (isFriend) {
1860     if (NumTempParamLists)
1861       Method->setTemplateParameterListsInfo(
1862           SemaRef.Context,
1863           llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
1864 
1865     Method->setLexicalDeclContext(Owner);
1866     Method->setObjectOfFriendDecl();
1867   } else if (D->isOutOfLine())
1868     Method->setLexicalDeclContext(D->getLexicalDeclContext());
1869 
1870   // Attach the parameters
1871   for (unsigned P = 0; P < Params.size(); ++P)
1872     Params[P]->setOwningFunction(Method);
1873   Method->setParams(Params);
1874 
1875   if (InitMethodInstantiation(Method, D))
1876     Method->setInvalidDecl();
1877 
1878   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1879                         Sema::ForRedeclaration);
1880 
1881   if (!FunctionTemplate || TemplateParams || isFriend) {
1882     SemaRef.LookupQualifiedName(Previous, Record);
1883 
1884     // In C++, the previous declaration we find might be a tag type
1885     // (class or enum). In this case, the new declaration will hide the
1886     // tag type. Note that this does does not apply if we're declaring a
1887     // typedef (C++ [dcl.typedef]p4).
1888     if (Previous.isSingleTagDecl())
1889       Previous.clear();
1890   }
1891 
1892   if (!IsClassScopeSpecialization)
1893     SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1894 
1895   if (D->isPure())
1896     SemaRef.CheckPureMethod(Method, SourceRange());
1897 
1898   // Propagate access.  For a non-friend declaration, the access is
1899   // whatever we're propagating from.  For a friend, it should be the
1900   // previous declaration we just found.
1901   if (isFriend && Method->getPreviousDecl())
1902     Method->setAccess(Method->getPreviousDecl()->getAccess());
1903   else
1904     Method->setAccess(D->getAccess());
1905   if (FunctionTemplate)
1906     FunctionTemplate->setAccess(Method->getAccess());
1907 
1908   SemaRef.CheckOverrideControl(Method);
1909 
1910   // If a function is defined as defaulted or deleted, mark it as such now.
1911   if (D->isExplicitlyDefaulted())
1912     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1913   if (D->isDeletedAsWritten())
1914     SemaRef.SetDeclDeleted(Method, Method->getLocation());
1915 
1916   // If there's a function template, let our caller handle it.
1917   if (FunctionTemplate) {
1918     // do nothing
1919 
1920   // Don't hide a (potentially) valid declaration with an invalid one.
1921   } else if (Method->isInvalidDecl() && !Previous.empty()) {
1922     // do nothing
1923 
1924   // Otherwise, check access to friends and make them visible.
1925   } else if (isFriend) {
1926     // We only need to re-check access for methods which we didn't
1927     // manage to match during parsing.
1928     if (!D->getPreviousDecl())
1929       SemaRef.CheckFriendAccess(Method);
1930 
1931     Record->makeDeclVisibleInContext(Method);
1932 
1933   // Otherwise, add the declaration.  We don't need to do this for
1934   // class-scope specializations because we'll have matched them with
1935   // the appropriate template.
1936   } else if (!IsClassScopeSpecialization) {
1937     Owner->addDecl(Method);
1938   }
1939 
1940   return Method;
1941 }
1942 
1943 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1944   return VisitCXXMethodDecl(D);
1945 }
1946 
1947 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1948   return VisitCXXMethodDecl(D);
1949 }
1950 
1951 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1952   return VisitCXXMethodDecl(D);
1953 }
1954 
1955 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1956   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1957                                   /*ExpectParameterPack=*/ false);
1958 }
1959 
1960 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1961                                                     TemplateTypeParmDecl *D) {
1962   // TODO: don't always clone when decls are refcounted.
1963   assert(D->getTypeForDecl()->isTemplateTypeParmType());
1964 
1965   TemplateTypeParmDecl *Inst =
1966     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1967                                  D->getLocStart(), D->getLocation(),
1968                                  D->getDepth() - TemplateArgs.getNumLevels(),
1969                                  D->getIndex(), D->getIdentifier(),
1970                                  D->wasDeclaredWithTypename(),
1971                                  D->isParameterPack());
1972   Inst->setAccess(AS_public);
1973 
1974   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
1975     TypeSourceInfo *InstantiatedDefaultArg =
1976         SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1977                           D->getDefaultArgumentLoc(), D->getDeclName());
1978     if (InstantiatedDefaultArg)
1979       Inst->setDefaultArgument(InstantiatedDefaultArg);
1980   }
1981 
1982   // Introduce this template parameter's instantiation into the instantiation
1983   // scope.
1984   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1985 
1986   return Inst;
1987 }
1988 
1989 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1990                                                  NonTypeTemplateParmDecl *D) {
1991   // Substitute into the type of the non-type template parameter.
1992   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1993   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1994   SmallVector<QualType, 4> ExpandedParameterPackTypes;
1995   bool IsExpandedParameterPack = false;
1996   TypeSourceInfo *DI;
1997   QualType T;
1998   bool Invalid = false;
1999 
2000   if (D->isExpandedParameterPack()) {
2001     // The non-type template parameter pack is an already-expanded pack
2002     // expansion of types. Substitute into each of the expanded types.
2003     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2004     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2005     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2006       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
2007                                                TemplateArgs,
2008                                                D->getLocation(),
2009                                                D->getDeclName());
2010       if (!NewDI)
2011         return nullptr;
2012 
2013       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2014       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
2015                                                               D->getLocation());
2016       if (NewT.isNull())
2017         return nullptr;
2018       ExpandedParameterPackTypes.push_back(NewT);
2019     }
2020 
2021     IsExpandedParameterPack = true;
2022     DI = D->getTypeSourceInfo();
2023     T = DI->getType();
2024   } else if (D->isPackExpansion()) {
2025     // The non-type template parameter pack's type is a pack expansion of types.
2026     // Determine whether we need to expand this parameter pack into separate
2027     // types.
2028     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2029     TypeLoc Pattern = Expansion.getPatternLoc();
2030     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2031     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2032 
2033     // Determine whether the set of unexpanded parameter packs can and should
2034     // be expanded.
2035     bool Expand = true;
2036     bool RetainExpansion = false;
2037     Optional<unsigned> OrigNumExpansions
2038       = Expansion.getTypePtr()->getNumExpansions();
2039     Optional<unsigned> NumExpansions = OrigNumExpansions;
2040     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2041                                                 Pattern.getSourceRange(),
2042                                                 Unexpanded,
2043                                                 TemplateArgs,
2044                                                 Expand, RetainExpansion,
2045                                                 NumExpansions))
2046       return nullptr;
2047 
2048     if (Expand) {
2049       for (unsigned I = 0; I != *NumExpansions; ++I) {
2050         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2051         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2052                                                   D->getLocation(),
2053                                                   D->getDeclName());
2054         if (!NewDI)
2055           return nullptr;
2056 
2057         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2058         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
2059                                                               NewDI->getType(),
2060                                                               D->getLocation());
2061         if (NewT.isNull())
2062           return nullptr;
2063         ExpandedParameterPackTypes.push_back(NewT);
2064       }
2065 
2066       // Note that we have an expanded parameter pack. The "type" of this
2067       // expanded parameter pack is the original expansion type, but callers
2068       // will end up using the expanded parameter pack types for type-checking.
2069       IsExpandedParameterPack = true;
2070       DI = D->getTypeSourceInfo();
2071       T = DI->getType();
2072     } else {
2073       // We cannot fully expand the pack expansion now, so substitute into the
2074       // pattern and create a new pack expansion type.
2075       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2076       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2077                                                      D->getLocation(),
2078                                                      D->getDeclName());
2079       if (!NewPattern)
2080         return nullptr;
2081 
2082       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2083                                       NumExpansions);
2084       if (!DI)
2085         return nullptr;
2086 
2087       T = DI->getType();
2088     }
2089   } else {
2090     // Simple case: substitution into a parameter that is not a parameter pack.
2091     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2092                            D->getLocation(), D->getDeclName());
2093     if (!DI)
2094       return nullptr;
2095 
2096     // Check that this type is acceptable for a non-type template parameter.
2097     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
2098                                                   D->getLocation());
2099     if (T.isNull()) {
2100       T = SemaRef.Context.IntTy;
2101       Invalid = true;
2102     }
2103   }
2104 
2105   NonTypeTemplateParmDecl *Param;
2106   if (IsExpandedParameterPack)
2107     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2108                                             D->getInnerLocStart(),
2109                                             D->getLocation(),
2110                                     D->getDepth() - TemplateArgs.getNumLevels(),
2111                                             D->getPosition(),
2112                                             D->getIdentifier(), T,
2113                                             DI,
2114                                             ExpandedParameterPackTypes.data(),
2115                                             ExpandedParameterPackTypes.size(),
2116                                     ExpandedParameterPackTypesAsWritten.data());
2117   else
2118     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
2119                                             D->getInnerLocStart(),
2120                                             D->getLocation(),
2121                                     D->getDepth() - TemplateArgs.getNumLevels(),
2122                                             D->getPosition(),
2123                                             D->getIdentifier(), T,
2124                                             D->isParameterPack(), DI);
2125 
2126   Param->setAccess(AS_public);
2127   if (Invalid)
2128     Param->setInvalidDecl();
2129 
2130   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2131     EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
2132                                                        Sema::ConstantEvaluated);
2133     ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2134     if (!Value.isInvalid())
2135       Param->setDefaultArgument(Value.get());
2136   }
2137 
2138   // Introduce this template parameter's instantiation into the instantiation
2139   // scope.
2140   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2141   return Param;
2142 }
2143 
2144 static void collectUnexpandedParameterPacks(
2145     Sema &S,
2146     TemplateParameterList *Params,
2147     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2148   for (const auto &P : *Params) {
2149     if (P->isTemplateParameterPack())
2150       continue;
2151     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2152       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2153                                         Unexpanded);
2154     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2155       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2156                                       Unexpanded);
2157   }
2158 }
2159 
2160 Decl *
2161 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2162                                                   TemplateTemplateParmDecl *D) {
2163   // Instantiate the template parameter list of the template template parameter.
2164   TemplateParameterList *TempParams = D->getTemplateParameters();
2165   TemplateParameterList *InstParams;
2166   SmallVector<TemplateParameterList*, 8> ExpandedParams;
2167 
2168   bool IsExpandedParameterPack = false;
2169 
2170   if (D->isExpandedParameterPack()) {
2171     // The template template parameter pack is an already-expanded pack
2172     // expansion of template parameters. Substitute into each of the expanded
2173     // parameters.
2174     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2175     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2176          I != N; ++I) {
2177       LocalInstantiationScope Scope(SemaRef);
2178       TemplateParameterList *Expansion =
2179         SubstTemplateParams(D->getExpansionTemplateParameters(I));
2180       if (!Expansion)
2181         return nullptr;
2182       ExpandedParams.push_back(Expansion);
2183     }
2184 
2185     IsExpandedParameterPack = true;
2186     InstParams = TempParams;
2187   } else if (D->isPackExpansion()) {
2188     // The template template parameter pack expands to a pack of template
2189     // template parameters. Determine whether we need to expand this parameter
2190     // pack into separate parameters.
2191     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2192     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2193                                     Unexpanded);
2194 
2195     // Determine whether the set of unexpanded parameter packs can and should
2196     // be expanded.
2197     bool Expand = true;
2198     bool RetainExpansion = false;
2199     Optional<unsigned> NumExpansions;
2200     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2201                                                 TempParams->getSourceRange(),
2202                                                 Unexpanded,
2203                                                 TemplateArgs,
2204                                                 Expand, RetainExpansion,
2205                                                 NumExpansions))
2206       return nullptr;
2207 
2208     if (Expand) {
2209       for (unsigned I = 0; I != *NumExpansions; ++I) {
2210         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2211         LocalInstantiationScope Scope(SemaRef);
2212         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2213         if (!Expansion)
2214           return nullptr;
2215         ExpandedParams.push_back(Expansion);
2216       }
2217 
2218       // Note that we have an expanded parameter pack. The "type" of this
2219       // expanded parameter pack is the original expansion type, but callers
2220       // will end up using the expanded parameter pack types for type-checking.
2221       IsExpandedParameterPack = true;
2222       InstParams = TempParams;
2223     } else {
2224       // We cannot fully expand the pack expansion now, so just substitute
2225       // into the pattern.
2226       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2227 
2228       LocalInstantiationScope Scope(SemaRef);
2229       InstParams = SubstTemplateParams(TempParams);
2230       if (!InstParams)
2231         return nullptr;
2232     }
2233   } else {
2234     // Perform the actual substitution of template parameters within a new,
2235     // local instantiation scope.
2236     LocalInstantiationScope Scope(SemaRef);
2237     InstParams = SubstTemplateParams(TempParams);
2238     if (!InstParams)
2239       return nullptr;
2240   }
2241 
2242   // Build the template template parameter.
2243   TemplateTemplateParmDecl *Param;
2244   if (IsExpandedParameterPack)
2245     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2246                                              D->getLocation(),
2247                                    D->getDepth() - TemplateArgs.getNumLevels(),
2248                                              D->getPosition(),
2249                                              D->getIdentifier(), InstParams,
2250                                              ExpandedParams);
2251   else
2252     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2253                                              D->getLocation(),
2254                                    D->getDepth() - TemplateArgs.getNumLevels(),
2255                                              D->getPosition(),
2256                                              D->isParameterPack(),
2257                                              D->getIdentifier(), InstParams);
2258   if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2259     NestedNameSpecifierLoc QualifierLoc =
2260         D->getDefaultArgument().getTemplateQualifierLoc();
2261     QualifierLoc =
2262         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2263     TemplateName TName = SemaRef.SubstTemplateName(
2264         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2265         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2266     if (!TName.isNull())
2267       Param->setDefaultArgument(
2268           SemaRef.Context,
2269           TemplateArgumentLoc(TemplateArgument(TName),
2270                               D->getDefaultArgument().getTemplateQualifierLoc(),
2271                               D->getDefaultArgument().getTemplateNameLoc()));
2272   }
2273   Param->setAccess(AS_public);
2274 
2275   // Introduce this template parameter's instantiation into the instantiation
2276   // scope.
2277   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2278 
2279   return Param;
2280 }
2281 
2282 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2283   // Using directives are never dependent (and never contain any types or
2284   // expressions), so they require no explicit instantiation work.
2285 
2286   UsingDirectiveDecl *Inst
2287     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2288                                  D->getNamespaceKeyLocation(),
2289                                  D->getQualifierLoc(),
2290                                  D->getIdentLocation(),
2291                                  D->getNominatedNamespace(),
2292                                  D->getCommonAncestor());
2293 
2294   // Add the using directive to its declaration context
2295   // only if this is not a function or method.
2296   if (!Owner->isFunctionOrMethod())
2297     Owner->addDecl(Inst);
2298 
2299   return Inst;
2300 }
2301 
2302 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2303 
2304   // The nested name specifier may be dependent, for example
2305   //     template <typename T> struct t {
2306   //       struct s1 { T f1(); };
2307   //       struct s2 : s1 { using s1::f1; };
2308   //     };
2309   //     template struct t<int>;
2310   // Here, in using s1::f1, s1 refers to t<T>::s1;
2311   // we need to substitute for t<int>::s1.
2312   NestedNameSpecifierLoc QualifierLoc
2313     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2314                                           TemplateArgs);
2315   if (!QualifierLoc)
2316     return nullptr;
2317 
2318   // The name info is non-dependent, so no transformation
2319   // is required.
2320   DeclarationNameInfo NameInfo = D->getNameInfo();
2321 
2322   // We only need to do redeclaration lookups if we're in a class
2323   // scope (in fact, it's not really even possible in non-class
2324   // scopes).
2325   bool CheckRedeclaration = Owner->isRecord();
2326 
2327   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2328                     Sema::ForRedeclaration);
2329 
2330   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2331                                        D->getUsingLoc(),
2332                                        QualifierLoc,
2333                                        NameInfo,
2334                                        D->hasTypename());
2335 
2336   CXXScopeSpec SS;
2337   SS.Adopt(QualifierLoc);
2338   if (CheckRedeclaration) {
2339     Prev.setHideTags(false);
2340     SemaRef.LookupQualifiedName(Prev, Owner);
2341 
2342     // Check for invalid redeclarations.
2343     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2344                                             D->hasTypename(), SS,
2345                                             D->getLocation(), Prev))
2346       NewUD->setInvalidDecl();
2347 
2348   }
2349 
2350   if (!NewUD->isInvalidDecl() &&
2351       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2352                                       D->getLocation()))
2353     NewUD->setInvalidDecl();
2354 
2355   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2356   NewUD->setAccess(D->getAccess());
2357   Owner->addDecl(NewUD);
2358 
2359   // Don't process the shadow decls for an invalid decl.
2360   if (NewUD->isInvalidDecl())
2361     return NewUD;
2362 
2363   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2364     SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2365     return NewUD;
2366   }
2367 
2368   bool isFunctionScope = Owner->isFunctionOrMethod();
2369 
2370   // Process the shadow decls.
2371   for (auto *Shadow : D->shadows()) {
2372     NamedDecl *InstTarget =
2373         cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2374             Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2375     if (!InstTarget)
2376       return nullptr;
2377 
2378     UsingShadowDecl *PrevDecl = nullptr;
2379     if (CheckRedeclaration) {
2380       if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2381         continue;
2382     } else if (UsingShadowDecl *OldPrev =
2383                    getPreviousDeclForInstantiation(Shadow)) {
2384       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2385           Shadow->getLocation(), OldPrev, TemplateArgs));
2386     }
2387 
2388     UsingShadowDecl *InstShadow =
2389         SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2390                                      PrevDecl);
2391     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2392 
2393     if (isFunctionScope)
2394       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2395   }
2396 
2397   return NewUD;
2398 }
2399 
2400 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2401   // Ignore these;  we handle them in bulk when processing the UsingDecl.
2402   return nullptr;
2403 }
2404 
2405 Decl * TemplateDeclInstantiator
2406     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2407   NestedNameSpecifierLoc QualifierLoc
2408     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2409                                           TemplateArgs);
2410   if (!QualifierLoc)
2411     return nullptr;
2412 
2413   CXXScopeSpec SS;
2414   SS.Adopt(QualifierLoc);
2415 
2416   // Since NameInfo refers to a typename, it cannot be a C++ special name.
2417   // Hence, no transformation is required for it.
2418   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2419   NamedDecl *UD =
2420     SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2421                                   D->getUsingLoc(), SS, NameInfo, nullptr,
2422                                   /*instantiation*/ true,
2423                                   /*typename*/ true, D->getTypenameLoc());
2424   if (UD)
2425     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2426 
2427   return UD;
2428 }
2429 
2430 Decl * TemplateDeclInstantiator
2431     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2432   NestedNameSpecifierLoc QualifierLoc
2433       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2434   if (!QualifierLoc)
2435     return nullptr;
2436 
2437   CXXScopeSpec SS;
2438   SS.Adopt(QualifierLoc);
2439 
2440   DeclarationNameInfo NameInfo
2441     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2442 
2443   NamedDecl *UD =
2444     SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2445                                   D->getUsingLoc(), SS, NameInfo, nullptr,
2446                                   /*instantiation*/ true,
2447                                   /*typename*/ false, SourceLocation());
2448   if (UD)
2449     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2450 
2451   return UD;
2452 }
2453 
2454 
2455 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2456                                      ClassScopeFunctionSpecializationDecl *Decl) {
2457   CXXMethodDecl *OldFD = Decl->getSpecialization();
2458   CXXMethodDecl *NewFD =
2459     cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2460   if (!NewFD)
2461     return nullptr;
2462 
2463   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2464                         Sema::ForRedeclaration);
2465 
2466   TemplateArgumentListInfo TemplateArgs;
2467   TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2468   if (Decl->hasExplicitTemplateArgs()) {
2469     TemplateArgs = Decl->templateArgs();
2470     TemplateArgsPtr = &TemplateArgs;
2471   }
2472 
2473   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2474   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2475                                                   Previous)) {
2476     NewFD->setInvalidDecl();
2477     return NewFD;
2478   }
2479 
2480   // Associate the specialization with the pattern.
2481   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2482   assert(Specialization && "Class scope Specialization is null");
2483   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2484 
2485   return NewFD;
2486 }
2487 
2488 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2489                                      OMPThreadPrivateDecl *D) {
2490   SmallVector<Expr *, 5> Vars;
2491   for (auto *I : D->varlists()) {
2492     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2493     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2494     Vars.push_back(Var);
2495   }
2496 
2497   OMPThreadPrivateDecl *TD =
2498     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2499 
2500   TD->setAccess(AS_public);
2501   Owner->addDecl(TD);
2502 
2503   return TD;
2504 }
2505 
2506 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2507     OMPCapturedExprDecl * /*D*/) {
2508   llvm_unreachable("Should not be met in templates");
2509 }
2510 
2511 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2512   return VisitFunctionDecl(D, nullptr);
2513 }
2514 
2515 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2516   return VisitCXXMethodDecl(D, nullptr);
2517 }
2518 
2519 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2520   llvm_unreachable("There are only CXXRecordDecls in C++");
2521 }
2522 
2523 Decl *
2524 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2525     ClassTemplateSpecializationDecl *D) {
2526   // As a MS extension, we permit class-scope explicit specialization
2527   // of member class templates.
2528   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2529   assert(ClassTemplate->getDeclContext()->isRecord() &&
2530          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2531          "can only instantiate an explicit specialization "
2532          "for a member class template");
2533 
2534   // Lookup the already-instantiated declaration in the instantiation
2535   // of the class template. FIXME: Diagnose or assert if this fails?
2536   DeclContext::lookup_result Found
2537     = Owner->lookup(ClassTemplate->getDeclName());
2538   if (Found.empty())
2539     return nullptr;
2540   ClassTemplateDecl *InstClassTemplate
2541     = dyn_cast<ClassTemplateDecl>(Found.front());
2542   if (!InstClassTemplate)
2543     return nullptr;
2544 
2545   // Substitute into the template arguments of the class template explicit
2546   // specialization.
2547   TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2548                                         castAs<TemplateSpecializationTypeLoc>();
2549   TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2550                                             Loc.getRAngleLoc());
2551   SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2552   for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2553     ArgLocs.push_back(Loc.getArgLoc(I));
2554   if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2555                     InstTemplateArgs, TemplateArgs))
2556     return nullptr;
2557 
2558   // Check that the template argument list is well-formed for this
2559   // class template.
2560   SmallVector<TemplateArgument, 4> Converted;
2561   if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2562                                         D->getLocation(),
2563                                         InstTemplateArgs,
2564                                         false,
2565                                         Converted))
2566     return nullptr;
2567 
2568   // Figure out where to insert this class template explicit specialization
2569   // in the member template's set of class template explicit specializations.
2570   void *InsertPos = nullptr;
2571   ClassTemplateSpecializationDecl *PrevDecl =
2572       InstClassTemplate->findSpecialization(Converted, InsertPos);
2573 
2574   // Check whether we've already seen a conflicting instantiation of this
2575   // declaration (for instance, if there was a prior implicit instantiation).
2576   bool Ignored;
2577   if (PrevDecl &&
2578       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2579                                                      D->getSpecializationKind(),
2580                                                      PrevDecl,
2581                                                      PrevDecl->getSpecializationKind(),
2582                                                      PrevDecl->getPointOfInstantiation(),
2583                                                      Ignored))
2584     return nullptr;
2585 
2586   // If PrevDecl was a definition and D is also a definition, diagnose.
2587   // This happens in cases like:
2588   //
2589   //   template<typename T, typename U>
2590   //   struct Outer {
2591   //     template<typename X> struct Inner;
2592   //     template<> struct Inner<T> {};
2593   //     template<> struct Inner<U> {};
2594   //   };
2595   //
2596   //   Outer<int, int> outer; // error: the explicit specializations of Inner
2597   //                          // have the same signature.
2598   if (PrevDecl && PrevDecl->getDefinition() &&
2599       D->isThisDeclarationADefinition()) {
2600     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2601     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2602                  diag::note_previous_definition);
2603     return nullptr;
2604   }
2605 
2606   // Create the class template partial specialization declaration.
2607   ClassTemplateSpecializationDecl *InstD
2608     = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2609                                               D->getTagKind(),
2610                                               Owner,
2611                                               D->getLocStart(),
2612                                               D->getLocation(),
2613                                               InstClassTemplate,
2614                                               Converted.data(),
2615                                               Converted.size(),
2616                                               PrevDecl);
2617 
2618   // Add this partial specialization to the set of class template partial
2619   // specializations.
2620   if (!PrevDecl)
2621     InstClassTemplate->AddSpecialization(InstD, InsertPos);
2622 
2623   // Substitute the nested name specifier, if any.
2624   if (SubstQualifier(D, InstD))
2625     return nullptr;
2626 
2627   // Build the canonical type that describes the converted template
2628   // arguments of the class template explicit specialization.
2629   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2630       TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2631       SemaRef.Context.getRecordType(InstD));
2632 
2633   // Build the fully-sugared type for this class template
2634   // specialization as the user wrote in the specialization
2635   // itself. This means that we'll pretty-print the type retrieved
2636   // from the specialization's declaration the way that the user
2637   // actually wrote the specialization, rather than formatting the
2638   // name based on the "canonical" representation used to store the
2639   // template arguments in the specialization.
2640   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2641       TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2642       CanonType);
2643 
2644   InstD->setAccess(D->getAccess());
2645   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2646   InstD->setSpecializationKind(D->getSpecializationKind());
2647   InstD->setTypeAsWritten(WrittenTy);
2648   InstD->setExternLoc(D->getExternLoc());
2649   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2650 
2651   Owner->addDecl(InstD);
2652 
2653   // Instantiate the members of the class-scope explicit specialization eagerly.
2654   // We don't have support for lazy instantiation of an explicit specialization
2655   // yet, and MSVC eagerly instantiates in this case.
2656   if (D->isThisDeclarationADefinition() &&
2657       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2658                                TSK_ImplicitInstantiation,
2659                                /*Complain=*/true))
2660     return nullptr;
2661 
2662   return InstD;
2663 }
2664 
2665 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2666     VarTemplateSpecializationDecl *D) {
2667 
2668   TemplateArgumentListInfo VarTemplateArgsInfo;
2669   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2670   assert(VarTemplate &&
2671          "A template specialization without specialized template?");
2672 
2673   // Substitute the current template arguments.
2674   const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2675   VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2676   VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2677 
2678   if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2679                     TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2680     return nullptr;
2681 
2682   // Check that the template argument list is well-formed for this template.
2683   SmallVector<TemplateArgument, 4> Converted;
2684   if (SemaRef.CheckTemplateArgumentList(
2685           VarTemplate, VarTemplate->getLocStart(),
2686           const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2687           Converted))
2688     return nullptr;
2689 
2690   // Find the variable template specialization declaration that
2691   // corresponds to these arguments.
2692   void *InsertPos = nullptr;
2693   if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2694           Converted, InsertPos))
2695     // If we already have a variable template specialization, return it.
2696     return VarSpec;
2697 
2698   return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2699                                             VarTemplateArgsInfo, Converted);
2700 }
2701 
2702 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2703     VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2704     const TemplateArgumentListInfo &TemplateArgsInfo,
2705     ArrayRef<TemplateArgument> Converted) {
2706 
2707   // Do substitution on the type of the declaration
2708   TypeSourceInfo *DI =
2709       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2710                         D->getTypeSpecStartLoc(), D->getDeclName());
2711   if (!DI)
2712     return nullptr;
2713 
2714   if (DI->getType()->isFunctionType()) {
2715     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2716         << D->isStaticDataMember() << DI->getType();
2717     return nullptr;
2718   }
2719 
2720   // Build the instantiated declaration
2721   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2722       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2723       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2724       Converted.size());
2725   Var->setTemplateArgsInfo(TemplateArgsInfo);
2726   if (InsertPos)
2727     VarTemplate->AddSpecialization(Var, InsertPos);
2728 
2729   // Substitute the nested name specifier, if any.
2730   if (SubstQualifier(D, Var))
2731     return nullptr;
2732 
2733   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2734                                      Owner, StartingScope);
2735 
2736   return Var;
2737 }
2738 
2739 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2740   llvm_unreachable("@defs is not supported in Objective-C++");
2741 }
2742 
2743 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2744   // FIXME: We need to be able to instantiate FriendTemplateDecls.
2745   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2746                                                DiagnosticsEngine::Error,
2747                                                "cannot instantiate %0 yet");
2748   SemaRef.Diag(D->getLocation(), DiagID)
2749     << D->getDeclKindName();
2750 
2751   return nullptr;
2752 }
2753 
2754 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2755   llvm_unreachable("Unexpected decl");
2756 }
2757 
2758 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2759                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2760   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2761   if (D->isInvalidDecl())
2762     return nullptr;
2763 
2764   return Instantiator.Visit(D);
2765 }
2766 
2767 /// \brief Instantiates a nested template parameter list in the current
2768 /// instantiation context.
2769 ///
2770 /// \param L The parameter list to instantiate
2771 ///
2772 /// \returns NULL if there was an error
2773 TemplateParameterList *
2774 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2775   // Get errors for all the parameters before bailing out.
2776   bool Invalid = false;
2777 
2778   unsigned N = L->size();
2779   typedef SmallVector<NamedDecl *, 8> ParamVector;
2780   ParamVector Params;
2781   Params.reserve(N);
2782   for (auto &P : *L) {
2783     NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
2784     Params.push_back(D);
2785     Invalid = Invalid || !D || D->isInvalidDecl();
2786   }
2787 
2788   // Clean up if we had an error.
2789   if (Invalid)
2790     return nullptr;
2791 
2792   TemplateParameterList *InstL
2793     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2794                                     L->getLAngleLoc(), Params,
2795                                     L->getRAngleLoc());
2796   return InstL;
2797 }
2798 
2799 /// \brief Instantiate the declaration of a class template partial
2800 /// specialization.
2801 ///
2802 /// \param ClassTemplate the (instantiated) class template that is partially
2803 // specialized by the instantiation of \p PartialSpec.
2804 ///
2805 /// \param PartialSpec the (uninstantiated) class template partial
2806 /// specialization that we are instantiating.
2807 ///
2808 /// \returns The instantiated partial specialization, if successful; otherwise,
2809 /// NULL to indicate an error.
2810 ClassTemplatePartialSpecializationDecl *
2811 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2812                                             ClassTemplateDecl *ClassTemplate,
2813                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
2814   // Create a local instantiation scope for this class template partial
2815   // specialization, which will contain the instantiations of the template
2816   // parameters.
2817   LocalInstantiationScope Scope(SemaRef);
2818 
2819   // Substitute into the template parameters of the class template partial
2820   // specialization.
2821   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2822   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2823   if (!InstParams)
2824     return nullptr;
2825 
2826   // Substitute into the template arguments of the class template partial
2827   // specialization.
2828   const ASTTemplateArgumentListInfo *TemplArgInfo
2829     = PartialSpec->getTemplateArgsAsWritten();
2830   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2831                                             TemplArgInfo->RAngleLoc);
2832   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2833                     TemplArgInfo->NumTemplateArgs,
2834                     InstTemplateArgs, TemplateArgs))
2835     return nullptr;
2836 
2837   // Check that the template argument list is well-formed for this
2838   // class template.
2839   SmallVector<TemplateArgument, 4> Converted;
2840   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2841                                         PartialSpec->getLocation(),
2842                                         InstTemplateArgs,
2843                                         false,
2844                                         Converted))
2845     return nullptr;
2846 
2847   // Figure out where to insert this class template partial specialization
2848   // in the member template's set of class template partial specializations.
2849   void *InsertPos = nullptr;
2850   ClassTemplateSpecializationDecl *PrevDecl
2851     = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2852 
2853   // Build the canonical type that describes the converted template
2854   // arguments of the class template partial specialization.
2855   QualType CanonType
2856     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2857                                                     Converted.data(),
2858                                                     Converted.size());
2859 
2860   // Build the fully-sugared type for this class template
2861   // specialization as the user wrote in the specialization
2862   // itself. This means that we'll pretty-print the type retrieved
2863   // from the specialization's declaration the way that the user
2864   // actually wrote the specialization, rather than formatting the
2865   // name based on the "canonical" representation used to store the
2866   // template arguments in the specialization.
2867   TypeSourceInfo *WrittenTy
2868     = SemaRef.Context.getTemplateSpecializationTypeInfo(
2869                                                     TemplateName(ClassTemplate),
2870                                                     PartialSpec->getLocation(),
2871                                                     InstTemplateArgs,
2872                                                     CanonType);
2873 
2874   if (PrevDecl) {
2875     // We've already seen a partial specialization with the same template
2876     // parameters and template arguments. This can happen, for example, when
2877     // substituting the outer template arguments ends up causing two
2878     // class template partial specializations of a member class template
2879     // to have identical forms, e.g.,
2880     //
2881     //   template<typename T, typename U>
2882     //   struct Outer {
2883     //     template<typename X, typename Y> struct Inner;
2884     //     template<typename Y> struct Inner<T, Y>;
2885     //     template<typename Y> struct Inner<U, Y>;
2886     //   };
2887     //
2888     //   Outer<int, int> outer; // error: the partial specializations of Inner
2889     //                          // have the same signature.
2890     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2891       << WrittenTy->getType();
2892     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2893       << SemaRef.Context.getTypeDeclType(PrevDecl);
2894     return nullptr;
2895   }
2896 
2897 
2898   // Create the class template partial specialization declaration.
2899   ClassTemplatePartialSpecializationDecl *InstPartialSpec
2900     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2901                                                      PartialSpec->getTagKind(),
2902                                                      Owner,
2903                                                      PartialSpec->getLocStart(),
2904                                                      PartialSpec->getLocation(),
2905                                                      InstParams,
2906                                                      ClassTemplate,
2907                                                      Converted.data(),
2908                                                      Converted.size(),
2909                                                      InstTemplateArgs,
2910                                                      CanonType,
2911                                                      nullptr);
2912   // Substitute the nested name specifier, if any.
2913   if (SubstQualifier(PartialSpec, InstPartialSpec))
2914     return nullptr;
2915 
2916   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2917   InstPartialSpec->setTypeAsWritten(WrittenTy);
2918 
2919   // Add this partial specialization to the set of class template partial
2920   // specializations.
2921   ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2922                                           /*InsertPos=*/nullptr);
2923   return InstPartialSpec;
2924 }
2925 
2926 /// \brief Instantiate the declaration of a variable template partial
2927 /// specialization.
2928 ///
2929 /// \param VarTemplate the (instantiated) variable template that is partially
2930 /// specialized by the instantiation of \p PartialSpec.
2931 ///
2932 /// \param PartialSpec the (uninstantiated) variable template partial
2933 /// specialization that we are instantiating.
2934 ///
2935 /// \returns The instantiated partial specialization, if successful; otherwise,
2936 /// NULL to indicate an error.
2937 VarTemplatePartialSpecializationDecl *
2938 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2939     VarTemplateDecl *VarTemplate,
2940     VarTemplatePartialSpecializationDecl *PartialSpec) {
2941   // Create a local instantiation scope for this variable template partial
2942   // specialization, which will contain the instantiations of the template
2943   // parameters.
2944   LocalInstantiationScope Scope(SemaRef);
2945 
2946   // Substitute into the template parameters of the variable template partial
2947   // specialization.
2948   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2949   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2950   if (!InstParams)
2951     return nullptr;
2952 
2953   // Substitute into the template arguments of the variable template partial
2954   // specialization.
2955   const ASTTemplateArgumentListInfo *TemplArgInfo
2956     = PartialSpec->getTemplateArgsAsWritten();
2957   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2958                                             TemplArgInfo->RAngleLoc);
2959   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2960                     TemplArgInfo->NumTemplateArgs,
2961                     InstTemplateArgs, TemplateArgs))
2962     return nullptr;
2963 
2964   // Check that the template argument list is well-formed for this
2965   // class template.
2966   SmallVector<TemplateArgument, 4> Converted;
2967   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2968                                         InstTemplateArgs, false, Converted))
2969     return nullptr;
2970 
2971   // Figure out where to insert this variable template partial specialization
2972   // in the member template's set of variable template partial specializations.
2973   void *InsertPos = nullptr;
2974   VarTemplateSpecializationDecl *PrevDecl =
2975       VarTemplate->findPartialSpecialization(Converted, InsertPos);
2976 
2977   // Build the canonical type that describes the converted template
2978   // arguments of the variable template partial specialization.
2979   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2980       TemplateName(VarTemplate), Converted.data(), Converted.size());
2981 
2982   // Build the fully-sugared type for this variable template
2983   // specialization as the user wrote in the specialization
2984   // itself. This means that we'll pretty-print the type retrieved
2985   // from the specialization's declaration the way that the user
2986   // actually wrote the specialization, rather than formatting the
2987   // name based on the "canonical" representation used to store the
2988   // template arguments in the specialization.
2989   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2990       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2991       CanonType);
2992 
2993   if (PrevDecl) {
2994     // We've already seen a partial specialization with the same template
2995     // parameters and template arguments. This can happen, for example, when
2996     // substituting the outer template arguments ends up causing two
2997     // variable template partial specializations of a member variable template
2998     // to have identical forms, e.g.,
2999     //
3000     //   template<typename T, typename U>
3001     //   struct Outer {
3002     //     template<typename X, typename Y> pair<X,Y> p;
3003     //     template<typename Y> pair<T, Y> p;
3004     //     template<typename Y> pair<U, Y> p;
3005     //   };
3006     //
3007     //   Outer<int, int> outer; // error: the partial specializations of Inner
3008     //                          // have the same signature.
3009     SemaRef.Diag(PartialSpec->getLocation(),
3010                  diag::err_var_partial_spec_redeclared)
3011         << WrittenTy->getType();
3012     SemaRef.Diag(PrevDecl->getLocation(),
3013                  diag::note_var_prev_partial_spec_here);
3014     return nullptr;
3015   }
3016 
3017   // Do substitution on the type of the declaration
3018   TypeSourceInfo *DI = SemaRef.SubstType(
3019       PartialSpec->getTypeSourceInfo(), TemplateArgs,
3020       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3021   if (!DI)
3022     return nullptr;
3023 
3024   if (DI->getType()->isFunctionType()) {
3025     SemaRef.Diag(PartialSpec->getLocation(),
3026                  diag::err_variable_instantiates_to_function)
3027         << PartialSpec->isStaticDataMember() << DI->getType();
3028     return nullptr;
3029   }
3030 
3031   // Create the variable template partial specialization declaration.
3032   VarTemplatePartialSpecializationDecl *InstPartialSpec =
3033       VarTemplatePartialSpecializationDecl::Create(
3034           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3035           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3036           DI, PartialSpec->getStorageClass(), Converted.data(),
3037           Converted.size(), InstTemplateArgs);
3038 
3039   // Substitute the nested name specifier, if any.
3040   if (SubstQualifier(PartialSpec, InstPartialSpec))
3041     return nullptr;
3042 
3043   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3044   InstPartialSpec->setTypeAsWritten(WrittenTy);
3045 
3046   // Add this partial specialization to the set of variable template partial
3047   // specializations. The instantiation of the initializer is not necessary.
3048   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3049 
3050   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3051                                      LateAttrs, Owner, StartingScope);
3052 
3053   return InstPartialSpec;
3054 }
3055 
3056 TypeSourceInfo*
3057 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3058                               SmallVectorImpl<ParmVarDecl *> &Params) {
3059   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3060   assert(OldTInfo && "substituting function without type source info");
3061   assert(Params.empty() && "parameter vector is non-empty at start");
3062 
3063   CXXRecordDecl *ThisContext = nullptr;
3064   unsigned ThisTypeQuals = 0;
3065   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3066     ThisContext = cast<CXXRecordDecl>(Owner);
3067     ThisTypeQuals = Method->getTypeQualifiers();
3068   }
3069 
3070   TypeSourceInfo *NewTInfo
3071     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3072                                     D->getTypeSpecStartLoc(),
3073                                     D->getDeclName(),
3074                                     ThisContext, ThisTypeQuals);
3075   if (!NewTInfo)
3076     return nullptr;
3077 
3078   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3079   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3080     if (NewTInfo != OldTInfo) {
3081       // Get parameters from the new type info.
3082       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3083       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3084       unsigned NewIdx = 0;
3085       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3086            OldIdx != NumOldParams; ++OldIdx) {
3087         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3088         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3089 
3090         Optional<unsigned> NumArgumentsInExpansion;
3091         if (OldParam->isParameterPack())
3092           NumArgumentsInExpansion =
3093               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3094                                                  TemplateArgs);
3095         if (!NumArgumentsInExpansion) {
3096           // Simple case: normal parameter, or a parameter pack that's
3097           // instantiated to a (still-dependent) parameter pack.
3098           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3099           Params.push_back(NewParam);
3100           Scope->InstantiatedLocal(OldParam, NewParam);
3101         } else {
3102           // Parameter pack expansion: make the instantiation an argument pack.
3103           Scope->MakeInstantiatedLocalArgPack(OldParam);
3104           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3105             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3106             Params.push_back(NewParam);
3107             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3108           }
3109         }
3110       }
3111     } else {
3112       // The function type itself was not dependent and therefore no
3113       // substitution occurred. However, we still need to instantiate
3114       // the function parameters themselves.
3115       const FunctionProtoType *OldProto =
3116           cast<FunctionProtoType>(OldProtoLoc.getType());
3117       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3118            ++i) {
3119         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3120         if (!OldParam) {
3121           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3122               D, D->getLocation(), OldProto->getParamType(i)));
3123           continue;
3124         }
3125 
3126         ParmVarDecl *Parm =
3127             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3128         if (!Parm)
3129           return nullptr;
3130         Params.push_back(Parm);
3131       }
3132     }
3133   } else {
3134     // If the type of this function, after ignoring parentheses, is not
3135     // *directly* a function type, then we're instantiating a function that
3136     // was declared via a typedef or with attributes, e.g.,
3137     //
3138     //   typedef int functype(int, int);
3139     //   functype func;
3140     //   int __cdecl meth(int, int);
3141     //
3142     // In this case, we'll just go instantiate the ParmVarDecls that we
3143     // synthesized in the method declaration.
3144     SmallVector<QualType, 4> ParamTypes;
3145     Sema::ExtParameterInfoBuilder ExtParamInfos;
3146     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
3147                                D->getNumParams(), nullptr, TemplateArgs,
3148                                ParamTypes, &Params, ExtParamInfos))
3149       return nullptr;
3150   }
3151 
3152   return NewTInfo;
3153 }
3154 
3155 /// Introduce the instantiated function parameters into the local
3156 /// instantiation scope, and set the parameter names to those used
3157 /// in the template.
3158 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3159                                              const FunctionDecl *PatternDecl,
3160                                              LocalInstantiationScope &Scope,
3161                            const MultiLevelTemplateArgumentList &TemplateArgs) {
3162   unsigned FParamIdx = 0;
3163   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3164     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3165     if (!PatternParam->isParameterPack()) {
3166       // Simple case: not a parameter pack.
3167       assert(FParamIdx < Function->getNumParams());
3168       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3169       FunctionParam->setDeclName(PatternParam->getDeclName());
3170       // If the parameter's type is not dependent, update it to match the type
3171       // in the pattern. They can differ in top-level cv-qualifiers, and we want
3172       // the pattern's type here. If the type is dependent, they can't differ,
3173       // per core issue 1668. Substitute into the type from the pattern, in case
3174       // it's instantiation-dependent.
3175       // FIXME: Updating the type to work around this is at best fragile.
3176       if (!PatternDecl->getType()->isDependentType()) {
3177         QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3178                                  FunctionParam->getLocation(),
3179                                  FunctionParam->getDeclName());
3180         if (T.isNull())
3181           return true;
3182         FunctionParam->setType(T);
3183       }
3184 
3185       Scope.InstantiatedLocal(PatternParam, FunctionParam);
3186       ++FParamIdx;
3187       continue;
3188     }
3189 
3190     // Expand the parameter pack.
3191     Scope.MakeInstantiatedLocalArgPack(PatternParam);
3192     Optional<unsigned> NumArgumentsInExpansion
3193       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3194     assert(NumArgumentsInExpansion &&
3195            "should only be called when all template arguments are known");
3196     QualType PatternType =
3197         PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3198     for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3199       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3200       FunctionParam->setDeclName(PatternParam->getDeclName());
3201       if (!PatternDecl->getType()->isDependentType()) {
3202         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3203         QualType T = S.SubstType(PatternType, TemplateArgs,
3204                                  FunctionParam->getLocation(),
3205                                  FunctionParam->getDeclName());
3206         if (T.isNull())
3207           return true;
3208         FunctionParam->setType(T);
3209       }
3210 
3211       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3212       ++FParamIdx;
3213     }
3214   }
3215 
3216   return false;
3217 }
3218 
3219 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3220                                     FunctionDecl *Decl) {
3221   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3222   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3223     return;
3224 
3225   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3226                              InstantiatingTemplate::ExceptionSpecification());
3227   if (Inst.isInvalid()) {
3228     // We hit the instantiation depth limit. Clear the exception specification
3229     // so that our callers don't have to cope with EST_Uninstantiated.
3230     UpdateExceptionSpec(Decl, EST_None);
3231     return;
3232   }
3233 
3234   // Enter the scope of this instantiation. We don't use
3235   // PushDeclContext because we don't have a scope.
3236   Sema::ContextRAII savedContext(*this, Decl);
3237   LocalInstantiationScope Scope(*this);
3238 
3239   MultiLevelTemplateArgumentList TemplateArgs =
3240     getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3241 
3242   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3243   if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3244                                        TemplateArgs)) {
3245     UpdateExceptionSpec(Decl, EST_None);
3246     return;
3247   }
3248 
3249   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3250                      TemplateArgs);
3251 }
3252 
3253 /// \brief Initializes the common fields of an instantiation function
3254 /// declaration (New) from the corresponding fields of its template (Tmpl).
3255 ///
3256 /// \returns true if there was an error
3257 bool
3258 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3259                                                     FunctionDecl *Tmpl) {
3260   if (Tmpl->isDeleted())
3261     New->setDeletedAsWritten();
3262 
3263   // Forward the mangling number from the template to the instantiated decl.
3264   SemaRef.Context.setManglingNumber(New,
3265                                     SemaRef.Context.getManglingNumber(Tmpl));
3266 
3267   // If we are performing substituting explicitly-specified template arguments
3268   // or deduced template arguments into a function template and we reach this
3269   // point, we are now past the point where SFINAE applies and have committed
3270   // to keeping the new function template specialization. We therefore
3271   // convert the active template instantiation for the function template
3272   // into a template instantiation for this specific function template
3273   // specialization, which is not a SFINAE context, so that we diagnose any
3274   // further errors in the declaration itself.
3275   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3276   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3277   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3278       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3279     if (FunctionTemplateDecl *FunTmpl
3280           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3281       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3282              "Deduction from the wrong function template?");
3283       (void) FunTmpl;
3284       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3285       ActiveInst.Entity = New;
3286     }
3287   }
3288 
3289   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3290   assert(Proto && "Function template without prototype?");
3291 
3292   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3293     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3294 
3295     // DR1330: In C++11, defer instantiation of a non-trivial
3296     // exception specification.
3297     // DR1484: Local classes and their members are instantiated along with the
3298     // containing function.
3299     if (SemaRef.getLangOpts().CPlusPlus11 &&
3300         EPI.ExceptionSpec.Type != EST_None &&
3301         EPI.ExceptionSpec.Type != EST_DynamicNone &&
3302         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3303         !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3304       FunctionDecl *ExceptionSpecTemplate = Tmpl;
3305       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3306         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3307       ExceptionSpecificationType NewEST = EST_Uninstantiated;
3308       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3309         NewEST = EST_Unevaluated;
3310 
3311       // Mark the function has having an uninstantiated exception specification.
3312       const FunctionProtoType *NewProto
3313         = New->getType()->getAs<FunctionProtoType>();
3314       assert(NewProto && "Template instantiation without function prototype?");
3315       EPI = NewProto->getExtProtoInfo();
3316       EPI.ExceptionSpec.Type = NewEST;
3317       EPI.ExceptionSpec.SourceDecl = New;
3318       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3319       New->setType(SemaRef.Context.getFunctionType(
3320           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3321     } else {
3322       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3323     }
3324   }
3325 
3326   // Get the definition. Leaves the variable unchanged if undefined.
3327   const FunctionDecl *Definition = Tmpl;
3328   Tmpl->isDefined(Definition);
3329 
3330   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3331                            LateAttrs, StartingScope);
3332 
3333   return false;
3334 }
3335 
3336 /// \brief Initializes common fields of an instantiated method
3337 /// declaration (New) from the corresponding fields of its template
3338 /// (Tmpl).
3339 ///
3340 /// \returns true if there was an error
3341 bool
3342 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3343                                                   CXXMethodDecl *Tmpl) {
3344   if (InitFunctionInstantiation(New, Tmpl))
3345     return true;
3346 
3347   New->setAccess(Tmpl->getAccess());
3348   if (Tmpl->isVirtualAsWritten())
3349     New->setVirtualAsWritten(true);
3350 
3351   // FIXME: New needs a pointer to Tmpl
3352   return false;
3353 }
3354 
3355 /// \brief Instantiate the definition of the given function from its
3356 /// template.
3357 ///
3358 /// \param PointOfInstantiation the point at which the instantiation was
3359 /// required. Note that this is not precisely a "point of instantiation"
3360 /// for the function, but it's close.
3361 ///
3362 /// \param Function the already-instantiated declaration of a
3363 /// function template specialization or member function of a class template
3364 /// specialization.
3365 ///
3366 /// \param Recursive if true, recursively instantiates any functions that
3367 /// are required by this instantiation.
3368 ///
3369 /// \param DefinitionRequired if true, then we are performing an explicit
3370 /// instantiation where the body of the function is required. Complain if
3371 /// there is no such body.
3372 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3373                                          FunctionDecl *Function,
3374                                          bool Recursive,
3375                                          bool DefinitionRequired) {
3376   if (Function->isInvalidDecl() || Function->isDefined())
3377     return;
3378 
3379   // Never instantiate an explicit specialization except if it is a class scope
3380   // explicit specialization.
3381   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3382       !Function->getClassScopeSpecializationPattern())
3383     return;
3384 
3385   // Find the function body that we'll be substituting.
3386   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3387   assert(PatternDecl && "instantiating a non-template");
3388 
3389   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3390   assert(PatternDecl && "template definition is not a template");
3391   if (!Pattern) {
3392     // Try to find a defaulted definition
3393     PatternDecl->isDefined(PatternDecl);
3394   }
3395   assert(PatternDecl && "template definition is not a template");
3396 
3397   // Postpone late parsed template instantiations.
3398   if (PatternDecl->isLateTemplateParsed() &&
3399       !LateTemplateParser) {
3400     PendingInstantiations.push_back(
3401       std::make_pair(Function, PointOfInstantiation));
3402     return;
3403   }
3404 
3405   // If we're performing recursive template instantiation, create our own
3406   // queue of pending implicit instantiations that we will instantiate later,
3407   // while we're still within our own instantiation context.
3408   // This has to happen before LateTemplateParser below is called, so that
3409   // it marks vtables used in late parsed templates as used.
3410   SavePendingLocalImplicitInstantiationsRAII
3411       SavedPendingLocalImplicitInstantiations(*this);
3412   SavePendingInstantiationsAndVTableUsesRAII
3413       SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3414 
3415   // Call the LateTemplateParser callback if there is a need to late parse
3416   // a templated function definition.
3417   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3418       LateTemplateParser) {
3419     // FIXME: Optimize to allow individual templates to be deserialized.
3420     if (PatternDecl->isFromASTFile())
3421       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3422 
3423     LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3424     assert(LPT && "missing LateParsedTemplate");
3425     LateTemplateParser(OpaqueParser, *LPT);
3426     Pattern = PatternDecl->getBody(PatternDecl);
3427   }
3428 
3429   if (!Pattern && !PatternDecl->isDefaulted()) {
3430     if (DefinitionRequired) {
3431       if (Function->getPrimaryTemplate())
3432         Diag(PointOfInstantiation,
3433              diag::err_explicit_instantiation_undefined_func_template)
3434           << Function->getPrimaryTemplate();
3435       else
3436         Diag(PointOfInstantiation,
3437              diag::err_explicit_instantiation_undefined_member)
3438           << 1 << Function->getDeclName() << Function->getDeclContext();
3439 
3440       if (PatternDecl)
3441         Diag(PatternDecl->getLocation(),
3442              diag::note_explicit_instantiation_here);
3443       Function->setInvalidDecl();
3444     } else if (Function->getTemplateSpecializationKind()
3445                  == TSK_ExplicitInstantiationDefinition) {
3446       assert(!Recursive);
3447       PendingInstantiations.push_back(
3448         std::make_pair(Function, PointOfInstantiation));
3449     }
3450 
3451     return;
3452   }
3453 
3454   // C++1y [temp.explicit]p10:
3455   //   Except for inline functions, declarations with types deduced from their
3456   //   initializer or return value, and class template specializations, other
3457   //   explicit instantiation declarations have the effect of suppressing the
3458   //   implicit instantiation of the entity to which they refer.
3459   if (Function->getTemplateSpecializationKind() ==
3460           TSK_ExplicitInstantiationDeclaration &&
3461       !PatternDecl->isInlined() &&
3462       !PatternDecl->getReturnType()->getContainedAutoType())
3463     return;
3464 
3465   if (PatternDecl->isInlined()) {
3466     // Function, and all later redeclarations of it (from imported modules,
3467     // for instance), are now implicitly inline.
3468     for (auto *D = Function->getMostRecentDecl(); /**/;
3469          D = D->getPreviousDecl()) {
3470       D->setImplicitlyInline();
3471       if (D == Function)
3472         break;
3473     }
3474   }
3475 
3476   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3477   if (Inst.isInvalid())
3478     return;
3479 
3480   // Copy the inner loc start from the pattern.
3481   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3482 
3483   EnterExpressionEvaluationContext EvalContext(*this,
3484                                                Sema::PotentiallyEvaluated);
3485 
3486   // Introduce a new scope where local variable instantiations will be
3487   // recorded, unless we're actually a member function within a local
3488   // class, in which case we need to merge our results with the parent
3489   // scope (of the enclosing function).
3490   bool MergeWithParentScope = false;
3491   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3492     MergeWithParentScope = Rec->isLocalClass();
3493 
3494   LocalInstantiationScope Scope(*this, MergeWithParentScope);
3495 
3496   if (PatternDecl->isDefaulted())
3497     SetDeclDefaulted(Function, PatternDecl->getLocation());
3498   else {
3499     MultiLevelTemplateArgumentList TemplateArgs =
3500       getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3501 
3502     // Substitute into the qualifier; we can get a substitution failure here
3503     // through evil use of alias templates.
3504     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3505     // of the) lexical context of the pattern?
3506     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3507 
3508     ActOnStartOfFunctionDef(nullptr, Function);
3509 
3510     // Enter the scope of this instantiation. We don't use
3511     // PushDeclContext because we don't have a scope.
3512     Sema::ContextRAII savedContext(*this, Function);
3513 
3514     if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3515                                          TemplateArgs))
3516       return;
3517 
3518     // If this is a constructor, instantiate the member initializers.
3519     if (const CXXConstructorDecl *Ctor =
3520           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3521       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3522                                  TemplateArgs);
3523     }
3524 
3525     // Instantiate the function body.
3526     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3527 
3528     if (Body.isInvalid())
3529       Function->setInvalidDecl();
3530 
3531     ActOnFinishFunctionBody(Function, Body.get(),
3532                             /*IsInstantiation=*/true);
3533 
3534     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3535 
3536     if (auto *Listener = getASTMutationListener())
3537       Listener->FunctionDefinitionInstantiated(Function);
3538 
3539     savedContext.pop();
3540   }
3541 
3542   DeclGroupRef DG(Function);
3543   Consumer.HandleTopLevelDecl(DG);
3544 
3545   // This class may have local implicit instantiations that need to be
3546   // instantiation within this scope.
3547   PerformPendingInstantiations(/*LocalOnly=*/true);
3548   Scope.Exit();
3549 
3550   if (Recursive) {
3551     // Define any pending vtables.
3552     DefineUsedVTables();
3553 
3554     // Instantiate any pending implicit instantiations found during the
3555     // instantiation of this template.
3556     PerformPendingInstantiations();
3557 
3558     // PendingInstantiations and VTableUses are restored through
3559     // SavePendingInstantiationsAndVTableUses's destructor.
3560   }
3561 }
3562 
3563 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3564     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3565     const TemplateArgumentList &TemplateArgList,
3566     const TemplateArgumentListInfo &TemplateArgsInfo,
3567     SmallVectorImpl<TemplateArgument> &Converted,
3568     SourceLocation PointOfInstantiation, void *InsertPos,
3569     LateInstantiatedAttrVec *LateAttrs,
3570     LocalInstantiationScope *StartingScope) {
3571   if (FromVar->isInvalidDecl())
3572     return nullptr;
3573 
3574   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3575   if (Inst.isInvalid())
3576     return nullptr;
3577 
3578   MultiLevelTemplateArgumentList TemplateArgLists;
3579   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3580 
3581   // Instantiate the first declaration of the variable template: for a partial
3582   // specialization of a static data member template, the first declaration may
3583   // or may not be the declaration in the class; if it's in the class, we want
3584   // to instantiate a member in the class (a declaration), and if it's outside,
3585   // we want to instantiate a definition.
3586   //
3587   // If we're instantiating an explicitly-specialized member template or member
3588   // partial specialization, don't do this. The member specialization completely
3589   // replaces the original declaration in this case.
3590   bool IsMemberSpec = false;
3591   if (VarTemplatePartialSpecializationDecl *PartialSpec =
3592           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3593     IsMemberSpec = PartialSpec->isMemberSpecialization();
3594   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3595     IsMemberSpec = FromTemplate->isMemberSpecialization();
3596   if (!IsMemberSpec)
3597     FromVar = FromVar->getFirstDecl();
3598 
3599   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3600   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3601                                         MultiLevelList);
3602 
3603   // TODO: Set LateAttrs and StartingScope ...
3604 
3605   return cast_or_null<VarTemplateSpecializationDecl>(
3606       Instantiator.VisitVarTemplateSpecializationDecl(
3607           VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3608 }
3609 
3610 /// \brief Instantiates a variable template specialization by completing it
3611 /// with appropriate type information and initializer.
3612 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3613     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3614     const MultiLevelTemplateArgumentList &TemplateArgs) {
3615 
3616   // Do substitution on the type of the declaration
3617   TypeSourceInfo *DI =
3618       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3619                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3620   if (!DI)
3621     return nullptr;
3622 
3623   // Update the type of this variable template specialization.
3624   VarSpec->setType(DI->getType());
3625 
3626   // Instantiate the initializer.
3627   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3628 
3629   return VarSpec;
3630 }
3631 
3632 /// BuildVariableInstantiation - Used after a new variable has been created.
3633 /// Sets basic variable data and decides whether to postpone the
3634 /// variable instantiation.
3635 void Sema::BuildVariableInstantiation(
3636     VarDecl *NewVar, VarDecl *OldVar,
3637     const MultiLevelTemplateArgumentList &TemplateArgs,
3638     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3639     LocalInstantiationScope *StartingScope,
3640     bool InstantiatingVarTemplate) {
3641 
3642   // If we are instantiating a local extern declaration, the
3643   // instantiation belongs lexically to the containing function.
3644   // If we are instantiating a static data member defined
3645   // out-of-line, the instantiation will have the same lexical
3646   // context (which will be a namespace scope) as the template.
3647   if (OldVar->isLocalExternDecl()) {
3648     NewVar->setLocalExternDecl();
3649     NewVar->setLexicalDeclContext(Owner);
3650   } else if (OldVar->isOutOfLine())
3651     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3652   NewVar->setTSCSpec(OldVar->getTSCSpec());
3653   NewVar->setInitStyle(OldVar->getInitStyle());
3654   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3655   NewVar->setConstexpr(OldVar->isConstexpr());
3656   NewVar->setInitCapture(OldVar->isInitCapture());
3657   NewVar->setPreviousDeclInSameBlockScope(
3658       OldVar->isPreviousDeclInSameBlockScope());
3659   NewVar->setAccess(OldVar->getAccess());
3660 
3661   if (!OldVar->isStaticDataMember()) {
3662     if (OldVar->isUsed(false))
3663       NewVar->setIsUsed();
3664     NewVar->setReferenced(OldVar->isReferenced());
3665   }
3666 
3667   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3668 
3669   LookupResult Previous(
3670       *this, NewVar->getDeclName(), NewVar->getLocation(),
3671       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3672                                   : Sema::LookupOrdinaryName,
3673       Sema::ForRedeclaration);
3674 
3675   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3676       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3677        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3678     // We have a previous declaration. Use that one, so we merge with the
3679     // right type.
3680     if (NamedDecl *NewPrev = FindInstantiatedDecl(
3681             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3682       Previous.addDecl(NewPrev);
3683   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3684              OldVar->hasLinkage())
3685     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3686   CheckVariableDeclaration(NewVar, Previous);
3687 
3688   if (!InstantiatingVarTemplate) {
3689     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3690     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3691       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3692   }
3693 
3694   if (!OldVar->isOutOfLine()) {
3695     if (NewVar->getDeclContext()->isFunctionOrMethod())
3696       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3697   }
3698 
3699   // Link instantiations of static data members back to the template from
3700   // which they were instantiated.
3701   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3702     NewVar->setInstantiationOfStaticDataMember(OldVar,
3703                                                TSK_ImplicitInstantiation);
3704 
3705   // Forward the mangling number from the template to the instantiated decl.
3706   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3707   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3708 
3709   // Delay instantiation of the initializer for variable templates until a
3710   // definition of the variable is needed. We need it right away if the type
3711   // contains 'auto'.
3712   if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3713        !InstantiatingVarTemplate) ||
3714       NewVar->getType()->isUndeducedType())
3715     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3716 
3717   // Diagnose unused local variables with dependent types, where the diagnostic
3718   // will have been deferred.
3719   if (!NewVar->isInvalidDecl() &&
3720       NewVar->getDeclContext()->isFunctionOrMethod() &&
3721       OldVar->getType()->isDependentType())
3722     DiagnoseUnusedDecl(NewVar);
3723 }
3724 
3725 /// \brief Instantiate the initializer of a variable.
3726 void Sema::InstantiateVariableInitializer(
3727     VarDecl *Var, VarDecl *OldVar,
3728     const MultiLevelTemplateArgumentList &TemplateArgs) {
3729 
3730   if (Var->getAnyInitializer())
3731     // We already have an initializer in the class.
3732     return;
3733 
3734   if (OldVar->getInit()) {
3735     if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3736       PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3737     else
3738       PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3739 
3740     // Instantiate the initializer.
3741     ExprResult Init =
3742         SubstInitializer(OldVar->getInit(), TemplateArgs,
3743                          OldVar->getInitStyle() == VarDecl::CallInit);
3744     if (!Init.isInvalid()) {
3745       bool TypeMayContainAuto = true;
3746       Expr *InitExpr = Init.get();
3747 
3748       if (Var->hasAttr<DLLImportAttr>() &&
3749           (!InitExpr ||
3750            !InitExpr->isConstantInitializer(getASTContext(), false))) {
3751         // Do not dynamically initialize dllimport variables.
3752       } else if (InitExpr) {
3753         bool DirectInit = OldVar->isDirectInit();
3754         AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3755       } else
3756         ActOnUninitializedDecl(Var, TypeMayContainAuto);
3757     } else {
3758       // FIXME: Not too happy about invalidating the declaration
3759       // because of a bogus initializer.
3760       Var->setInvalidDecl();
3761     }
3762 
3763     PopExpressionEvaluationContext();
3764   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3765              !Var->isCXXForRangeDecl())
3766     ActOnUninitializedDecl(Var, false);
3767 }
3768 
3769 /// \brief Instantiate the definition of the given variable from its
3770 /// template.
3771 ///
3772 /// \param PointOfInstantiation the point at which the instantiation was
3773 /// required. Note that this is not precisely a "point of instantiation"
3774 /// for the function, but it's close.
3775 ///
3776 /// \param Var the already-instantiated declaration of a static member
3777 /// variable of a class template specialization.
3778 ///
3779 /// \param Recursive if true, recursively instantiates any functions that
3780 /// are required by this instantiation.
3781 ///
3782 /// \param DefinitionRequired if true, then we are performing an explicit
3783 /// instantiation where an out-of-line definition of the member variable
3784 /// is required. Complain if there is no such definition.
3785 void Sema::InstantiateStaticDataMemberDefinition(
3786                                           SourceLocation PointOfInstantiation,
3787                                                  VarDecl *Var,
3788                                                  bool Recursive,
3789                                                  bool DefinitionRequired) {
3790   InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3791                                 DefinitionRequired);
3792 }
3793 
3794 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3795                                          VarDecl *Var, bool Recursive,
3796                                          bool DefinitionRequired) {
3797   if (Var->isInvalidDecl())
3798     return;
3799 
3800   VarTemplateSpecializationDecl *VarSpec =
3801       dyn_cast<VarTemplateSpecializationDecl>(Var);
3802   VarDecl *PatternDecl = nullptr, *Def = nullptr;
3803   MultiLevelTemplateArgumentList TemplateArgs =
3804       getTemplateInstantiationArgs(Var);
3805 
3806   if (VarSpec) {
3807     // If this is a variable template specialization, make sure that it is
3808     // non-dependent, then find its instantiation pattern.
3809     bool InstantiationDependent = false;
3810     assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3811                VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3812            "Only instantiate variable template specializations that are "
3813            "not type-dependent");
3814     (void)InstantiationDependent;
3815 
3816     // Find the variable initialization that we'll be substituting. If the
3817     // pattern was instantiated from a member template, look back further to
3818     // find the real pattern.
3819     assert(VarSpec->getSpecializedTemplate() &&
3820            "Specialization without specialized template?");
3821     llvm::PointerUnion<VarTemplateDecl *,
3822                        VarTemplatePartialSpecializationDecl *> PatternPtr =
3823         VarSpec->getSpecializedTemplateOrPartial();
3824     if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3825       VarTemplatePartialSpecializationDecl *Tmpl =
3826           PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3827       while (VarTemplatePartialSpecializationDecl *From =
3828                  Tmpl->getInstantiatedFromMember()) {
3829         if (Tmpl->isMemberSpecialization())
3830           break;
3831 
3832         Tmpl = From;
3833       }
3834       PatternDecl = Tmpl;
3835     } else {
3836       VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3837       while (VarTemplateDecl *From =
3838                  Tmpl->getInstantiatedFromMemberTemplate()) {
3839         if (Tmpl->isMemberSpecialization())
3840           break;
3841 
3842         Tmpl = From;
3843       }
3844       PatternDecl = Tmpl->getTemplatedDecl();
3845     }
3846 
3847     // If this is a static data member template, there might be an
3848     // uninstantiated initializer on the declaration. If so, instantiate
3849     // it now.
3850     if (PatternDecl->isStaticDataMember() &&
3851         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3852         !Var->hasInit()) {
3853       // FIXME: Factor out the duplicated instantiation context setup/tear down
3854       // code here.
3855       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3856       if (Inst.isInvalid())
3857         return;
3858 
3859       // If we're performing recursive template instantiation, create our own
3860       // queue of pending implicit instantiations that we will instantiate
3861       // later, while we're still within our own instantiation context.
3862       SavePendingInstantiationsAndVTableUsesRAII
3863           SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3864 
3865       LocalInstantiationScope Local(*this);
3866 
3867       // Enter the scope of this instantiation. We don't use
3868       // PushDeclContext because we don't have a scope.
3869       ContextRAII PreviousContext(*this, Var->getDeclContext());
3870       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3871       PreviousContext.pop();
3872 
3873       // FIXME: Need to inform the ASTConsumer that we instantiated the
3874       // initializer?
3875 
3876       // This variable may have local implicit instantiations that need to be
3877       // instantiated within this scope.
3878       PerformPendingInstantiations(/*LocalOnly=*/true);
3879 
3880       Local.Exit();
3881 
3882       if (Recursive) {
3883         // Define any newly required vtables.
3884         DefineUsedVTables();
3885 
3886         // Instantiate any pending implicit instantiations found during the
3887         // instantiation of this template.
3888         PerformPendingInstantiations();
3889 
3890         // PendingInstantiations and VTableUses are restored through
3891         // SavePendingInstantiationsAndVTableUses's destructor.
3892       }
3893     }
3894 
3895     // Find actual definition
3896     Def = PatternDecl->getDefinition(getASTContext());
3897   } else {
3898     // If this is a static data member, find its out-of-line definition.
3899     assert(Var->isStaticDataMember() && "not a static data member?");
3900     PatternDecl = Var->getInstantiatedFromStaticDataMember();
3901 
3902     assert(PatternDecl && "data member was not instantiated from a template?");
3903     assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3904     Def = PatternDecl->getOutOfLineDefinition();
3905   }
3906 
3907   // If we don't have a definition of the variable template, we won't perform
3908   // any instantiation. Rather, we rely on the user to instantiate this
3909   // definition (or provide a specialization for it) in another translation
3910   // unit.
3911   if (!Def) {
3912     if (DefinitionRequired) {
3913       if (VarSpec)
3914         Diag(PointOfInstantiation,
3915              diag::err_explicit_instantiation_undefined_var_template) << Var;
3916       else
3917         Diag(PointOfInstantiation,
3918              diag::err_explicit_instantiation_undefined_member)
3919             << 2 << Var->getDeclName() << Var->getDeclContext();
3920       Diag(PatternDecl->getLocation(),
3921            diag::note_explicit_instantiation_here);
3922       if (VarSpec)
3923         Var->setInvalidDecl();
3924     } else if (Var->getTemplateSpecializationKind()
3925                  == TSK_ExplicitInstantiationDefinition) {
3926       PendingInstantiations.push_back(
3927         std::make_pair(Var, PointOfInstantiation));
3928     }
3929 
3930     return;
3931   }
3932 
3933   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3934 
3935   // Never instantiate an explicit specialization.
3936   if (TSK == TSK_ExplicitSpecialization)
3937     return;
3938 
3939   // C++11 [temp.explicit]p10:
3940   //   Except for inline functions, [...] explicit instantiation declarations
3941   //   have the effect of suppressing the implicit instantiation of the entity
3942   //   to which they refer.
3943   if (TSK == TSK_ExplicitInstantiationDeclaration)
3944     return;
3945 
3946   // Make sure to pass the instantiated variable to the consumer at the end.
3947   struct PassToConsumerRAII {
3948     ASTConsumer &Consumer;
3949     VarDecl *Var;
3950 
3951     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3952       : Consumer(Consumer), Var(Var) { }
3953 
3954     ~PassToConsumerRAII() {
3955       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3956     }
3957   } PassToConsumerRAII(Consumer, Var);
3958 
3959   // If we already have a definition, we're done.
3960   if (VarDecl *Def = Var->getDefinition()) {
3961     // We may be explicitly instantiating something we've already implicitly
3962     // instantiated.
3963     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3964                                        PointOfInstantiation);
3965     return;
3966   }
3967 
3968   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3969   if (Inst.isInvalid())
3970     return;
3971 
3972   // If we're performing recursive template instantiation, create our own
3973   // queue of pending implicit instantiations that we will instantiate later,
3974   // while we're still within our own instantiation context.
3975   SavePendingLocalImplicitInstantiationsRAII
3976       SavedPendingLocalImplicitInstantiations(*this);
3977   SavePendingInstantiationsAndVTableUsesRAII
3978       SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3979 
3980   // Enter the scope of this instantiation. We don't use
3981   // PushDeclContext because we don't have a scope.
3982   ContextRAII PreviousContext(*this, Var->getDeclContext());
3983   LocalInstantiationScope Local(*this);
3984 
3985   VarDecl *OldVar = Var;
3986   if (!VarSpec)
3987     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3988                                           TemplateArgs));
3989   else if (Var->isStaticDataMember() &&
3990            Var->getLexicalDeclContext()->isRecord()) {
3991     // We need to instantiate the definition of a static data member template,
3992     // and all we have is the in-class declaration of it. Instantiate a separate
3993     // declaration of the definition.
3994     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3995                                           TemplateArgs);
3996     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3997         VarSpec->getSpecializedTemplate(), Def, nullptr,
3998         VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3999     if (Var) {
4000       llvm::PointerUnion<VarTemplateDecl *,
4001                          VarTemplatePartialSpecializationDecl *> PatternPtr =
4002           VarSpec->getSpecializedTemplateOrPartial();
4003       if (VarTemplatePartialSpecializationDecl *Partial =
4004           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4005         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4006             Partial, &VarSpec->getTemplateInstantiationArgs());
4007 
4008       // Merge the definition with the declaration.
4009       LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4010                      LookupOrdinaryName, ForRedeclaration);
4011       R.addDecl(OldVar);
4012       MergeVarDecl(Var, R);
4013 
4014       // Attach the initializer.
4015       InstantiateVariableInitializer(Var, Def, TemplateArgs);
4016     }
4017   } else
4018     // Complete the existing variable's definition with an appropriately
4019     // substituted type and initializer.
4020     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4021 
4022   PreviousContext.pop();
4023 
4024   if (Var) {
4025     PassToConsumerRAII.Var = Var;
4026     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4027                                        OldVar->getPointOfInstantiation());
4028   }
4029 
4030   // This variable may have local implicit instantiations that need to be
4031   // instantiated within this scope.
4032   PerformPendingInstantiations(/*LocalOnly=*/true);
4033 
4034   Local.Exit();
4035 
4036   if (Recursive) {
4037     // Define any newly required vtables.
4038     DefineUsedVTables();
4039 
4040     // Instantiate any pending implicit instantiations found during the
4041     // instantiation of this template.
4042     PerformPendingInstantiations();
4043 
4044     // PendingInstantiations and VTableUses are restored through
4045     // SavePendingInstantiationsAndVTableUses's destructor.
4046   }
4047 }
4048 
4049 void
4050 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4051                                  const CXXConstructorDecl *Tmpl,
4052                            const MultiLevelTemplateArgumentList &TemplateArgs) {
4053 
4054   SmallVector<CXXCtorInitializer*, 4> NewInits;
4055   bool AnyErrors = Tmpl->isInvalidDecl();
4056 
4057   // Instantiate all the initializers.
4058   for (const auto *Init : Tmpl->inits()) {
4059     // Only instantiate written initializers, let Sema re-construct implicit
4060     // ones.
4061     if (!Init->isWritten())
4062       continue;
4063 
4064     SourceLocation EllipsisLoc;
4065 
4066     if (Init->isPackExpansion()) {
4067       // This is a pack expansion. We should expand it now.
4068       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4069       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4070       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4071       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4072       bool ShouldExpand = false;
4073       bool RetainExpansion = false;
4074       Optional<unsigned> NumExpansions;
4075       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4076                                           BaseTL.getSourceRange(),
4077                                           Unexpanded,
4078                                           TemplateArgs, ShouldExpand,
4079                                           RetainExpansion,
4080                                           NumExpansions)) {
4081         AnyErrors = true;
4082         New->setInvalidDecl();
4083         continue;
4084       }
4085       assert(ShouldExpand && "Partial instantiation of base initializer?");
4086 
4087       // Loop over all of the arguments in the argument pack(s),
4088       for (unsigned I = 0; I != *NumExpansions; ++I) {
4089         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4090 
4091         // Instantiate the initializer.
4092         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4093                                                /*CXXDirectInit=*/true);
4094         if (TempInit.isInvalid()) {
4095           AnyErrors = true;
4096           break;
4097         }
4098 
4099         // Instantiate the base type.
4100         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4101                                               TemplateArgs,
4102                                               Init->getSourceLocation(),
4103                                               New->getDeclName());
4104         if (!BaseTInfo) {
4105           AnyErrors = true;
4106           break;
4107         }
4108 
4109         // Build the initializer.
4110         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4111                                                      BaseTInfo, TempInit.get(),
4112                                                      New->getParent(),
4113                                                      SourceLocation());
4114         if (NewInit.isInvalid()) {
4115           AnyErrors = true;
4116           break;
4117         }
4118 
4119         NewInits.push_back(NewInit.get());
4120       }
4121 
4122       continue;
4123     }
4124 
4125     // Instantiate the initializer.
4126     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4127                                            /*CXXDirectInit=*/true);
4128     if (TempInit.isInvalid()) {
4129       AnyErrors = true;
4130       continue;
4131     }
4132 
4133     MemInitResult NewInit;
4134     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4135       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4136                                         TemplateArgs,
4137                                         Init->getSourceLocation(),
4138                                         New->getDeclName());
4139       if (!TInfo) {
4140         AnyErrors = true;
4141         New->setInvalidDecl();
4142         continue;
4143       }
4144 
4145       if (Init->isBaseInitializer())
4146         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4147                                        New->getParent(), EllipsisLoc);
4148       else
4149         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4150                                   cast<CXXRecordDecl>(CurContext->getParent()));
4151     } else if (Init->isMemberInitializer()) {
4152       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4153                                                      Init->getMemberLocation(),
4154                                                      Init->getMember(),
4155                                                      TemplateArgs));
4156       if (!Member) {
4157         AnyErrors = true;
4158         New->setInvalidDecl();
4159         continue;
4160       }
4161 
4162       NewInit = BuildMemberInitializer(Member, TempInit.get(),
4163                                        Init->getSourceLocation());
4164     } else if (Init->isIndirectMemberInitializer()) {
4165       IndirectFieldDecl *IndirectMember =
4166          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4167                                  Init->getMemberLocation(),
4168                                  Init->getIndirectMember(), TemplateArgs));
4169 
4170       if (!IndirectMember) {
4171         AnyErrors = true;
4172         New->setInvalidDecl();
4173         continue;
4174       }
4175 
4176       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4177                                        Init->getSourceLocation());
4178     }
4179 
4180     if (NewInit.isInvalid()) {
4181       AnyErrors = true;
4182       New->setInvalidDecl();
4183     } else {
4184       NewInits.push_back(NewInit.get());
4185     }
4186   }
4187 
4188   // Assign all the initializers to the new constructor.
4189   ActOnMemInitializers(New,
4190                        /*FIXME: ColonLoc */
4191                        SourceLocation(),
4192                        NewInits,
4193                        AnyErrors);
4194 }
4195 
4196 // TODO: this could be templated if the various decl types used the
4197 // same method name.
4198 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4199                               ClassTemplateDecl *Instance) {
4200   Pattern = Pattern->getCanonicalDecl();
4201 
4202   do {
4203     Instance = Instance->getCanonicalDecl();
4204     if (Pattern == Instance) return true;
4205     Instance = Instance->getInstantiatedFromMemberTemplate();
4206   } while (Instance);
4207 
4208   return false;
4209 }
4210 
4211 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4212                               FunctionTemplateDecl *Instance) {
4213   Pattern = Pattern->getCanonicalDecl();
4214 
4215   do {
4216     Instance = Instance->getCanonicalDecl();
4217     if (Pattern == Instance) return true;
4218     Instance = Instance->getInstantiatedFromMemberTemplate();
4219   } while (Instance);
4220 
4221   return false;
4222 }
4223 
4224 static bool
4225 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4226                   ClassTemplatePartialSpecializationDecl *Instance) {
4227   Pattern
4228     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4229   do {
4230     Instance = cast<ClassTemplatePartialSpecializationDecl>(
4231                                                 Instance->getCanonicalDecl());
4232     if (Pattern == Instance)
4233       return true;
4234     Instance = Instance->getInstantiatedFromMember();
4235   } while (Instance);
4236 
4237   return false;
4238 }
4239 
4240 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4241                               CXXRecordDecl *Instance) {
4242   Pattern = Pattern->getCanonicalDecl();
4243 
4244   do {
4245     Instance = Instance->getCanonicalDecl();
4246     if (Pattern == Instance) return true;
4247     Instance = Instance->getInstantiatedFromMemberClass();
4248   } while (Instance);
4249 
4250   return false;
4251 }
4252 
4253 static bool isInstantiationOf(FunctionDecl *Pattern,
4254                               FunctionDecl *Instance) {
4255   Pattern = Pattern->getCanonicalDecl();
4256 
4257   do {
4258     Instance = Instance->getCanonicalDecl();
4259     if (Pattern == Instance) return true;
4260     Instance = Instance->getInstantiatedFromMemberFunction();
4261   } while (Instance);
4262 
4263   return false;
4264 }
4265 
4266 static bool isInstantiationOf(EnumDecl *Pattern,
4267                               EnumDecl *Instance) {
4268   Pattern = Pattern->getCanonicalDecl();
4269 
4270   do {
4271     Instance = Instance->getCanonicalDecl();
4272     if (Pattern == Instance) return true;
4273     Instance = Instance->getInstantiatedFromMemberEnum();
4274   } while (Instance);
4275 
4276   return false;
4277 }
4278 
4279 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4280                               UsingShadowDecl *Instance,
4281                               ASTContext &C) {
4282   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4283                             Pattern);
4284 }
4285 
4286 static bool isInstantiationOf(UsingDecl *Pattern,
4287                               UsingDecl *Instance,
4288                               ASTContext &C) {
4289   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4290 }
4291 
4292 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4293                               UsingDecl *Instance,
4294                               ASTContext &C) {
4295   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4296 }
4297 
4298 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4299                               UsingDecl *Instance,
4300                               ASTContext &C) {
4301   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4302 }
4303 
4304 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4305                                               VarDecl *Instance) {
4306   assert(Instance->isStaticDataMember());
4307 
4308   Pattern = Pattern->getCanonicalDecl();
4309 
4310   do {
4311     Instance = Instance->getCanonicalDecl();
4312     if (Pattern == Instance) return true;
4313     Instance = Instance->getInstantiatedFromStaticDataMember();
4314   } while (Instance);
4315 
4316   return false;
4317 }
4318 
4319 // Other is the prospective instantiation
4320 // D is the prospective pattern
4321 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4322   if (D->getKind() != Other->getKind()) {
4323     if (UnresolvedUsingTypenameDecl *UUD
4324           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4325       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4326         return isInstantiationOf(UUD, UD, Ctx);
4327       }
4328     }
4329 
4330     if (UnresolvedUsingValueDecl *UUD
4331           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4332       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4333         return isInstantiationOf(UUD, UD, Ctx);
4334       }
4335     }
4336 
4337     return false;
4338   }
4339 
4340   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4341     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4342 
4343   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4344     return isInstantiationOf(cast<FunctionDecl>(D), Function);
4345 
4346   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4347     return isInstantiationOf(cast<EnumDecl>(D), Enum);
4348 
4349   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4350     if (Var->isStaticDataMember())
4351       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4352 
4353   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4354     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4355 
4356   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4357     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4358 
4359   if (ClassTemplatePartialSpecializationDecl *PartialSpec
4360         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4361     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4362                              PartialSpec);
4363 
4364   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4365     if (!Field->getDeclName()) {
4366       // This is an unnamed field.
4367       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4368                                 cast<FieldDecl>(D));
4369     }
4370   }
4371 
4372   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4373     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4374 
4375   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4376     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4377 
4378   return D->getDeclName() && isa<NamedDecl>(Other) &&
4379     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4380 }
4381 
4382 template<typename ForwardIterator>
4383 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4384                                       NamedDecl *D,
4385                                       ForwardIterator first,
4386                                       ForwardIterator last) {
4387   for (; first != last; ++first)
4388     if (isInstantiationOf(Ctx, D, *first))
4389       return cast<NamedDecl>(*first);
4390 
4391   return nullptr;
4392 }
4393 
4394 /// \brief Finds the instantiation of the given declaration context
4395 /// within the current instantiation.
4396 ///
4397 /// \returns NULL if there was an error
4398 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4399                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4400   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4401     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4402     return cast_or_null<DeclContext>(ID);
4403   } else return DC;
4404 }
4405 
4406 /// \brief Find the instantiation of the given declaration within the
4407 /// current instantiation.
4408 ///
4409 /// This routine is intended to be used when \p D is a declaration
4410 /// referenced from within a template, that needs to mapped into the
4411 /// corresponding declaration within an instantiation. For example,
4412 /// given:
4413 ///
4414 /// \code
4415 /// template<typename T>
4416 /// struct X {
4417 ///   enum Kind {
4418 ///     KnownValue = sizeof(T)
4419 ///   };
4420 ///
4421 ///   bool getKind() const { return KnownValue; }
4422 /// };
4423 ///
4424 /// template struct X<int>;
4425 /// \endcode
4426 ///
4427 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4428 /// \p EnumConstantDecl for \p KnownValue (which refers to
4429 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4430 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4431 /// this mapping from within the instantiation of <tt>X<int></tt>.
4432 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4433                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4434   DeclContext *ParentDC = D->getDeclContext();
4435   // FIXME: Parmeters of pointer to functions (y below) that are themselves
4436   // parameters (p below) can have their ParentDC set to the translation-unit
4437   // - thus we can not consistently check if the ParentDC of such a parameter
4438   // is Dependent or/and a FunctionOrMethod.
4439   // For e.g. this code, during Template argument deduction tries to
4440   // find an instantiated decl for (T y) when the ParentDC for y is
4441   // the translation unit.
4442   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4443   //   float baz(float(*)()) { return 0.0; }
4444   //   Foo(baz);
4445   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4446   // it gets here, always has a FunctionOrMethod as its ParentDC??
4447   // For now:
4448   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4449   //    whose type is not instantiation dependent, do nothing to the decl
4450   //  - otherwise find its instantiated decl.
4451   if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4452       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4453     return D;
4454   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4455       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4456       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4457       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4458     // D is a local of some kind. Look into the map of local
4459     // declarations to their instantiations.
4460     if (CurrentInstantiationScope) {
4461       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4462         if (Decl *FD = Found->dyn_cast<Decl *>())
4463           return cast<NamedDecl>(FD);
4464 
4465         int PackIdx = ArgumentPackSubstitutionIndex;
4466         assert(PackIdx != -1 &&
4467                "found declaration pack but not pack expanding");
4468         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4469         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4470       }
4471     }
4472 
4473     // If we're performing a partial substitution during template argument
4474     // deduction, we may not have values for template parameters yet. They
4475     // just map to themselves.
4476     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4477         isa<TemplateTemplateParmDecl>(D))
4478       return D;
4479 
4480     if (D->isInvalidDecl())
4481       return nullptr;
4482 
4483     // Normally this function only searches for already instantiated declaration
4484     // however we have to make an exclusion for local types used before
4485     // definition as in the code:
4486     //
4487     //   template<typename T> void f1() {
4488     //     void g1(struct x1);
4489     //     struct x1 {};
4490     //   }
4491     //
4492     // In this case instantiation of the type of 'g1' requires definition of
4493     // 'x1', which is defined later. Error recovery may produce an enum used
4494     // before definition. In these cases we need to instantiate relevant
4495     // declarations here.
4496     bool NeedInstantiate = false;
4497     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4498       NeedInstantiate = RD->isLocalClass();
4499     else
4500       NeedInstantiate = isa<EnumDecl>(D);
4501     if (NeedInstantiate) {
4502       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4503       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4504       return cast<TypeDecl>(Inst);
4505     }
4506 
4507     // If we didn't find the decl, then we must have a label decl that hasn't
4508     // been found yet.  Lazily instantiate it and return it now.
4509     assert(isa<LabelDecl>(D));
4510 
4511     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4512     assert(Inst && "Failed to instantiate label??");
4513 
4514     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4515     return cast<LabelDecl>(Inst);
4516   }
4517 
4518   // For variable template specializations, update those that are still
4519   // type-dependent.
4520   if (VarTemplateSpecializationDecl *VarSpec =
4521           dyn_cast<VarTemplateSpecializationDecl>(D)) {
4522     bool InstantiationDependent = false;
4523     const TemplateArgumentListInfo &VarTemplateArgs =
4524         VarSpec->getTemplateArgsInfo();
4525     if (TemplateSpecializationType::anyDependentTemplateArguments(
4526             VarTemplateArgs, InstantiationDependent))
4527       D = cast<NamedDecl>(
4528           SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4529     return D;
4530   }
4531 
4532   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4533     if (!Record->isDependentContext())
4534       return D;
4535 
4536     // Determine whether this record is the "templated" declaration describing
4537     // a class template or class template partial specialization.
4538     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4539     if (ClassTemplate)
4540       ClassTemplate = ClassTemplate->getCanonicalDecl();
4541     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4542                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4543       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4544 
4545     // Walk the current context to find either the record or an instantiation of
4546     // it.
4547     DeclContext *DC = CurContext;
4548     while (!DC->isFileContext()) {
4549       // If we're performing substitution while we're inside the template
4550       // definition, we'll find our own context. We're done.
4551       if (DC->Equals(Record))
4552         return Record;
4553 
4554       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4555         // Check whether we're in the process of instantiating a class template
4556         // specialization of the template we're mapping.
4557         if (ClassTemplateSpecializationDecl *InstSpec
4558                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4559           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4560           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4561             return InstRecord;
4562         }
4563 
4564         // Check whether we're in the process of instantiating a member class.
4565         if (isInstantiationOf(Record, InstRecord))
4566           return InstRecord;
4567       }
4568 
4569       // Move to the outer template scope.
4570       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4571         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4572           DC = FD->getLexicalDeclContext();
4573           continue;
4574         }
4575       }
4576 
4577       DC = DC->getParent();
4578     }
4579 
4580     // Fall through to deal with other dependent record types (e.g.,
4581     // anonymous unions in class templates).
4582   }
4583 
4584   if (!ParentDC->isDependentContext())
4585     return D;
4586 
4587   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4588   if (!ParentDC)
4589     return nullptr;
4590 
4591   if (ParentDC != D->getDeclContext()) {
4592     // We performed some kind of instantiation in the parent context,
4593     // so now we need to look into the instantiated parent context to
4594     // find the instantiation of the declaration D.
4595 
4596     // If our context used to be dependent, we may need to instantiate
4597     // it before performing lookup into that context.
4598     bool IsBeingInstantiated = false;
4599     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4600       if (!Spec->isDependentContext()) {
4601         QualType T = Context.getTypeDeclType(Spec);
4602         const RecordType *Tag = T->getAs<RecordType>();
4603         assert(Tag && "type of non-dependent record is not a RecordType");
4604         if (Tag->isBeingDefined())
4605           IsBeingInstantiated = true;
4606         if (!Tag->isBeingDefined() &&
4607             RequireCompleteType(Loc, T, diag::err_incomplete_type))
4608           return nullptr;
4609 
4610         ParentDC = Tag->getDecl();
4611       }
4612     }
4613 
4614     NamedDecl *Result = nullptr;
4615     if (D->getDeclName()) {
4616       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4617       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4618     } else {
4619       // Since we don't have a name for the entity we're looking for,
4620       // our only option is to walk through all of the declarations to
4621       // find that name. This will occur in a few cases:
4622       //
4623       //   - anonymous struct/union within a template
4624       //   - unnamed class/struct/union/enum within a template
4625       //
4626       // FIXME: Find a better way to find these instantiations!
4627       Result = findInstantiationOf(Context, D,
4628                                    ParentDC->decls_begin(),
4629                                    ParentDC->decls_end());
4630     }
4631 
4632     if (!Result) {
4633       if (isa<UsingShadowDecl>(D)) {
4634         // UsingShadowDecls can instantiate to nothing because of using hiding.
4635       } else if (Diags.hasErrorOccurred()) {
4636         // We've already complained about something, so most likely this
4637         // declaration failed to instantiate. There's no point in complaining
4638         // further, since this is normal in invalid code.
4639       } else if (IsBeingInstantiated) {
4640         // The class in which this member exists is currently being
4641         // instantiated, and we haven't gotten around to instantiating this
4642         // member yet. This can happen when the code uses forward declarations
4643         // of member classes, and introduces ordering dependencies via
4644         // template instantiation.
4645         Diag(Loc, diag::err_member_not_yet_instantiated)
4646           << D->getDeclName()
4647           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4648         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4649       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4650         // This enumeration constant was found when the template was defined,
4651         // but can't be found in the instantiation. This can happen if an
4652         // unscoped enumeration member is explicitly specialized.
4653         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4654         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4655                                                              TemplateArgs));
4656         assert(Spec->getTemplateSpecializationKind() ==
4657                  TSK_ExplicitSpecialization);
4658         Diag(Loc, diag::err_enumerator_does_not_exist)
4659           << D->getDeclName()
4660           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4661         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4662           << Context.getTypeDeclType(Spec);
4663       } else {
4664         // We should have found something, but didn't.
4665         llvm_unreachable("Unable to find instantiation of declaration!");
4666       }
4667     }
4668 
4669     D = Result;
4670   }
4671 
4672   return D;
4673 }
4674 
4675 /// \brief Performs template instantiation for all implicit template
4676 /// instantiations we have seen until this point.
4677 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4678   while (!PendingLocalImplicitInstantiations.empty() ||
4679          (!LocalOnly && !PendingInstantiations.empty())) {
4680     PendingImplicitInstantiation Inst;
4681 
4682     if (PendingLocalImplicitInstantiations.empty()) {
4683       Inst = PendingInstantiations.front();
4684       PendingInstantiations.pop_front();
4685     } else {
4686       Inst = PendingLocalImplicitInstantiations.front();
4687       PendingLocalImplicitInstantiations.pop_front();
4688     }
4689 
4690     // Instantiate function definitions
4691     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4692       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4693                                           "instantiating function definition");
4694       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4695                                 TSK_ExplicitInstantiationDefinition;
4696       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4697                                     DefinitionRequired);
4698       continue;
4699     }
4700 
4701     // Instantiate variable definitions
4702     VarDecl *Var = cast<VarDecl>(Inst.first);
4703 
4704     assert((Var->isStaticDataMember() ||
4705             isa<VarTemplateSpecializationDecl>(Var)) &&
4706            "Not a static data member, nor a variable template"
4707            " specialization?");
4708 
4709     // Don't try to instantiate declarations if the most recent redeclaration
4710     // is invalid.
4711     if (Var->getMostRecentDecl()->isInvalidDecl())
4712       continue;
4713 
4714     // Check if the most recent declaration has changed the specialization kind
4715     // and removed the need for implicit instantiation.
4716     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4717     case TSK_Undeclared:
4718       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4719     case TSK_ExplicitInstantiationDeclaration:
4720     case TSK_ExplicitSpecialization:
4721       continue;  // No longer need to instantiate this type.
4722     case TSK_ExplicitInstantiationDefinition:
4723       // We only need an instantiation if the pending instantiation *is* the
4724       // explicit instantiation.
4725       if (Var != Var->getMostRecentDecl()) continue;
4726     case TSK_ImplicitInstantiation:
4727       break;
4728     }
4729 
4730     PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4731                                         "instantiating variable definition");
4732     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4733                               TSK_ExplicitInstantiationDefinition;
4734 
4735     // Instantiate static data member definitions or variable template
4736     // specializations.
4737     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4738                                   DefinitionRequired);
4739   }
4740 }
4741 
4742 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4743                        const MultiLevelTemplateArgumentList &TemplateArgs) {
4744   for (auto DD : Pattern->ddiags()) {
4745     switch (DD->getKind()) {
4746     case DependentDiagnostic::Access:
4747       HandleDependentAccessCheck(*DD, TemplateArgs);
4748       break;
4749     }
4750   }
4751 }
4752