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