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