clang  16.0.0git
SemaTemplateInstantiateDecl.cpp
Go to the documentation of this file.
1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
7 //
8 // This file implements C++ template instantiation for declarations.
9 //
10 //===----------------------------------------------------------------------===/
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/TypeLoc.h"
24 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/Template.h"
31 #include "llvm/Support/TimeProfiler.h"
32 
33 using namespace clang;
34 
35 static bool isDeclWithinFunction(const Decl *D) {
36  const DeclContext *DC = D->getDeclContext();
37  if (DC->isFunctionOrMethod())
38  return true;
39 
40  if (DC->isRecord())
41  return cast<CXXRecordDecl>(DC)->isLocalClass();
42 
43  return false;
44 }
45 
46 template<typename DeclT>
47 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
48  const MultiLevelTemplateArgumentList &TemplateArgs) {
49  if (!OldDecl->getQualifierLoc())
50  return false;
51 
52  assert((NewDecl->getFriendObjectKind() ||
53  !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
54  "non-friend with qualified name defined in dependent context");
55  Sema::ContextRAII SavedContext(
56  SemaRef,
57  const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
58  ? NewDecl->getLexicalDeclContext()
59  : OldDecl->getLexicalDeclContext()));
60 
61  NestedNameSpecifierLoc NewQualifierLoc
62  = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63  TemplateArgs);
64 
65  if (!NewQualifierLoc)
66  return true;
67 
68  NewDecl->setQualifierInfo(NewQualifierLoc);
69  return false;
70 }
71 
73  DeclaratorDecl *NewDecl) {
74  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
75 }
76 
78  TagDecl *NewDecl) {
79  return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
80 }
81 
82 // Include attribute instantiation code.
83 #include "clang/Sema/AttrTemplateInstantiate.inc"
84 
86  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
87  const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
88  if (Aligned->isAlignmentExpr()) {
89  // The alignment expression is a constant expression.
92  ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
93  if (!Result.isInvalid())
94  S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
95  } else {
96  TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
97  TemplateArgs, Aligned->getLocation(),
98  DeclarationName());
99  if (Result)
100  S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
101  }
102 }
103 
105  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
106  const AlignedAttr *Aligned, Decl *New) {
107  if (!Aligned->isPackExpansion()) {
108  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
109  return;
110  }
111 
113  if (Aligned->isAlignmentExpr())
114  S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
115  Unexpanded);
116  else
117  S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
118  Unexpanded);
119  assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
120 
121  // Determine whether we can expand this attribute pack yet.
122  bool Expand = true, RetainExpansion = false;
123  Optional<unsigned> NumExpansions;
124  // FIXME: Use the actual location of the ellipsis.
125  SourceLocation EllipsisLoc = Aligned->getLocation();
126  if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
127  Unexpanded, TemplateArgs, Expand,
128  RetainExpansion, NumExpansions))
129  return;
130 
131  if (!Expand) {
132  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
133  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
134  } else {
135  for (unsigned I = 0; I != *NumExpansions; ++I) {
137  instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
138  }
139  }
140 }
141 
143  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
144  const AssumeAlignedAttr *Aligned, Decl *New) {
145  // The alignment expression is a constant expression.
148 
149  Expr *E, *OE = nullptr;
150  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
151  if (Result.isInvalid())
152  return;
153  E = Result.getAs<Expr>();
154 
155  if (Aligned->getOffset()) {
156  Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
157  if (Result.isInvalid())
158  return;
159  OE = Result.getAs<Expr>();
160  }
161 
162  S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
163 }
164 
166  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
167  const AlignValueAttr *Aligned, Decl *New) {
168  // The alignment expression is a constant expression.
171  ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
172  if (!Result.isInvalid())
173  S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
174 }
175 
177  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
178  const AllocAlignAttr *Align, Decl *New) {
179  Expr *Param = IntegerLiteral::Create(
180  S.getASTContext(),
181  llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
182  S.getASTContext().UnsignedLongLongTy, Align->getLocation());
183  S.AddAllocAlignAttr(New, *Align, Param);
184 }
185 
187  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
188  const AnnotateAttr *Attr, Decl *New) {
191 
192  // If the attribute has delayed arguments it will have to instantiate those
193  // and handle them as new arguments for the attribute.
194  bool HasDelayedArgs = Attr->delayedArgs_size();
195 
196  ArrayRef<Expr *> ArgsToInstantiate =
197  HasDelayedArgs
198  ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
199  : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
200 
202  if (S.SubstExprs(ArgsToInstantiate,
203  /*IsCall=*/false, TemplateArgs, Args))
204  return;
205 
206  StringRef Str = Attr->getAnnotation();
207  if (HasDelayedArgs) {
208  if (Args.size() < 1) {
209  S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
210  << Attr << 1;
211  return;
212  }
213 
214  if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
215  return;
216 
217  llvm::SmallVector<Expr *, 4> ActualArgs;
218  ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
219  std::swap(Args, ActualArgs);
220  }
221  S.AddAnnotationAttr(New, *Attr, Str, Args);
222 }
223 
225  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
226  const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
227  Expr *Cond = nullptr;
228  {
229  Sema::ContextRAII SwitchContext(S, New);
232  ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
233  if (Result.isInvalid())
234  return nullptr;
235  Cond = Result.getAs<Expr>();
236  }
237  if (!Cond->isTypeDependent()) {
238  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
239  if (Converted.isInvalid())
240  return nullptr;
241  Cond = Converted.get();
242  }
243 
245  if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
246  !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
247  S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
248  for (const auto &P : Diags)
249  S.Diag(P.first, P.second);
250  return nullptr;
251  }
252  return Cond;
253 }
254 
256  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
257  const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
259  S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
260 
261  if (Cond)
262  New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
263  Cond, EIA->getMessage()));
264 }
265 
267  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
268  const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
270  S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
271 
272  if (Cond)
273  New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
274  S.getASTContext(), *DIA, Cond, DIA->getMessage(),
275  DIA->getDiagnosticType(), DIA->getArgDependent(), New));
276 }
277 
278 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
279 // template A as the base and arguments from TemplateArgs.
281  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
282  const CUDALaunchBoundsAttr &Attr, Decl *New) {
283  // The alignment expression is a constant expression.
286 
287  ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
288  if (Result.isInvalid())
289  return;
290  Expr *MaxThreads = Result.getAs<Expr>();
291 
292  Expr *MinBlocks = nullptr;
293  if (Attr.getMinBlocks()) {
294  Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
295  if (Result.isInvalid())
296  return;
297  MinBlocks = Result.getAs<Expr>();
298  }
299 
300  S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
301 }
302 
303 static void
305  const MultiLevelTemplateArgumentList &TemplateArgs,
306  const ModeAttr &Attr, Decl *New) {
307  S.AddModeAttr(New, Attr, Attr.getMode(),
308  /*InInstantiation=*/true);
309 }
310 
311 /// Instantiation of 'declare simd' attribute and its arguments.
313  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
314  const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
315  // Allow 'this' in clauses with varlists.
316  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
317  New = FTD->getTemplatedDecl();
318  auto *FD = cast<FunctionDecl>(New);
319  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
320  SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
321  SmallVector<unsigned, 4> LinModifiers;
322 
323  auto SubstExpr = [&](Expr *E) -> ExprResult {
324  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
325  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
326  Sema::ContextRAII SavedContext(S, FD);
327  LocalInstantiationScope Local(S);
328  if (FD->getNumParams() > PVD->getFunctionScopeIndex())
329  Local.InstantiatedLocal(
330  PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
331  return S.SubstExpr(E, TemplateArgs);
332  }
333  Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
334  FD->isCXXInstanceMember());
335  return S.SubstExpr(E, TemplateArgs);
336  };
337 
338  // Substitute a single OpenMP clause, which is a potentially-evaluated
339  // full-expression.
340  auto Subst = [&](Expr *E) -> ExprResult {
343  ExprResult Res = SubstExpr(E);
344  if (Res.isInvalid())
345  return Res;
346  return S.ActOnFinishFullExpr(Res.get(), false);
347  };
348 
349  ExprResult Simdlen;
350  if (auto *E = Attr.getSimdlen())
351  Simdlen = Subst(E);
352 
353  if (Attr.uniforms_size() > 0) {
354  for(auto *E : Attr.uniforms()) {
355  ExprResult Inst = Subst(E);
356  if (Inst.isInvalid())
357  continue;
358  Uniforms.push_back(Inst.get());
359  }
360  }
361 
362  auto AI = Attr.alignments_begin();
363  for (auto *E : Attr.aligneds()) {
364  ExprResult Inst = Subst(E);
365  if (Inst.isInvalid())
366  continue;
367  Aligneds.push_back(Inst.get());
368  Inst = ExprEmpty();
369  if (*AI)
370  Inst = S.SubstExpr(*AI, TemplateArgs);
371  Alignments.push_back(Inst.get());
372  ++AI;
373  }
374 
375  auto SI = Attr.steps_begin();
376  for (auto *E : Attr.linears()) {
377  ExprResult Inst = Subst(E);
378  if (Inst.isInvalid())
379  continue;
380  Linears.push_back(Inst.get());
381  Inst = ExprEmpty();
382  if (*SI)
383  Inst = S.SubstExpr(*SI, TemplateArgs);
384  Steps.push_back(Inst.get());
385  ++SI;
386  }
387  LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
389  S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
390  Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
391  Attr.getRange());
392 }
393 
394 /// Instantiation of 'declare variant' attribute and its arguments.
396  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
397  const OMPDeclareVariantAttr &Attr, Decl *New) {
398  // Allow 'this' in clauses with varlists.
399  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
400  New = FTD->getTemplatedDecl();
401  auto *FD = cast<FunctionDecl>(New);
402  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
403 
404  auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
405  if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
406  if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
407  Sema::ContextRAII SavedContext(S, FD);
408  LocalInstantiationScope Local(S);
409  if (FD->getNumParams() > PVD->getFunctionScopeIndex())
410  Local.InstantiatedLocal(
411  PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
412  return S.SubstExpr(E, TemplateArgs);
413  }
414  Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
415  FD->isCXXInstanceMember());
416  return S.SubstExpr(E, TemplateArgs);
417  };
418 
419  // Substitute a single OpenMP clause, which is a potentially-evaluated
420  // full-expression.
421  auto &&Subst = [&SubstExpr, &S](Expr *E) {
424  ExprResult Res = SubstExpr(E);
425  if (Res.isInvalid())
426  return Res;
427  return S.ActOnFinishFullExpr(Res.get(), false);
428  };
429 
430  ExprResult VariantFuncRef;
431  if (Expr *E = Attr.getVariantFuncRef()) {
432  // Do not mark function as is used to prevent its emission if this is the
433  // only place where it is used.
436  VariantFuncRef = Subst(E);
437  }
438 
439  // Copy the template version of the OMPTraitInfo and run substitute on all
440  // score and condition expressiosn.
442  TI = *Attr.getTraitInfos();
443 
444  // Try to substitute template parameters in score and condition expressions.
445  auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
446  if (E) {
449  ExprResult ER = Subst(E);
450  if (ER.isUsable())
451  E = ER.get();
452  else
453  return true;
454  }
455  return false;
456  };
457  if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
458  return;
459 
460  Expr *E = VariantFuncRef.get();
461 
462  // Check function/variant ref for `omp declare variant` but not for `omp
463  // begin declare variant` (which use implicit attributes).
466  Attr.appendArgs_size(),
467  Attr.getRange());
468 
469  if (!DeclVarData)
470  return;
471 
472  E = DeclVarData.value().second;
473  FD = DeclVarData.value().first;
474 
475  if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
476  if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
477  if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
478  if (!VariantFTD->isThisDeclarationADefinition())
479  return;
482  S.Context, TemplateArgs.getInnermost());
483 
484  auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
485  New->getLocation());
486  if (!SubstFD)
487  return;
488  QualType NewType = S.Context.mergeFunctionTypes(
489  SubstFD->getType(), FD->getType(),
490  /* OfBlockPointer */ false,
491  /* Unqualified */ false, /* AllowCXX */ true);
492  if (NewType.isNull())
493  return;
495  New->getLocation(), SubstFD, /* Recursive */ true,
496  /* DefinitionRequired */ false, /* AtEndOfTU */ false);
497  SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
499  SourceLocation(), SubstFD,
500  /* RefersToEnclosingVariableOrCapture */ false,
501  /* NameLoc */ SubstFD->getLocation(),
502  SubstFD->getType(), ExprValueKind::VK_PRValue);
503  }
504  }
505  }
506 
507  SmallVector<Expr *, 8> NothingExprs;
508  SmallVector<Expr *, 8> NeedDevicePtrExprs;
510 
511  for (Expr *E : Attr.adjustArgsNothing()) {
512  ExprResult ER = Subst(E);
513  if (ER.isInvalid())
514  continue;
515  NothingExprs.push_back(ER.get());
516  }
517  for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
518  ExprResult ER = Subst(E);
519  if (ER.isInvalid())
520  continue;
521  NeedDevicePtrExprs.push_back(ER.get());
522  }
523  for (OMPInteropInfo &II : Attr.appendArgs()) {
524  // When prefer_type is implemented for append_args handle them here too.
525  AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
526  }
527 
529  FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
531 }
532 
534  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
535  const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
536  // Both min and max expression are constant expressions.
539 
540  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
541  if (Result.isInvalid())
542  return;
543  Expr *MinExpr = Result.getAs<Expr>();
544 
545  Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
546  if (Result.isInvalid())
547  return;
548  Expr *MaxExpr = Result.getAs<Expr>();
549 
550  S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
551 }
552 
553 static ExplicitSpecifier
555  const MultiLevelTemplateArgumentList &TemplateArgs,
556  ExplicitSpecifier ES, FunctionDecl *New) {
557  if (!ES.getExpr())
558  return ES;
559  Expr *OldCond = ES.getExpr();
560  Expr *Cond = nullptr;
561  {
564  ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
565  if (SubstResult.isInvalid()) {
567  }
568  Cond = SubstResult.get();
569  }
570  ExplicitSpecifier Result(Cond, ES.getKind());
571  if (!Cond->isTypeDependent())
572  S.tryResolveExplicitSpecifier(Result);
573  return Result;
574 }
575 
577  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
578  const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
579  // Both min and max expression are constant expressions.
582 
583  ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
584  if (Result.isInvalid())
585  return;
586  Expr *MinExpr = Result.getAs<Expr>();
587 
588  Expr *MaxExpr = nullptr;
589  if (auto Max = Attr.getMax()) {
590  Result = S.SubstExpr(Max, TemplateArgs);
591  if (Result.isInvalid())
592  return;
593  MaxExpr = Result.getAs<Expr>();
594  }
595 
596  S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
597 }
598 
599 // This doesn't take any template parameters, but we have a custom action that
600 // needs to happen when the kernel itself is instantiated. We need to run the
601 // ItaniumMangler to mark the names required to name this kernel.
603  Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
604  const SYCLKernelAttr &Attr, Decl *New) {
605  New->addAttr(Attr.clone(S.getASTContext()));
606 }
607 
608 /// Determine whether the attribute A might be relevant to the declaration D.
609 /// If not, we can skip instantiating it. The attribute may or may not have
610 /// been instantiated yet.
611 static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
612  // 'preferred_name' is only relevant to the matching specialization of the
613  // template.
614  if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
615  QualType T = PNA->getTypedefType();
616  const auto *RD = cast<CXXRecordDecl>(D);
617  if (!T->isDependentType() && !RD->isDependentContext() &&
619  return false;
620  for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
621  if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
622  PNA->getTypedefType()))
623  return false;
624  return true;
625  }
626 
627  if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
628  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
629  switch (BA->getID()) {
630  case Builtin::BIforward:
631  // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
632  // type and returns an lvalue reference type. The library implementation
633  // will produce an error in this case; don't get in its way.
634  if (FD && FD->getNumParams() >= 1 &&
637  return false;
638  }
639  [[fallthrough]];
640  case Builtin::BImove:
641  case Builtin::BImove_if_noexcept:
642  // HACK: Super-old versions of libc++ (3.1 and earlier) provide
643  // std::forward and std::move overloads that sometimes return by value
644  // instead of by reference when building in C++98 mode. Don't treat such
645  // cases as builtins.
646  if (FD && !FD->getReturnType()->isReferenceType())
647  return false;
648  break;
649  }
650  }
651 
652  return true;
653 }
654 
656  const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
657  Decl *New, LateInstantiatedAttrVec *LateAttrs,
658  LocalInstantiationScope *OuterMostScope) {
659  if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
660  // FIXME: This function is called multiple times for the same template
661  // specialization. We should only instantiate attributes that were added
662  // since the previous instantiation.
663  for (const auto *TmplAttr : Tmpl->attrs()) {
664  if (!isRelevantAttr(*this, New, TmplAttr))
665  continue;
666 
667  // FIXME: If any of the special case versions from InstantiateAttrs become
668  // applicable to template declaration, we'll need to add them here.
669  CXXThisScopeRAII ThisScope(
670  *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
671  Qualifiers(), ND->isCXXInstanceMember());
672 
674  TmplAttr, Context, *this, TemplateArgs);
675  if (NewAttr && isRelevantAttr(*this, New, NewAttr))
676  New->addAttr(NewAttr);
677  }
678  }
679 }
680 
683  switch (A->getKind()) {
684  case clang::attr::CFConsumed:
686  case clang::attr::OSConsumed:
688  case clang::attr::NSConsumed:
690  default:
691  llvm_unreachable("Wrong argument supplied");
692  }
693 }
694 
696  const Decl *Tmpl, Decl *New,
697  LateInstantiatedAttrVec *LateAttrs,
698  LocalInstantiationScope *OuterMostScope) {
699  for (const auto *TmplAttr : Tmpl->attrs()) {
700  if (!isRelevantAttr(*this, New, TmplAttr))
701  continue;
702 
703  // FIXME: This should be generalized to more than just the AlignedAttr.
704  const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
705  if (Aligned && Aligned->isAlignmentDependent()) {
706  instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
707  continue;
708  }
709 
710  if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
711  instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
712  continue;
713  }
714 
715  if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
716  instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
717  continue;
718  }
719 
720  if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
721  instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
722  continue;
723  }
724 
725  if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
726  instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
727  continue;
728  }
729 
730  if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
731  instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
732  cast<FunctionDecl>(New));
733  continue;
734  }
735 
736  if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
737  instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
738  cast<FunctionDecl>(New));
739  continue;
740  }
741 
742  if (const auto *CUDALaunchBounds =
743  dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
744  instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
745  *CUDALaunchBounds, New);
746  continue;
747  }
748 
749  if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
750  instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
751  continue;
752  }
753 
754  if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
755  instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
756  continue;
757  }
758 
759  if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
760  instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
761  continue;
762  }
763 
764  if (const auto *AMDGPUFlatWorkGroupSize =
765  dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
767  *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
768  }
769 
770  if (const auto *AMDGPUFlatWorkGroupSize =
771  dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
772  instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
773  *AMDGPUFlatWorkGroupSize, New);
774  }
775 
776  // Existing DLL attribute on the instantiation takes precedence.
777  if (TmplAttr->getKind() == attr::DLLExport ||
778  TmplAttr->getKind() == attr::DLLImport) {
779  if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
780  continue;
781  }
782  }
783 
784  if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
785  AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
786  continue;
787  }
788 
789  if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
790  isa<CFConsumedAttr>(TmplAttr)) {
791  AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
792  /*template instantiation=*/true);
793  continue;
794  }
795 
796  if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
797  if (!New->hasAttr<PointerAttr>())
798  New->addAttr(A->clone(Context));
799  continue;
800  }
801 
802  if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
803  if (!New->hasAttr<OwnerAttr>())
804  New->addAttr(A->clone(Context));
805  continue;
806  }
807 
808  if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
809  instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
810  continue;
811  }
812 
813  assert(!TmplAttr->isPackExpansion());
814  if (TmplAttr->isLateParsed() && LateAttrs) {
815  // Late parsed attributes must be instantiated and attached after the
816  // enclosing class has been instantiated. See Sema::InstantiateClass.
817  LocalInstantiationScope *Saved = nullptr;
819  Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
820  LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
821  } else {
822  // Allow 'this' within late-parsed attributes.
823  auto *ND = cast<NamedDecl>(New);
824  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
825  CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
826  ND->isCXXInstanceMember());
827 
828  Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
829  *this, TemplateArgs);
830  if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
831  New->addAttr(NewAttr);
832  }
833  }
834 }
835 
836 /// In the MS ABI, we need to instantiate default arguments of dllexported
837 /// default constructors along with the constructor definition. This allows IR
838 /// gen to emit a constructor closure which calls the default constructor with
839 /// its default arguments.
842  Ctor->isDefaultConstructor());
843  unsigned NumParams = Ctor->getNumParams();
844  if (NumParams == 0)
845  return;
846  DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
847  if (!Attr)
848  return;
849  for (unsigned I = 0; I != NumParams; ++I) {
850  (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
851  Ctor->getParamDecl(I));
853  }
854 }
855 
856 /// Get the previous declaration of a declaration for the purposes of template
857 /// instantiation. If this finds a previous declaration, then the previous
858 /// declaration of the instantiation of D should be an instantiation of the
859 /// result of this function.
860 template<typename DeclT>
861 static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
862  DeclT *Result = D->getPreviousDecl();
863 
864  // If the declaration is within a class, and the previous declaration was
865  // merged from a different definition of that class, then we don't have a
866  // previous declaration for the purpose of template instantiation.
867  if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
869  return nullptr;
870 
871  return Result;
872 }
873 
874 Decl *
875 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
876  llvm_unreachable("Translation units cannot be instantiated");
877 }
878 
879 Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
880  llvm_unreachable("HLSL buffer declarations cannot be instantiated");
881 }
882 
883 Decl *
884 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
885  llvm_unreachable("pragma comment cannot be instantiated");
886 }
887 
888 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
890  llvm_unreachable("pragma comment cannot be instantiated");
891 }
892 
893 Decl *
894 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
895  llvm_unreachable("extern \"C\" context cannot be instantiated");
896 }
897 
898 Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
899  llvm_unreachable("GUID declaration cannot be instantiated");
900 }
901 
902 Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
904  llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated");
905 }
906 
907 Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
909  llvm_unreachable("template parameter objects cannot be instantiated");
910 }
911 
912 Decl *
913 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
914  LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
915  D->getIdentifier());
916  Owner->addDecl(Inst);
917  return Inst;
918 }
919 
920 Decl *
921 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
922  llvm_unreachable("Namespaces cannot be instantiated");
923 }
924 
925 Decl *
926 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
927  NamespaceAliasDecl *Inst
928  = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
929  D->getNamespaceLoc(),
930  D->getAliasLoc(),
931  D->getIdentifier(),
932  D->getQualifierLoc(),
933  D->getTargetNameLoc(),
934  D->getNamespace());
935  Owner->addDecl(Inst);
936  return Inst;
937 }
938 
940  bool IsTypeAlias) {
941  bool Invalid = false;
943  if (DI->getType()->isInstantiationDependentType() ||
944  DI->getType()->isVariablyModifiedType()) {
945  DI = SemaRef.SubstType(DI, TemplateArgs,
946  D->getLocation(), D->getDeclName());
947  if (!DI) {
948  Invalid = true;
949  DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
950  }
951  } else {
953  }
954 
955  // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
956  // libstdc++ relies upon this bug in its implementation of common_type. If we
957  // happen to be processing that implementation, fake up the g++ ?:
958  // semantics. See LWG issue 2141 for more information on the bug. The bugs
959  // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
960  const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
961  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
962  if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
963  DT->isReferenceType() &&
964  RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
965  RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
966  D->getIdentifier() && D->getIdentifier()->isStr("type") &&
968  // Fold it to the (non-reference) type which g++ would have produced.
969  DI = SemaRef.Context.getTrivialTypeSourceInfo(
970  DI->getType().getNonReferenceType());
971 
972  // Create the new typedef
973  TypedefNameDecl *Typedef;
974  if (IsTypeAlias)
975  Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
976  D->getLocation(), D->getIdentifier(), DI);
977  else
978  Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
979  D->getLocation(), D->getIdentifier(), DI);
980  if (Invalid)
981  Typedef->setInvalidDecl();
982 
983  // If the old typedef was the name for linkage purposes of an anonymous
984  // tag decl, re-establish that relationship for the new typedef.
985  if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
986  TagDecl *oldTag = oldTagType->getDecl();
987  if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
988  TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
989  assert(!newTag->hasNameForLinkage());
990  newTag->setTypedefNameForAnonDecl(Typedef);
991  }
992  }
993 
995  NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
996  TemplateArgs);
997  if (!InstPrev)
998  return nullptr;
999 
1000  TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1001 
1002  // If the typedef types are not identical, reject them.
1003  SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1004 
1005  Typedef->setPreviousDecl(InstPrevTypedef);
1006  }
1007 
1008  SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1009 
1011  SemaRef.inferGslPointerAttribute(Typedef);
1012 
1013  Typedef->setAccess(D->getAccess());
1014  Typedef->setReferenced(D->isReferenced());
1015 
1016  return Typedef;
1017 }
1018 
1019 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1020  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1021  if (Typedef)
1022  Owner->addDecl(Typedef);
1023  return Typedef;
1024 }
1025 
1026 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1027  Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1028  if (Typedef)
1029  Owner->addDecl(Typedef);
1030  return Typedef;
1031 }
1032 
1033 Decl *
1034 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1035  // Create a local instantiation scope for this type alias template, which
1036  // will contain the instantiations of the template parameters.
1037  LocalInstantiationScope Scope(SemaRef);
1038 
1039  TemplateParameterList *TempParams = D->getTemplateParameters();
1040  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1041  if (!InstParams)
1042  return nullptr;
1043 
1044  TypeAliasDecl *Pattern = D->getTemplatedDecl();
1045 
1046  TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1047  if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1048  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1049  if (!Found.empty()) {
1050  PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1051  }
1052  }
1053 
1054  TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1055  InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1056  if (!AliasInst)
1057  return nullptr;
1058 
1059  TypeAliasTemplateDecl *Inst
1060  = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1061  D->getDeclName(), InstParams, AliasInst);
1062  AliasInst->setDescribedAliasTemplate(Inst);
1063  if (PrevAliasTemplate)
1064  Inst->setPreviousDecl(PrevAliasTemplate);
1065 
1066  Inst->setAccess(D->getAccess());
1067 
1068  if (!PrevAliasTemplate)
1070 
1071  Owner->addDecl(Inst);
1072 
1073  return Inst;
1074 }
1075 
1076 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1077  auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1078  D->getIdentifier());
1079  NewBD->setReferenced(D->isReferenced());
1080  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1081  return NewBD;
1082 }
1083 
1084 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1085  // Transform the bindings first.
1086  SmallVector<BindingDecl*, 16> NewBindings;
1087  for (auto *OldBD : D->bindings())
1088  NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1089  ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1090 
1091  auto *NewDD = cast_or_null<DecompositionDecl>(
1092  VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1093 
1094  if (!NewDD || NewDD->isInvalidDecl())
1095  for (auto *NewBD : NewBindings)
1096  NewBD->setInvalidDecl();
1097 
1098  return NewDD;
1099 }
1100 
1102  return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1103 }
1104 
1106  bool InstantiatingVarTemplate,
1108 
1109  // Do substitution on the type of the declaration
1110  TypeSourceInfo *DI = SemaRef.SubstType(
1111  D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1112  D->getDeclName(), /*AllowDeducedTST*/true);
1113  if (!DI)
1114  return nullptr;
1115 
1116  if (DI->getType()->isFunctionType()) {
1117  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1118  << D->isStaticDataMember() << DI->getType();
1119  return nullptr;
1120  }
1121 
1122  DeclContext *DC = Owner;
1123  if (D->isLocalExternDecl())
1124  SemaRef.adjustContextForLocalExternDecl(DC);
1125 
1126  // Build the instantiated declaration.
1127  VarDecl *Var;
1128  if (Bindings)
1129  Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1130  D->getLocation(), DI->getType(), DI,
1131  D->getStorageClass(), *Bindings);
1132  else
1133  Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1134  D->getLocation(), D->getIdentifier(), DI->getType(),
1135  DI, D->getStorageClass());
1136 
1137  // In ARC, infer 'retaining' for variables of retainable type.
1138  if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1139  SemaRef.inferObjCARCLifetime(Var))
1140  Var->setInvalidDecl();
1141 
1142  if (SemaRef.getLangOpts().OpenCL)
1143  SemaRef.deduceOpenCLAddressSpace(Var);
1144 
1145  // Substitute the nested name specifier, if any.
1146  if (SubstQualifier(D, Var))
1147  return nullptr;
1148 
1149  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1150  StartingScope, InstantiatingVarTemplate);
1151  if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1152  QualType RT;
1153  if (auto *F = dyn_cast<FunctionDecl>(DC))
1154  RT = F->getReturnType();
1155  else if (isa<BlockDecl>(DC))
1156  RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1157  ->getReturnType();
1158  else
1159  llvm_unreachable("Unknown context type");
1160 
1161  // This is the last chance we have of checking copy elision eligibility
1162  // for functions in dependent contexts. The sema actions for building
1163  // the return statement during template instantiation will have no effect
1164  // regarding copy elision, since NRVO propagation runs on the scope exit
1165  // actions, and these are not run on instantiation.
1166  // This might run through some VarDecls which were returned from non-taken
1167  // 'if constexpr' branches, and these will end up being constructed on the
1168  // return slot even if they will never be returned, as a sort of accidental
1169  // 'optimization'. Notably, functions with 'auto' return types won't have it
1170  // deduced by this point. Coupled with the limitation described
1171  // previously, this makes it very hard to support copy elision for these.
1172  Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1173  bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1174  Var->setNRVOVariable(NRVO);
1175  }
1176 
1177  Var->setImplicit(D->isImplicit());
1178 
1179  if (Var->isStaticLocal())
1180  SemaRef.CheckStaticLocalForDllExport(Var);
1181 
1182  if (Var->getTLSKind())
1183  SemaRef.CheckThreadLocalForLargeAlignment(Var);
1184 
1185  return Var;
1186 }
1187 
1188 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1189  AccessSpecDecl* AD
1190  = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1191  D->getAccessSpecifierLoc(), D->getColonLoc());
1192  Owner->addHiddenDecl(AD);
1193  return AD;
1194 }
1195 
1196 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1197  bool Invalid = false;
1198  TypeSourceInfo *DI = D->getTypeSourceInfo();
1199  if (DI->getType()->isInstantiationDependentType() ||
1200  DI->getType()->isVariablyModifiedType()) {
1201  DI = SemaRef.SubstType(DI, TemplateArgs,
1202  D->getLocation(), D->getDeclName());
1203  if (!DI) {
1204  DI = D->getTypeSourceInfo();
1205  Invalid = true;
1206  } else if (DI->getType()->isFunctionType()) {
1207  // C++ [temp.arg.type]p3:
1208  // If a declaration acquires a function type through a type
1209  // dependent on a template-parameter and this causes a
1210  // declaration that does not use the syntactic form of a
1211  // function declarator to have function type, the program is
1212  // ill-formed.
1213  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1214  << DI->getType();
1215  Invalid = true;
1216  }
1217  } else {
1219  }
1220 
1221  Expr *BitWidth = D->getBitWidth();
1222  if (Invalid)
1223  BitWidth = nullptr;
1224  else if (BitWidth) {
1225  // The bit-width expression is a constant expression.
1228 
1229  ExprResult InstantiatedBitWidth
1230  = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1231  if (InstantiatedBitWidth.isInvalid()) {
1232  Invalid = true;
1233  BitWidth = nullptr;
1234  } else
1235  BitWidth = InstantiatedBitWidth.getAs<Expr>();
1236  }
1237 
1238  FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1239  DI->getType(), DI,
1240  cast<RecordDecl>(Owner),
1241  D->getLocation(),
1242  D->isMutable(),
1243  BitWidth,
1244  D->getInClassInitStyle(),
1245  D->getInnerLocStart(),
1246  D->getAccess(),
1247  nullptr);
1248  if (!Field) {
1249  cast<Decl>(Owner)->setInvalidDecl();
1250  return nullptr;
1251  }
1252 
1253  SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1254 
1255  if (Field->hasAttrs())
1256  SemaRef.CheckAlignasUnderalignment(Field);
1257 
1258  if (Invalid)
1259  Field->setInvalidDecl();
1260 
1261  if (!Field->getDeclName()) {
1262  // Keep track of where this decl came from.
1263  SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1264  }
1265  if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1266  if (Parent->isAnonymousStructOrUnion() &&
1267  Parent->getRedeclContext()->isFunctionOrMethod())
1268  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1269  }
1270 
1271  Field->setImplicit(D->isImplicit());
1272  Field->setAccess(D->getAccess());
1273  Owner->addDecl(Field);
1274 
1275  return Field;
1276 }
1277 
1278 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1279  bool Invalid = false;
1280  TypeSourceInfo *DI = D->getTypeSourceInfo();
1281 
1282  if (DI->getType()->isVariablyModifiedType()) {
1283  SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1284  << D;
1285  Invalid = true;
1286  } else if (DI->getType()->isInstantiationDependentType()) {
1287  DI = SemaRef.SubstType(DI, TemplateArgs,
1288  D->getLocation(), D->getDeclName());
1289  if (!DI) {
1290  DI = D->getTypeSourceInfo();
1291  Invalid = true;
1292  } else if (DI->getType()->isFunctionType()) {
1293  // C++ [temp.arg.type]p3:
1294  // If a declaration acquires a function type through a type
1295  // dependent on a template-parameter and this causes a
1296  // declaration that does not use the syntactic form of a
1297  // function declarator to have function type, the program is
1298  // ill-formed.
1299  SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1300  << DI->getType();
1301  Invalid = true;
1302  }
1303  } else {
1305  }
1306 
1308  SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1309  DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1310 
1311  SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1312  StartingScope);
1313 
1314  if (Invalid)
1315  Property->setInvalidDecl();
1316 
1317  Property->setAccess(D->getAccess());
1318  Owner->addDecl(Property);
1319 
1320  return Property;
1321 }
1322 
1323 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1324  NamedDecl **NamedChain =
1325  new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1326 
1327  int i = 0;
1328  for (auto *PI : D->chain()) {
1329  NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1330  TemplateArgs);
1331  if (!Next)
1332  return nullptr;
1333 
1334  NamedChain[i++] = Next;
1335  }
1336 
1337  QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1339  SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1340  {NamedChain, D->getChainingSize()});
1341 
1342  for (const auto *Attr : D->attrs())
1343  IndirectField->addAttr(Attr->clone(SemaRef.Context));
1344 
1345  IndirectField->setImplicit(D->isImplicit());
1346  IndirectField->setAccess(D->getAccess());
1347  Owner->addDecl(IndirectField);
1348  return IndirectField;
1349 }
1350 
1351 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1352  // Handle friend type expressions by simply substituting template
1353  // parameters into the pattern type and checking the result.
1354  if (TypeSourceInfo *Ty = D->getFriendType()) {
1355  TypeSourceInfo *InstTy;
1356  // If this is an unsupported friend, don't bother substituting template
1357  // arguments into it. The actual type referred to won't be used by any
1358  // parts of Clang, and may not be valid for instantiating. Just use the
1359  // same info for the instantiated friend.
1360  if (D->isUnsupportedFriend()) {
1361  InstTy = Ty;
1362  } else {
1363  InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1364  D->getLocation(), DeclarationName());
1365  }
1366  if (!InstTy)
1367  return nullptr;
1368 
1369  FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1370  D->getFriendLoc(), InstTy);
1371  if (!FD)
1372  return nullptr;
1373 
1374  FD->setAccess(AS_public);
1376  Owner->addDecl(FD);
1377  return FD;
1378  }
1379 
1380  NamedDecl *ND = D->getFriendDecl();
1381  assert(ND && "friend decl must be a decl or a type!");
1382 
1383  // All of the Visit implementations for the various potential friend
1384  // declarations have to be carefully written to work for friend
1385  // objects, with the most important detail being that the target
1386  // decl should almost certainly not be placed in Owner.
1387  Decl *NewND = Visit(ND);
1388  if (!NewND) return nullptr;
1389 
1390  FriendDecl *FD =
1391  FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1392  cast<NamedDecl>(NewND), D->getFriendLoc());
1393  FD->setAccess(AS_public);
1395  Owner->addDecl(FD);
1396  return FD;
1397 }
1398 
1399 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1400  Expr *AssertExpr = D->getAssertExpr();
1401 
1402  // The expression in a static assertion is a constant expression.
1405 
1406  ExprResult InstantiatedAssertExpr
1407  = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1408  if (InstantiatedAssertExpr.isInvalid())
1409  return nullptr;
1410 
1411  return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1412  InstantiatedAssertExpr.get(),
1413  D->getMessage(),
1414  D->getRParenLoc(),
1415  D->isFailed());
1416 }
1417 
1418 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1419  EnumDecl *PrevDecl = nullptr;
1420  if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1421  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1422  PatternPrev,
1423  TemplateArgs);
1424  if (!Prev) return nullptr;
1425  PrevDecl = cast<EnumDecl>(Prev);
1426  }
1427 
1428  EnumDecl *Enum =
1429  EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1430  D->getLocation(), D->getIdentifier(), PrevDecl,
1431  D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1432  if (D->isFixed()) {
1433  if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1434  // If we have type source information for the underlying type, it means it
1435  // has been explicitly set by the user. Perform substitution on it before
1436  // moving on.
1437  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1438  TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1439  DeclarationName());
1440  if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1441  Enum->setIntegerType(SemaRef.Context.IntTy);
1442  else
1443  Enum->setIntegerTypeSourceInfo(NewTI);
1444  } else {
1445  assert(!D->getIntegerType()->isDependentType()
1446  && "Dependent type without type source info");
1447  Enum->setIntegerType(D->getIntegerType());
1448  }
1449  }
1450 
1451  SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1452 
1453  Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1454  Enum->setAccess(D->getAccess());
1455  // Forward the mangling number from the template to the instantiated decl.
1456  SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1457  // See if the old tag was defined along with a declarator.
1458  // If it did, mark the new tag as being associated with that declarator.
1460  SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1461  // See if the old tag was defined along with a typedef.
1462  // If it did, mark the new tag as being associated with that typedef.
1464  SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1465  if (SubstQualifier(D, Enum)) return nullptr;
1466  Owner->addDecl(Enum);
1467 
1468  EnumDecl *Def = D->getDefinition();
1469  if (Def && Def != D) {
1470  // If this is an out-of-line definition of an enum member template, check
1471  // that the underlying types match in the instantiation of both
1472  // declarations.
1473  if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1474  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1475  QualType DefnUnderlying =
1476  SemaRef.SubstType(TI->getType(), TemplateArgs,
1477  UnderlyingLoc, DeclarationName());
1478  SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1479  DefnUnderlying, /*IsFixed=*/true, Enum);
1480  }
1481  }
1482 
1483  // C++11 [temp.inst]p1: The implicit instantiation of a class template
1484  // specialization causes the implicit instantiation of the declarations, but
1485  // not the definitions of scoped member enumerations.
1486  //
1487  // DR1484 clarifies that enumeration definitions inside of a template
1488  // declaration aren't considered entities that can be separately instantiated
1489  // from the rest of the entity they are declared inside of.
1490  if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1491  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1492  InstantiateEnumDefinition(Enum, Def);
1493  }
1494 
1495  return Enum;
1496 }
1497 
1499  EnumDecl *Enum, EnumDecl *Pattern) {
1500  Enum->startDefinition();
1501 
1502  // Update the location to refer to the definition.
1503  Enum->setLocation(Pattern->getLocation());
1504 
1505  SmallVector<Decl*, 4> Enumerators;
1506 
1507  EnumConstantDecl *LastEnumConst = nullptr;
1508  for (auto *EC : Pattern->enumerators()) {
1509  // The specified value for the enumerator.
1510  ExprResult Value((Expr *)nullptr);
1511  if (Expr *UninstValue = EC->getInitExpr()) {
1512  // The enumerator's value expression is a constant expression.
1515 
1516  Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1517  }
1518 
1519  // Drop the initial value and continue.
1520  bool isInvalid = false;
1521  if (Value.isInvalid()) {
1522  Value = nullptr;
1523  isInvalid = true;
1524  }
1525 
1526  EnumConstantDecl *EnumConst
1527  = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1528  EC->getLocation(), EC->getIdentifier(),
1529  Value.get());
1530 
1531  if (isInvalid) {
1532  if (EnumConst)
1533  EnumConst->setInvalidDecl();
1534  Enum->setInvalidDecl();
1535  }
1536 
1537  if (EnumConst) {
1538  SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1539 
1540  EnumConst->setAccess(Enum->getAccess());
1541  Enum->addDecl(EnumConst);
1542  Enumerators.push_back(EnumConst);
1543  LastEnumConst = EnumConst;
1544 
1545  if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1546  !Enum->isScoped()) {
1547  // If the enumeration is within a function or method, record the enum
1548  // constant as a local.
1549  SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1550  }
1551  }
1552  }
1553 
1554  SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1555  Enumerators, nullptr, ParsedAttributesView());
1556 }
1557 
1558 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1559  llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
1560 }
1561 
1562 Decl *
1563 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1564  llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.");
1565 }
1566 
1567 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1568  bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1569 
1570  // Create a local instantiation scope for this class template, which
1571  // will contain the instantiations of the template parameters.
1572  LocalInstantiationScope Scope(SemaRef);
1573  TemplateParameterList *TempParams = D->getTemplateParameters();
1574  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1575  if (!InstParams)
1576  return nullptr;
1577 
1578  CXXRecordDecl *Pattern = D->getTemplatedDecl();
1579 
1580  // Instantiate the qualifier. We have to do this first in case
1581  // we're a friend declaration, because if we are then we need to put
1582  // the new declaration in the appropriate context.
1583  NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1584  if (QualifierLoc) {
1585  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1586  TemplateArgs);
1587  if (!QualifierLoc)
1588  return nullptr;
1589  }
1590 
1591  CXXRecordDecl *PrevDecl = nullptr;
1592  ClassTemplateDecl *PrevClassTemplate = nullptr;
1593 
1594  if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1595  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1596  if (!Found.empty()) {
1597  PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1598  if (PrevClassTemplate)
1599  PrevDecl = PrevClassTemplate->getTemplatedDecl();
1600  }
1601  }
1602 
1603  // If this isn't a friend, then it's a member template, in which
1604  // case we just want to build the instantiation in the
1605  // specialization. If it is a friend, we want to build it in
1606  // the appropriate context.
1607  DeclContext *DC = Owner;
1608  if (isFriend) {
1609  if (QualifierLoc) {
1610  CXXScopeSpec SS;
1611  SS.Adopt(QualifierLoc);
1612  DC = SemaRef.computeDeclContext(SS);
1613  if (!DC) return nullptr;
1614  } else {
1615  DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1616  Pattern->getDeclContext(),
1617  TemplateArgs);
1618  }
1619 
1620  // Look for a previous declaration of the template in the owning
1621  // context.
1622  LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1624  SemaRef.forRedeclarationInCurContext());
1625  SemaRef.LookupQualifiedName(R, DC);
1626 
1627  if (R.isSingleResult()) {
1628  PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1629  if (PrevClassTemplate)
1630  PrevDecl = PrevClassTemplate->getTemplatedDecl();
1631  }
1632 
1633  if (!PrevClassTemplate && QualifierLoc) {
1634  SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1635  << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1636  << QualifierLoc.getSourceRange();
1637  return nullptr;
1638  }
1639 
1640  if (PrevClassTemplate) {
1641  const ClassTemplateDecl *MostRecentPrevCT =
1642  PrevClassTemplate->getMostRecentDecl();
1643  TemplateParameterList *PrevParams =
1644  MostRecentPrevCT->getTemplateParameters();
1645 
1646  // Make sure the parameter lists match.
1647  if (!SemaRef.TemplateParameterListsAreEqual(
1648  D->getTemplatedDecl(), InstParams,
1649  MostRecentPrevCT->getTemplatedDecl(), PrevParams, true,
1651  return nullptr;
1652 
1653  // Do some additional validation, then merge default arguments
1654  // from the existing declarations.
1655  if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1657  return nullptr;
1658  }
1659  }
1660 
1661  CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1662  SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1663  Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1664  /*DelayTypeCreation=*/true);
1665 
1666  if (QualifierLoc)
1667  RecordInst->setQualifierInfo(QualifierLoc);
1668 
1669  SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1670  StartingScope);
1671 
1672  ClassTemplateDecl *Inst
1673  = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1674  D->getIdentifier(), InstParams, RecordInst);
1675  assert(!(isFriend && Owner->isDependentContext()));
1676  Inst->setPreviousDecl(PrevClassTemplate);
1677 
1678  RecordInst->setDescribedClassTemplate(Inst);
1679 
1680  if (isFriend) {
1681  if (PrevClassTemplate)
1682  Inst->setAccess(PrevClassTemplate->getAccess());
1683  else
1684  Inst->setAccess(D->getAccess());
1685 
1686  Inst->setObjectOfFriendDecl();
1687  // TODO: do we want to track the instantiation progeny of this
1688  // friend target decl?
1689  } else {
1690  Inst->setAccess(D->getAccess());
1691  if (!PrevClassTemplate)
1693  }
1694 
1695  // Trigger creation of the type for the instantiation.
1696  SemaRef.Context.getInjectedClassNameType(RecordInst,
1698 
1699  // Finish handling of friends.
1700  if (isFriend) {
1701  DC->makeDeclVisibleInContext(Inst);
1702  Inst->setLexicalDeclContext(Owner);
1703  RecordInst->setLexicalDeclContext(Owner);
1704  return Inst;
1705  }
1706 
1707  if (D->isOutOfLine()) {
1709  RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1710  }
1711 
1712  Owner->addDecl(Inst);
1713 
1714  if (!PrevClassTemplate) {
1715  // Queue up any out-of-line partial specializations of this member
1716  // class template; the client will force their instantiation once
1717  // the enclosing class has been instantiated.
1719  D->getPartialSpecializations(PartialSpecs);
1720  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1721  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1722  OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1723  }
1724 
1725  return Inst;
1726 }
1727 
1728 Decl *
1729 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1731  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1732 
1733  // Lookup the already-instantiated declaration in the instantiation
1734  // of the class template and return that.
1736  = Owner->lookup(ClassTemplate->getDeclName());
1737  if (Found.empty())
1738  return nullptr;
1739 
1740  ClassTemplateDecl *InstClassTemplate
1741  = dyn_cast<ClassTemplateDecl>(Found.front());
1742  if (!InstClassTemplate)
1743  return nullptr;
1744 
1746  = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1747  return Result;
1748 
1749  return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1750 }
1751 
1752 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1753  assert(D->getTemplatedDecl()->isStaticDataMember() &&
1754  "Only static data member templates are allowed.");
1755 
1756  // Create a local instantiation scope for this variable template, which
1757  // will contain the instantiations of the template parameters.
1758  LocalInstantiationScope Scope(SemaRef);
1759  TemplateParameterList *TempParams = D->getTemplateParameters();
1760  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1761  if (!InstParams)
1762  return nullptr;
1763 
1764  VarDecl *Pattern = D->getTemplatedDecl();
1765  VarTemplateDecl *PrevVarTemplate = nullptr;
1766 
1767  if (getPreviousDeclForInstantiation(Pattern)) {
1768  DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1769  if (!Found.empty())
1770  PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1771  }
1772 
1773  VarDecl *VarInst =
1774  cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1775  /*InstantiatingVarTemplate=*/true));
1776  if (!VarInst) return nullptr;
1777 
1778  DeclContext *DC = Owner;
1779 
1781  SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1782  VarInst);
1783  VarInst->setDescribedVarTemplate(Inst);
1784  Inst->setPreviousDecl(PrevVarTemplate);
1785 
1786  Inst->setAccess(D->getAccess());
1787  if (!PrevVarTemplate)
1789 
1790  if (D->isOutOfLine()) {
1793  }
1794 
1795  Owner->addDecl(Inst);
1796 
1797  if (!PrevVarTemplate) {
1798  // Queue up any out-of-line partial specializations of this member
1799  // variable template; the client will force their instantiation once
1800  // the enclosing class has been instantiated.
1802  D->getPartialSpecializations(PartialSpecs);
1803  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1804  if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1805  OutOfLineVarPartialSpecs.push_back(
1806  std::make_pair(Inst, PartialSpecs[I]));
1807  }
1808 
1809  return Inst;
1810 }
1811 
1812 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1814  assert(D->isStaticDataMember() &&
1815  "Only static data member templates are allowed.");
1816 
1817  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1818 
1819  // Lookup the already-instantiated declaration and return that.
1820  DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1821  assert(!Found.empty() && "Instantiation found nothing?");
1822 
1823  VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1824  assert(InstVarTemplate && "Instantiation did not find a variable template?");
1825 
1827  InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1828  return Result;
1829 
1830  return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1831 }
1832 
1833 Decl *
1834 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1835  // Create a local instantiation scope for this function template, which
1836  // will contain the instantiations of the template parameters and then get
1837  // merged with the local instantiation scope for the function template
1838  // itself.
1839  LocalInstantiationScope Scope(SemaRef);
1841 
1842  TemplateParameterList *TempParams = D->getTemplateParameters();
1843  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1844  if (!InstParams)
1845  return nullptr;
1846 
1847  FunctionDecl *Instantiated = nullptr;
1848  if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1849  Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1850  InstParams));
1851  else
1852  Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1853  D->getTemplatedDecl(),
1854  InstParams));
1855 
1856  if (!Instantiated)
1857  return nullptr;
1858 
1859  // Link the instantiated function template declaration to the function
1860  // template from which it was instantiated.
1861  FunctionTemplateDecl *InstTemplate
1862  = Instantiated->getDescribedFunctionTemplate();
1863  InstTemplate->setAccess(D->getAccess());
1864  assert(InstTemplate &&
1865  "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1866 
1867  bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1868 
1869  // Link the instantiation back to the pattern *unless* this is a
1870  // non-definition friend declaration.
1871  if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1872  !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1873  InstTemplate->setInstantiatedFromMemberTemplate(D);
1874 
1875  // Make declarations visible in the appropriate context.
1876  if (!isFriend) {
1877  Owner->addDecl(InstTemplate);
1878  } else if (InstTemplate->getDeclContext()->isRecord() &&
1880  SemaRef.CheckFriendAccess(InstTemplate);
1881  }
1882 
1883  return InstTemplate;
1884 }
1885 
1886 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1887  CXXRecordDecl *PrevDecl = nullptr;
1888  if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1889  NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1890  PatternPrev,
1891  TemplateArgs);
1892  if (!Prev) return nullptr;
1893  PrevDecl = cast<CXXRecordDecl>(Prev);
1894  }
1895 
1896  CXXRecordDecl *Record = nullptr;
1897  bool IsInjectedClassName = D->isInjectedClassName();
1898  if (D->isLambda())
1899  Record = CXXRecordDecl::CreateLambda(
1900  SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1903  else
1904  Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1905  D->getBeginLoc(), D->getLocation(),
1906  D->getIdentifier(), PrevDecl,
1907  /*DelayTypeCreation=*/IsInjectedClassName);
1908  // Link the type of the injected-class-name to that of the outer class.
1909  if (IsInjectedClassName)
1910  (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1911 
1912  // Substitute the nested name specifier, if any.
1913  if (SubstQualifier(D, Record))
1914  return nullptr;
1915 
1916  SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1917  StartingScope);
1918 
1919  Record->setImplicit(D->isImplicit());
1920  // FIXME: Check against AS_none is an ugly hack to work around the issue that
1921  // the tag decls introduced by friend class declarations don't have an access
1922  // specifier. Remove once this area of the code gets sorted out.
1923  if (D->getAccess() != AS_none)
1924  Record->setAccess(D->getAccess());
1925  if (!IsInjectedClassName)
1927 
1928  // If the original function was part of a friend declaration,
1929  // inherit its namespace state.
1930  if (D->getFriendObjectKind())
1931  Record->setObjectOfFriendDecl();
1932 
1933  // Make sure that anonymous structs and unions are recorded.
1934  if (D->isAnonymousStructOrUnion())
1935  Record->setAnonymousStructOrUnion(true);
1936 
1937  if (D->isLocalClass())
1938  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1939 
1940  // Forward the mangling number from the template to the instantiated decl.
1941  SemaRef.Context.setManglingNumber(Record,
1942  SemaRef.Context.getManglingNumber(D));
1943 
1944  // See if the old tag was defined along with a declarator.
1945  // If it did, mark the new tag as being associated with that declarator.
1947  SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1948 
1949  // See if the old tag was defined along with a typedef.
1950  // If it did, mark the new tag as being associated with that typedef.
1952  SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1953 
1954  Owner->addDecl(Record);
1955 
1956  // DR1484 clarifies that the members of a local class are instantiated as part
1957  // of the instantiation of their enclosing entity.
1958  if (D->isCompleteDefinition() && D->isLocalClass()) {
1959  Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1960 
1961  SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1963  /*Complain=*/true);
1964 
1965  // For nested local classes, we will instantiate the members when we
1966  // reach the end of the outermost (non-nested) local class.
1967  if (!D->isCXXClassMember())
1968  SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1970 
1971  // This class may have local implicit instantiations that need to be
1972  // performed within this scope.
1973  LocalInstantiations.perform();
1974  }
1975 
1976  SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1977 
1978  if (IsInjectedClassName)
1979  assert(Record->isInjectedClassName() && "Broken injected-class-name");
1980 
1981  return Record;
1982 }
1983 
1984 /// Adjust the given function type for an instantiation of the
1985 /// given declaration, to cope with modifications to the function's type that
1986 /// aren't reflected in the type-source information.
1987 ///
1988 /// \param D The declaration we're instantiating.
1989 /// \param TInfo The already-instantiated type.
1991  FunctionDecl *D,
1992  TypeSourceInfo *TInfo) {
1993  const FunctionProtoType *OrigFunc
1994  = D->getType()->castAs<FunctionProtoType>();
1995  const FunctionProtoType *NewFunc
1996  = TInfo->getType()->castAs<FunctionProtoType>();
1997  if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1998  return TInfo->getType();
1999 
2000  FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2001  NewEPI.ExtInfo = OrigFunc->getExtInfo();
2002  return Context.getFunctionType(NewFunc->getReturnType(),
2003  NewFunc->getParamTypes(), NewEPI);
2004 }
2005 
2006 /// Normal class members are of more specific types and therefore
2007 /// don't make it here. This function serves three purposes:
2008 /// 1) instantiating function templates
2009 /// 2) substituting friend and local function declarations
2010 /// 3) substituting deduction guide declarations for nested class templates
2012  FunctionDecl *D, TemplateParameterList *TemplateParams,
2013  RewriteKind FunctionRewriteKind) {
2014  // Check whether there is already a function template specialization for
2015  // this declaration.
2016  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2017  if (FunctionTemplate && !TemplateParams) {
2018  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2019 
2020  void *InsertPos = nullptr;
2021  FunctionDecl *SpecFunc
2022  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2023 
2024  // If we already have a function template specialization, return it.
2025  if (SpecFunc)
2026  return SpecFunc;
2027  }
2028 
2029  bool isFriend;
2030  if (FunctionTemplate)
2031  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2032  else
2033  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2034 
2035  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2036  Owner->isFunctionOrMethod() ||
2037  !(isa<Decl>(Owner) &&
2038  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2039  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2040 
2041  ExplicitSpecifier InstantiatedExplicitSpecifier;
2042  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2043  InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
2044  SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
2045  if (InstantiatedExplicitSpecifier.isInvalid())
2046  return nullptr;
2047  }
2048 
2050  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2051  if (!TInfo)
2052  return nullptr;
2053  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2054 
2055  if (TemplateParams && TemplateParams->size()) {
2056  auto *LastParam =
2057  dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2058  if (LastParam && LastParam->isImplicit() &&
2059  LastParam->hasTypeConstraint()) {
2060  // In abbreviated templates, the type-constraints of invented template
2061  // type parameters are instantiated with the function type, invalidating
2062  // the TemplateParameterList which relied on the template type parameter
2063  // not having a type constraint. Recreate the TemplateParameterList with
2064  // the updated parameter list.
2065  TemplateParams = TemplateParameterList::Create(
2066  SemaRef.Context, TemplateParams->getTemplateLoc(),
2067  TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2068  TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2069  }
2070  }
2071 
2072  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2073  if (QualifierLoc) {
2074  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2075  TemplateArgs);
2076  if (!QualifierLoc)
2077  return nullptr;
2078  }
2079 
2080  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2081 
2082  // If we're instantiating a local function declaration, put the result
2083  // in the enclosing namespace; otherwise we need to find the instantiated
2084  // context.
2085  DeclContext *DC;
2086  if (D->isLocalExternDecl()) {
2087  DC = Owner;
2088  SemaRef.adjustContextForLocalExternDecl(DC);
2089  } else if (isFriend && QualifierLoc) {
2090  CXXScopeSpec SS;
2091  SS.Adopt(QualifierLoc);
2092  DC = SemaRef.computeDeclContext(SS);
2093  if (!DC) return nullptr;
2094  } else {
2095  DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2096  TemplateArgs);
2097  }
2098 
2099  DeclarationNameInfo NameInfo
2100  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2101 
2102  if (FunctionRewriteKind != RewriteKind::None)
2103  adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2104 
2105  FunctionDecl *Function;
2106  if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2107  Function = CXXDeductionGuideDecl::Create(
2108  SemaRef.Context, DC, D->getInnerLocStart(),
2109  InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2110  D->getSourceRange().getEnd());
2111  if (DGuide->isCopyDeductionCandidate())
2112  cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2113  Function->setAccess(D->getAccess());
2114  } else {
2115  Function = FunctionDecl::Create(
2116  SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2119  TrailingRequiresClause);
2120  Function->setFriendConstraintRefersToEnclosingTemplate(
2122  Function->setRangeEnd(D->getSourceRange().getEnd());
2123  }
2124 
2125  if (D->isInlined())
2126  Function->setImplicitlyInline();
2127 
2128  if (QualifierLoc)
2129  Function->setQualifierInfo(QualifierLoc);
2130 
2131  if (D->isLocalExternDecl())
2132  Function->setLocalExternDecl();
2133 
2134  DeclContext *LexicalDC = Owner;
2135  if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2136  assert(D->getDeclContext()->isFileContext());
2137  LexicalDC = D->getDeclContext();
2138  }
2139  else if (D->isLocalExternDecl()) {
2140  LexicalDC = SemaRef.CurContext;
2141  }
2142 
2143  Function->setLexicalDeclContext(LexicalDC);
2144 
2145  // Attach the parameters
2146  for (unsigned P = 0; P < Params.size(); ++P)
2147  if (Params[P])
2148  Params[P]->setOwningFunction(Function);
2149  Function->setParams(Params);
2150 
2151  if (TrailingRequiresClause)
2152  Function->setTrailingRequiresClause(TrailingRequiresClause);
2153 
2154  if (TemplateParams) {
2155  // Our resulting instantiation is actually a function template, since we
2156  // are substituting only the outer template parameters. For example, given
2157  //
2158  // template<typename T>
2159  // struct X {
2160  // template<typename U> friend void f(T, U);
2161  // };
2162  //
2163  // X<int> x;
2164  //
2165  // We are instantiating the friend function template "f" within X<int>,
2166  // which means substituting int for T, but leaving "f" as a friend function
2167  // template.
2168  // Build the function template itself.
2169  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2170  Function->getLocation(),
2171  Function->getDeclName(),
2172  TemplateParams, Function);
2173  Function->setDescribedFunctionTemplate(FunctionTemplate);
2174 
2175  FunctionTemplate->setLexicalDeclContext(LexicalDC);
2176 
2177  if (isFriend && D->isThisDeclarationADefinition()) {
2178  FunctionTemplate->setInstantiatedFromMemberTemplate(
2180  }
2181  } else if (FunctionTemplate) {
2182  // Record this function template specialization.
2183  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2184  Function->setFunctionTemplateSpecialization(FunctionTemplate,
2186  Innermost),
2187  /*InsertPos=*/nullptr);
2188  } else if (isFriend && D->isThisDeclarationADefinition()) {
2189  // Do not connect the friend to the template unless it's actually a
2190  // definition. We don't want non-template functions to be marked as being
2191  // template instantiations.
2192  Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2193  } else if (!isFriend) {
2194  // If this is not a function template, and this is not a friend (that is,
2195  // this is a locally declared function), save the instantiation relationship
2196  // for the purposes of constraint instantiation.
2197  Function->setInstantiatedFromDecl(D);
2198  }
2199 
2200  if (isFriend) {
2201  Function->setObjectOfFriendDecl();
2202  if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2203  FT->setObjectOfFriendDecl();
2204  }
2205 
2206  if (InitFunctionInstantiation(Function, D))
2207  Function->setInvalidDecl();
2208 
2209  bool IsExplicitSpecialization = false;
2210 
2212  SemaRef, Function->getDeclName(), SourceLocation(),
2216  : SemaRef.forRedeclarationInCurContext());
2217 
2220  assert(isFriend && "non-friend has dependent specialization info?");
2221 
2222  // Instantiate the explicit template arguments.
2223  TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2224  Info->getRAngleLoc());
2225  if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2226  ExplicitArgs))
2227  return nullptr;
2228 
2229  // Map the candidate templates to their instantiations.
2230  for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2231  Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2232  Info->getTemplate(I),
2233  TemplateArgs);
2234  if (!Temp) return nullptr;
2235 
2236  Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2237  }
2238 
2239  if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2240  &ExplicitArgs,
2241  Previous))
2242  Function->setInvalidDecl();
2243 
2244  IsExplicitSpecialization = true;
2245  } else if (const ASTTemplateArgumentListInfo *Info =
2247  // The name of this function was written as a template-id.
2248  SemaRef.LookupQualifiedName(Previous, DC);
2249 
2250  // Instantiate the explicit template arguments.
2251  TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2252  Info->getRAngleLoc());
2253  if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2254  ExplicitArgs))
2255  return nullptr;
2256 
2257  if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2258  &ExplicitArgs,
2259  Previous))
2260  Function->setInvalidDecl();
2261 
2262  IsExplicitSpecialization = true;
2263  } else if (TemplateParams || !FunctionTemplate) {
2264  // Look only into the namespace where the friend would be declared to
2265  // find a previous declaration. This is the innermost enclosing namespace,
2266  // as described in ActOnFriendFunctionDecl.
2268 
2269  // In C++, the previous declaration we find might be a tag type
2270  // (class or enum). In this case, the new declaration will hide the
2271  // tag type. Note that this does not apply if we're declaring a
2272  // typedef (C++ [dcl.typedef]p4).
2273  if (Previous.isSingleTagDecl())
2274  Previous.clear();
2275 
2276  // Filter out previous declarations that don't match the scope. The only
2277  // effect this has is to remove declarations found in inline namespaces
2278  // for friend declarations with unqualified names.
2279  if (isFriend && !QualifierLoc && !FunctionTemplate) {
2280  SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2281  /*ConsiderLinkage=*/ true,
2282  QualifierLoc.hasQualifier());
2283  }
2284  }
2285 
2286  // Per [temp.inst], default arguments in function declarations at local scope
2287  // are instantiated along with the enclosing declaration. For example:
2288  //
2289  // template<typename T>
2290  // void ft() {
2291  // void f(int = []{ return T::value; }());
2292  // }
2293  // template void ft<int>(); // error: type 'int' cannot be used prior
2294  // to '::' because it has no members
2295  //
2296  // The error is issued during instantiation of ft<int>() because substitution
2297  // into the default argument fails; the default argument is instantiated even
2298  // though it is never used.
2299  if (Function->isLocalExternDecl()) {
2300  for (ParmVarDecl *PVD : Function->parameters()) {
2301  if (!PVD->hasDefaultArg())
2302  continue;
2303  if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2304  // If substitution fails, the default argument is set to a
2305  // RecoveryExpr that wraps the uninstantiated default argument so
2306  // that downstream diagnostics are omitted.
2307  Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2308  ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2309  UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2310  { UninstExpr }, UninstExpr->getType());
2311  if (ErrorResult.isUsable())
2312  PVD->setDefaultArg(ErrorResult.get());
2313  }
2314  }
2315  }
2316 
2317  SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2318  IsExplicitSpecialization,
2319  Function->isThisDeclarationADefinition());
2320 
2321  // Check the template parameter list against the previous declaration. The
2322  // goal here is to pick up default arguments added since the friend was
2323  // declared; we know the template parameter lists match, since otherwise
2324  // we would not have picked this template as the previous declaration.
2325  if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2327  TemplateParams,
2328  FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2329  Function->isThisDeclarationADefinition()
2332  }
2333 
2334  // If we're introducing a friend definition after the first use, trigger
2335  // instantiation.
2336  // FIXME: If this is a friend function template definition, we should check
2337  // to see if any specializations have been used.
2338  if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2339  if (MemberSpecializationInfo *MSInfo =
2340  Function->getMemberSpecializationInfo()) {
2341  if (MSInfo->getPointOfInstantiation().isInvalid()) {
2342  SourceLocation Loc = D->getLocation(); // FIXME
2343  MSInfo->setPointOfInstantiation(Loc);
2344  SemaRef.PendingLocalImplicitInstantiations.push_back(
2345  std::make_pair(Function, Loc));
2346  }
2347  }
2348  }
2349 
2350  if (D->isExplicitlyDefaulted()) {
2351  if (SubstDefaultedFunction(Function, D))
2352  return nullptr;
2353  }
2354  if (D->isDeleted())
2355  SemaRef.SetDeclDeleted(Function, D->getLocation());
2356 
2357  NamedDecl *PrincipalDecl =
2358  (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2359 
2360  // If this declaration lives in a different context from its lexical context,
2361  // add it to the corresponding lookup table.
2362  if (isFriend ||
2363  (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2364  DC->makeDeclVisibleInContext(PrincipalDecl);
2365 
2366  if (Function->isOverloadedOperator() && !DC->isRecord() &&
2368  PrincipalDecl->setNonMemberOperator();
2369 
2370  return Function;
2371 }
2372 
2374  CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2375  Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs,
2376  RewriteKind FunctionRewriteKind) {
2377  FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2378  if (FunctionTemplate && !TemplateParams) {
2379  // We are creating a function template specialization from a function
2380  // template. Check whether there is already a function template
2381  // specialization for this particular set of template arguments.
2382  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2383 
2384  void *InsertPos = nullptr;
2385  FunctionDecl *SpecFunc
2386  = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2387 
2388  // If we already have a function template specialization, return it.
2389  if (SpecFunc)
2390  return SpecFunc;
2391  }
2392 
2393  bool isFriend;
2394  if (FunctionTemplate)
2395  isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2396  else
2397  isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2398 
2399  bool MergeWithParentScope = (TemplateParams != nullptr) ||
2400  !(isa<Decl>(Owner) &&
2401  cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2402  LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2403 
2404  // Instantiate enclosing template arguments for friends.
2406  unsigned NumTempParamLists = 0;
2407  if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2408  TempParamLists.resize(NumTempParamLists);
2409  for (unsigned I = 0; I != NumTempParamLists; ++I) {
2410  TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2411  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2412  if (!InstParams)
2413  return nullptr;
2414  TempParamLists[I] = InstParams;
2415  }
2416  }
2417 
2418  ExplicitSpecifier InstantiatedExplicitSpecifier =
2419  instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2421  if (InstantiatedExplicitSpecifier.isInvalid())
2422  return nullptr;
2423 
2424  // Implicit destructors/constructors created for local classes in
2425  // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2426  // Unfortunately there isn't enough context in those functions to
2427  // conditionally populate the TSI without breaking non-template related use
2428  // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2429  // a proper transformation.
2430  if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2431  !D->getTypeSourceInfo() &&
2432  isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2433  TypeSourceInfo *TSI =
2435  D->setTypeSourceInfo(TSI);
2436  }
2437 
2439  TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2440  if (!TInfo)
2441  return nullptr;
2442  QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2443 
2444  if (TemplateParams && TemplateParams->size()) {
2445  auto *LastParam =
2446  dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2447  if (LastParam && LastParam->isImplicit() &&
2448  LastParam->hasTypeConstraint()) {
2449  // In abbreviated templates, the type-constraints of invented template
2450  // type parameters are instantiated with the function type, invalidating
2451  // the TemplateParameterList which relied on the template type parameter
2452  // not having a type constraint. Recreate the TemplateParameterList with
2453  // the updated parameter list.
2454  TemplateParams = TemplateParameterList::Create(
2455  SemaRef.Context, TemplateParams->getTemplateLoc(),
2456  TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2457  TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2458  }
2459  }
2460 
2461  NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2462  if (QualifierLoc) {
2463  QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2464  TemplateArgs);
2465  if (!QualifierLoc)
2466  return nullptr;
2467  }
2468 
2469  DeclContext *DC = Owner;
2470  if (isFriend) {
2471  if (QualifierLoc) {
2472  CXXScopeSpec SS;
2473  SS.Adopt(QualifierLoc);
2474  DC = SemaRef.computeDeclContext(SS);
2475 
2476  if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2477  return nullptr;
2478  } else {
2479  DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2480  D->getDeclContext(),
2481  TemplateArgs);
2482  }
2483  if (!DC) return nullptr;
2484  }
2485 
2486  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2487  Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2488 
2489  DeclarationNameInfo NameInfo
2490  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2491 
2492  if (FunctionRewriteKind != RewriteKind::None)
2493  adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2494 
2495  // Build the instantiated method declaration.
2496  CXXMethodDecl *Method = nullptr;
2497 
2498  SourceLocation StartLoc = D->getInnerLocStart();
2499  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2500  Method = CXXConstructorDecl::Create(
2501  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2502  InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2503  Constructor->isInlineSpecified(), false,
2504  Constructor->getConstexprKind(), InheritedConstructor(),
2505  TrailingRequiresClause);
2506  Method->setRangeEnd(Constructor->getEndLoc());
2507  if (Constructor->isDefaultConstructor() ||
2508  Constructor->isCopyOrMoveConstructor())
2509  Method->setIneligibleOrNotSelected(true);
2510  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2511  Method = CXXDestructorDecl::Create(
2512  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2513  Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2514  Destructor->getConstexprKind(), TrailingRequiresClause);
2515  Method->setIneligibleOrNotSelected(true);
2516  Method->setRangeEnd(Destructor->getEndLoc());
2518  SemaRef.Context.getCanonicalType(
2519  SemaRef.Context.getTypeDeclType(Record))));
2520  } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2521  Method = CXXConversionDecl::Create(
2522  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2523  Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2524  InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2525  Conversion->getEndLoc(), TrailingRequiresClause);
2526  } else {
2527  StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2528  Method = CXXMethodDecl::Create(
2529  SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2531  D->getEndLoc(), TrailingRequiresClause);
2533  Method->setIneligibleOrNotSelected(true);
2534  }
2535 
2536  if (D->isInlined())
2537  Method->setImplicitlyInline();
2538 
2539  if (QualifierLoc)
2540  Method->setQualifierInfo(QualifierLoc);
2541 
2542  if (TemplateParams) {
2543  // Our resulting instantiation is actually a function template, since we
2544  // are substituting only the outer template parameters. For example, given
2545  //
2546  // template<typename T>
2547  // struct X {
2548  // template<typename U> void f(T, U);
2549  // };
2550  //
2551  // X<int> x;
2552  //
2553  // We are instantiating the member template "f" within X<int>, which means
2554  // substituting int for T, but leaving "f" as a member function template.
2555  // Build the function template itself.
2556  FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2557  Method->getLocation(),
2558  Method->getDeclName(),
2559  TemplateParams, Method);
2560  if (isFriend) {
2561  FunctionTemplate->setLexicalDeclContext(Owner);
2562  FunctionTemplate->setObjectOfFriendDecl();
2563  } else if (D->isOutOfLine())
2564  FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2565  Method->setDescribedFunctionTemplate(FunctionTemplate);
2566  } else if (FunctionTemplate) {
2567  // Record this function template specialization.
2568  ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2569  Method->setFunctionTemplateSpecialization(FunctionTemplate,
2571  Innermost),
2572  /*InsertPos=*/nullptr);
2573  } else if (!isFriend) {
2574  // Record that this is an instantiation of a member function.
2576  }
2577 
2578  // If we are instantiating a member function defined
2579  // out-of-line, the instantiation will have the same lexical
2580  // context (which will be a namespace scope) as the template.
2581  if (isFriend) {
2582  if (NumTempParamLists)
2584  SemaRef.Context,
2585  llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2586 
2587  Method->setLexicalDeclContext(Owner);
2588  Method->setObjectOfFriendDecl();
2589  } else if (D->isOutOfLine())
2591 
2592  // Attach the parameters
2593  for (unsigned P = 0; P < Params.size(); ++P)
2594  Params[P]->setOwningFunction(Method);
2595  Method->setParams(Params);
2596 
2597  if (InitMethodInstantiation(Method, D))
2598  Method->setInvalidDecl();
2599 
2600  LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2602 
2603  bool IsExplicitSpecialization = false;
2604 
2605  // If the name of this function was written as a template-id, instantiate
2606  // the explicit template arguments.
2609  assert(isFriend && "non-friend has dependent specialization info?");
2610 
2611  // Instantiate the explicit template arguments.
2612  TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2613  Info->getRAngleLoc());
2614  if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2615  ExplicitArgs))
2616  return nullptr;
2617 
2618  // Map the candidate templates to their instantiations.
2619  for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2620  Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2621  Info->getTemplate(I),
2622  TemplateArgs);
2623  if (!Temp) return nullptr;
2624 
2625  Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2626  }
2627 
2628  if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2629  &ExplicitArgs,
2630  Previous))
2631  Method->setInvalidDecl();
2632 
2633  IsExplicitSpecialization = true;
2634  } else if (const ASTTemplateArgumentListInfo *Info =
2635  ClassScopeSpecializationArgs.value_or(
2637  SemaRef.LookupQualifiedName(Previous, DC);
2638 
2639  TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2640  Info->getRAngleLoc());
2641  if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2642  ExplicitArgs))
2643  return nullptr;
2644 
2645  if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2646  &ExplicitArgs,
2647  Previous))
2648  Method->setInvalidDecl();
2649 
2650  IsExplicitSpecialization = true;
2651  } else if (ClassScopeSpecializationArgs) {
2652  // Class-scope explicit specialization written without explicit template
2653  // arguments.
2654  SemaRef.LookupQualifiedName(Previous, DC);
2655  if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2656  Method->setInvalidDecl();
2657 
2658  IsExplicitSpecialization = true;
2659  } else if (!FunctionTemplate || TemplateParams || isFriend) {
2660  SemaRef.LookupQualifiedName(Previous, Record);
2661 
2662  // In C++, the previous declaration we find might be a tag type
2663  // (class or enum). In this case, the new declaration will hide the
2664  // tag type. Note that this does not apply if we're declaring a
2665  // typedef (C++ [dcl.typedef]p4).
2666  if (Previous.isSingleTagDecl())
2667  Previous.clear();
2668  }
2669 
2670  // Per [temp.inst], default arguments in member functions of local classes
2671  // are instantiated along with the member function declaration. For example:
2672  //
2673  // template<typename T>
2674  // void ft() {
2675  // struct lc {
2676  // int operator()(int p = []{ return T::value; }());
2677  // };
2678  // }
2679  // template void ft<int>(); // error: type 'int' cannot be used prior
2680  // to '::'because it has no members
2681  //
2682  // The error is issued during instantiation of ft<int>()::lc::operator()
2683  // because substitution into the default argument fails; the default argument
2684  // is instantiated even though it is never used.
2685  if (D->isInLocalScopeForInstantiation()) {
2686  for (unsigned P = 0; P < Params.size(); ++P) {
2687  if (!Params[P]->hasDefaultArg())
2688  continue;
2689  if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2690  // If substitution fails, the default argument is set to a
2691  // RecoveryExpr that wraps the uninstantiated default argument so
2692  // that downstream diagnostics are omitted.
2693  Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2694  ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2695  UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2696  { UninstExpr }, UninstExpr->getType());
2697  if (ErrorResult.isUsable())
2698  Params[P]->setDefaultArg(ErrorResult.get());
2699  }
2700  }
2701  }
2702 
2703  SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2704  IsExplicitSpecialization,
2705  Method->isThisDeclarationADefinition());
2706 
2707  if (D->isPure())
2708  SemaRef.CheckPureMethod(Method, SourceRange());
2709 
2710  // Propagate access. For a non-friend declaration, the access is
2711  // whatever we're propagating from. For a friend, it should be the
2712  // previous declaration we just found.
2713  if (isFriend && Method->getPreviousDecl())
2714  Method->setAccess(Method->getPreviousDecl()->getAccess());
2715  else
2716  Method->setAccess(D->getAccess());
2717  if (FunctionTemplate)
2718  FunctionTemplate->setAccess(Method->getAccess());
2719 
2720  SemaRef.CheckOverrideControl(Method);
2721 
2722  // If a function is defined as defaulted or deleted, mark it as such now.
2723  if (D->isExplicitlyDefaulted()) {
2724  if (SubstDefaultedFunction(Method, D))
2725  return nullptr;
2726  }
2727  if (D->isDeletedAsWritten())
2728  SemaRef.SetDeclDeleted(Method, Method->getLocation());
2729 
2730  // If this is an explicit specialization, mark the implicitly-instantiated
2731  // template specialization as being an explicit specialization too.
2732  // FIXME: Is this necessary?
2733  if (IsExplicitSpecialization && !isFriend)
2734  SemaRef.CompleteMemberSpecialization(Method, Previous);
2735 
2736  // If there's a function template, let our caller handle it.
2737  if (FunctionTemplate) {
2738  // do nothing
2739 
2740  // Don't hide a (potentially) valid declaration with an invalid one.
2741  } else if (Method->isInvalidDecl() && !Previous.empty()) {
2742  // do nothing
2743 
2744  // Otherwise, check access to friends and make them visible.
2745  } else if (isFriend) {
2746  // We only need to re-check access for methods which we didn't
2747  // manage to match during parsing.
2748  if (!D->getPreviousDecl())
2749  SemaRef.CheckFriendAccess(Method);
2750 
2751  Record->makeDeclVisibleInContext(Method);
2752 
2753  // Otherwise, add the declaration. We don't need to do this for
2754  // class-scope specializations because we'll have matched them with
2755  // the appropriate template.
2756  } else {
2757  Owner->addDecl(Method);
2758  }
2759 
2760  // PR17480: Honor the used attribute to instantiate member function
2761  // definitions
2762  if (Method->hasAttr<UsedAttr>()) {
2763  if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2764  SourceLocation Loc;
2765  if (const MemberSpecializationInfo *MSInfo =
2766  A->getMemberSpecializationInfo())
2767  Loc = MSInfo->getPointOfInstantiation();
2768  else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2769  Loc = Spec->getPointOfInstantiation();
2770  SemaRef.MarkFunctionReferenced(Loc, Method);
2771  }
2772  }
2773 
2774  return Method;
2775 }
2776 
2777 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2778  return VisitCXXMethodDecl(D);
2779 }
2780 
2781 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2782  return VisitCXXMethodDecl(D);
2783 }
2784 
2785 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2786  return VisitCXXMethodDecl(D);
2787 }
2788 
2789 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2790  return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2791  /*ExpectParameterPack=*/ false);
2792 }
2793 
2794 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2795  TemplateTypeParmDecl *D) {
2796  assert(D->getTypeForDecl()->isTemplateTypeParmType());
2797 
2798  Optional<unsigned> NumExpanded;
2799 
2800  if (const TypeConstraint *TC = D->getTypeConstraint()) {
2801  if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2802  assert(TC->getTemplateArgsAsWritten() &&
2803  "type parameter can only be an expansion when explicit arguments "
2804  "are specified");
2805  // The template type parameter pack's type is a pack expansion of types.
2806  // Determine whether we need to expand this parameter pack into separate
2807  // types.
2809  for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2810  SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2811 
2812  // Determine whether the set of unexpanded parameter packs can and should
2813  // be expanded.
2814  bool Expand = true;
2815  bool RetainExpansion = false;
2816  if (SemaRef.CheckParameterPacksForExpansion(
2817  cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2818  ->getEllipsisLoc(),
2819  SourceRange(TC->getConceptNameLoc(),
2820  TC->hasExplicitTemplateArgs() ?
2821  TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2822  TC->getConceptNameInfo().getEndLoc()),
2823  Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2824  return nullptr;
2825  }
2826  }
2827 
2829  SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2830  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2832  D->hasTypeConstraint(), NumExpanded);
2833 
2834  Inst->setAccess(AS_public);
2835  Inst->setImplicit(D->isImplicit());
2836  if (auto *TC = D->getTypeConstraint()) {
2837  if (!D->isImplicit()) {
2838  // Invented template parameter type constraints will be instantiated
2839  // with the corresponding auto-typed parameter as it might reference
2840  // other parameters.
2841  if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2842  EvaluateConstraints))
2843  return nullptr;
2844  }
2845  }
2846  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2847  TypeSourceInfo *InstantiatedDefaultArg =
2848  SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2849  D->getDefaultArgumentLoc(), D->getDeclName());
2850  if (InstantiatedDefaultArg)
2851  Inst->setDefaultArgument(InstantiatedDefaultArg);
2852  }
2853 
2854  // Introduce this template parameter's instantiation into the instantiation
2855  // scope.
2856  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2857 
2858  return Inst;
2859 }
2860 
2861 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2863  // Substitute into the type of the non-type template parameter.
2864  TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2865  SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2866  SmallVector<QualType, 4> ExpandedParameterPackTypes;
2867  bool IsExpandedParameterPack = false;
2868  TypeSourceInfo *DI;
2869  QualType T;
2870  bool Invalid = false;
2871 
2872  if (D->isExpandedParameterPack()) {
2873  // The non-type template parameter pack is an already-expanded pack
2874  // expansion of types. Substitute into each of the expanded types.
2875  ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2876  ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2877  for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2878  TypeSourceInfo *NewDI =
2879  SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2880  D->getLocation(), D->getDeclName());
2881  if (!NewDI)
2882  return nullptr;
2883 
2884  QualType NewT =
2885  SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2886  if (NewT.isNull())
2887  return nullptr;
2888 
2889  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2890  ExpandedParameterPackTypes.push_back(NewT);
2891  }
2892 
2893  IsExpandedParameterPack = true;
2894  DI = D->getTypeSourceInfo();
2895  T = DI->getType();
2896  } else if (D->isPackExpansion()) {
2897  // The non-type template parameter pack's type is a pack expansion of types.
2898  // Determine whether we need to expand this parameter pack into separate
2899  // types.
2901  TypeLoc Pattern = Expansion.getPatternLoc();
2903  SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2904 
2905  // Determine whether the set of unexpanded parameter packs can and should
2906  // be expanded.
2907  bool Expand = true;
2908  bool RetainExpansion = false;
2909  Optional<unsigned> OrigNumExpansions
2910  = Expansion.getTypePtr()->getNumExpansions();
2911  Optional<unsigned> NumExpansions = OrigNumExpansions;
2912  if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2913  Pattern.getSourceRange(),
2914  Unexpanded,
2915  TemplateArgs,
2916  Expand, RetainExpansion,
2917  NumExpansions))
2918  return nullptr;
2919 
2920  if (Expand) {
2921  for (unsigned I = 0; I != *NumExpansions; ++I) {
2922  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2923  TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2924  D->getLocation(),
2925  D->getDeclName());
2926  if (!NewDI)
2927  return nullptr;
2928 
2929  QualType NewT =
2930  SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2931  if (NewT.isNull())
2932  return nullptr;
2933 
2934  ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2935  ExpandedParameterPackTypes.push_back(NewT);
2936  }
2937 
2938  // Note that we have an expanded parameter pack. The "type" of this
2939  // expanded parameter pack is the original expansion type, but callers
2940  // will end up using the expanded parameter pack types for type-checking.
2941  IsExpandedParameterPack = true;
2942  DI = D->getTypeSourceInfo();
2943  T = DI->getType();
2944  } else {
2945  // We cannot fully expand the pack expansion now, so substitute into the
2946  // pattern and create a new pack expansion type.
2947  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2948  TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2949  D->getLocation(),
2950  D->getDeclName());
2951  if (!NewPattern)
2952  return nullptr;
2953 
2954  SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2955  DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2956  NumExpansions);
2957  if (!DI)
2958  return nullptr;
2959 
2960  T = DI->getType();
2961  }
2962  } else {
2963  // Simple case: substitution into a parameter that is not a parameter pack.
2964  DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2965  D->getLocation(), D->getDeclName());
2966  if (!DI)
2967  return nullptr;
2968 
2969  // Check that this type is acceptable for a non-type template parameter.
2970  T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2971  if (T.isNull()) {
2972  T = SemaRef.Context.IntTy;
2973  Invalid = true;
2974  }
2975  }
2976 
2977  NonTypeTemplateParmDecl *Param;
2978  if (IsExpandedParameterPack)
2980  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2981  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2982  D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2983  ExpandedParameterPackTypesAsWritten);
2984  else
2986  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2987  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2988  D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2989 
2990  if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
2991  if (AutoLoc.isConstrained())
2992  if (SemaRef.AttachTypeConstraint(
2993  AutoLoc, Param,
2994  IsExpandedParameterPack
2996  .getEllipsisLoc()
2997  : SourceLocation()))
2998  Invalid = true;
2999 
3000  Param->setAccess(AS_public);
3001  Param->setImplicit(D->isImplicit());
3002  if (Invalid)
3003  Param->setInvalidDecl();
3004 
3005  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3006  EnterExpressionEvaluationContext ConstantEvaluated(
3008  ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
3009  if (!Value.isInvalid())
3010  Param->setDefaultArgument(Value.get());
3011  }
3012 
3013  // Introduce this template parameter's instantiation into the instantiation
3014  // scope.
3015  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3016  return Param;
3017 }
3018 
3020  Sema &S,
3021  TemplateParameterList *Params,
3023  for (const auto &P : *Params) {
3024  if (P->isTemplateParameterPack())
3025  continue;
3026  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3027  S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3028  Unexpanded);
3029  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3030  collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3031  Unexpanded);
3032  }
3033 }
3034 
3035 Decl *
3036 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3038  // Instantiate the template parameter list of the template template parameter.
3039  TemplateParameterList *TempParams = D->getTemplateParameters();
3040  TemplateParameterList *InstParams;
3042 
3043  bool IsExpandedParameterPack = false;
3044 
3045  if (D->isExpandedParameterPack()) {
3046  // The template template parameter pack is an already-expanded pack
3047  // expansion of template parameters. Substitute into each of the expanded
3048  // parameters.
3049  ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3050  for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3051  I != N; ++I) {
3052  LocalInstantiationScope Scope(SemaRef);
3053  TemplateParameterList *Expansion =
3055  if (!Expansion)
3056  return nullptr;
3057  ExpandedParams.push_back(Expansion);
3058  }
3059 
3060  IsExpandedParameterPack = true;
3061  InstParams = TempParams;
3062  } else if (D->isPackExpansion()) {
3063  // The template template parameter pack expands to a pack of template
3064  // template parameters. Determine whether we need to expand this parameter
3065  // pack into separate parameters.
3068  Unexpanded);
3069 
3070  // Determine whether the set of unexpanded parameter packs can and should
3071  // be expanded.
3072  bool Expand = true;
3073  bool RetainExpansion = false;
3074  Optional<unsigned> NumExpansions;
3076  TempParams->getSourceRange(),
3077  Unexpanded,
3078  TemplateArgs,
3079  Expand, RetainExpansion,
3080  NumExpansions))
3081  return nullptr;
3082 
3083  if (Expand) {
3084  for (unsigned I = 0; I != *NumExpansions; ++I) {
3085  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3086  LocalInstantiationScope Scope(SemaRef);
3087  TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3088  if (!Expansion)
3089  return nullptr;
3090  ExpandedParams.push_back(Expansion);
3091  }
3092 
3093  // Note that we have an expanded parameter pack. The "type" of this
3094  // expanded parameter pack is the original expansion type, but callers
3095  // will end up using the expanded parameter pack types for type-checking.
3096  IsExpandedParameterPack = true;
3097  InstParams = TempParams;
3098  } else {
3099  // We cannot fully expand the pack expansion now, so just substitute
3100  // into the pattern.
3101  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3102 
3103  LocalInstantiationScope Scope(SemaRef);
3104  InstParams = SubstTemplateParams(TempParams);
3105  if (!InstParams)
3106  return nullptr;
3107  }
3108  } else {
3109  // Perform the actual substitution of template parameters within a new,
3110  // local instantiation scope.
3111  LocalInstantiationScope Scope(SemaRef);
3112  InstParams = SubstTemplateParams(TempParams);
3113  if (!InstParams)
3114  return nullptr;
3115  }
3116 
3117  // Build the template template parameter.
3118  TemplateTemplateParmDecl *Param;
3119  if (IsExpandedParameterPack)
3121  SemaRef.Context, Owner, D->getLocation(),
3122  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3123  D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3124  else
3126  SemaRef.Context, Owner, D->getLocation(),
3127  D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3128  D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3129  if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3130  NestedNameSpecifierLoc QualifierLoc =
3132  QualifierLoc =
3133  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3134  TemplateName TName = SemaRef.SubstTemplateName(
3135  QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3136  D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3137  if (!TName.isNull())
3138  Param->setDefaultArgument(
3139  SemaRef.Context,
3143  }
3144  Param->setAccess(AS_public);
3145  Param->setImplicit(D->isImplicit());
3146 
3147  // Introduce this template parameter's instantiation into the instantiation
3148  // scope.
3149  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3150 
3151  return Param;
3152 }
3153 
3154 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3155  // Using directives are never dependent (and never contain any types or
3156  // expressions), so they require no explicit instantiation work.
3157 
3158  UsingDirectiveDecl *Inst
3159  = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3161  D->getQualifierLoc(),
3162  D->getIdentLocation(),
3163  D->getNominatedNamespace(),
3164  D->getCommonAncestor());
3165 
3166  // Add the using directive to its declaration context
3167  // only if this is not a function or method.
3168  if (!Owner->isFunctionOrMethod())
3169  Owner->addDecl(Inst);
3170 
3171  return Inst;
3172 }
3173 
3175  BaseUsingDecl *Inst,
3176  LookupResult *Lookup) {
3177 
3178  bool isFunctionScope = Owner->isFunctionOrMethod();
3179 
3180  for (auto *Shadow : D->shadows()) {
3181  // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3182  // reconstruct it in the case where it matters. Hm, can we extract it from
3183  // the DeclSpec when parsing and save it in the UsingDecl itself?
3184  NamedDecl *OldTarget = Shadow->getTargetDecl();
3185  if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3186  if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3187  OldTarget = BaseShadow;
3188 
3189  NamedDecl *InstTarget = nullptr;
3190  if (auto *EmptyD =
3191  dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3193  SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3194  } else {
3195  InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3196  Shadow->getLocation(), OldTarget, TemplateArgs));
3197  }
3198  if (!InstTarget)
3199  return nullptr;
3200 
3201  UsingShadowDecl *PrevDecl = nullptr;
3202  if (Lookup &&
3203  SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3204  continue;
3205 
3206  if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3207  PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3208  Shadow->getLocation(), OldPrev, TemplateArgs));
3209 
3210  UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3211  /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3212  SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3213 
3214  if (isFunctionScope)
3215  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3216  }
3217 
3218  return Inst;
3219 }
3220 
3221 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3222 
3223  // The nested name specifier may be dependent, for example
3224  // template <typename T> struct t {
3225  // struct s1 { T f1(); };
3226  // struct s2 : s1 { using s1::f1; };
3227  // };
3228  // template struct t<int>;
3229  // Here, in using s1::f1, s1 refers to t<T>::s1;
3230  // we need to substitute for t<int>::s1.
3231  NestedNameSpecifierLoc QualifierLoc
3233  TemplateArgs);
3234  if (!QualifierLoc)
3235  return nullptr;
3236 
3237  // For an inheriting constructor declaration, the name of the using
3238  // declaration is the name of a constructor in this class, not in the
3239  // base class.
3240  DeclarationNameInfo NameInfo = D->getNameInfo();
3242  if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3244  SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3245 
3246  // We only need to do redeclaration lookups if we're in a class scope (in
3247  // fact, it's not really even possible in non-class scopes).
3248  bool CheckRedeclaration = Owner->isRecord();
3249  LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3251 
3252  UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3253  D->getUsingLoc(),
3254  QualifierLoc,
3255  NameInfo,
3256  D->hasTypename());
3257 
3258  CXXScopeSpec SS;
3259  SS.Adopt(QualifierLoc);
3260  if (CheckRedeclaration) {
3261  Prev.setHideTags(false);
3262  SemaRef.LookupQualifiedName(Prev, Owner);
3263 
3264  // Check for invalid redeclarations.
3265  if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3266  D->hasTypename(), SS,
3267  D->getLocation(), Prev))
3268  NewUD->setInvalidDecl();
3269  }
3270 
3271  if (!NewUD->isInvalidDecl() &&
3272  SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3273  NameInfo, D->getLocation(), nullptr, D))
3274  NewUD->setInvalidDecl();
3275 
3276  SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3277  NewUD->setAccess(D->getAccess());
3278  Owner->addDecl(NewUD);
3279 
3280  // Don't process the shadow decls for an invalid decl.
3281  if (NewUD->isInvalidDecl())
3282  return NewUD;
3283 
3284  // If the using scope was dependent, or we had dependent bases, we need to
3285  // recheck the inheritance
3287  SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3288 
3289  return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3290 }
3291 
3292 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3293  // Cannot be a dependent type, but still could be an instantiation
3294  EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3295  D->getLocation(), D->getEnumDecl(), TemplateArgs));
3296 
3297  if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3298  return nullptr;
3299 
3300  TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3301  D->getLocation(), D->getDeclName());
3302  UsingEnumDecl *NewUD =
3303  UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3304  D->getEnumLoc(), D->getLocation(), TSI);
3305 
3306  SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3307  NewUD->setAccess(D->getAccess());
3308  Owner->addDecl(NewUD);
3309 
3310  // Don't process the shadow decls for an invalid decl.
3311  if (NewUD->isInvalidDecl())
3312  return NewUD;
3313 
3314  // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3315  // cannot be dependent, and will therefore have been checked during template
3316  // definition.
3317 
3318  return VisitBaseUsingDecls(D, NewUD, nullptr);
3319 }
3320 
3321 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3322  // Ignore these; we handle them in bulk when processing the UsingDecl.
3323  return nullptr;
3324 }
3325 
3326 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3328  // Ignore these; we handle them in bulk when processing the UsingDecl.
3329  return nullptr;
3330 }
3331 
3332 template <typename T>
3333 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3334  T *D, bool InstantiatingPackElement) {
3335  // If this is a pack expansion, expand it now.
3336  if (D->isPackExpansion() && !InstantiatingPackElement) {
3338  SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3339  SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3340 
3341  // Determine whether the set of unexpanded parameter packs can and should
3342  // be expanded.
3343  bool Expand = true;
3344  bool RetainExpansion = false;
3345  Optional<unsigned> NumExpansions;
3346  if (SemaRef.CheckParameterPacksForExpansion(
3347  D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3348  Expand, RetainExpansion, NumExpansions))
3349  return nullptr;
3350 
3351  // This declaration cannot appear within a function template signature,
3352  // so we can't have a partial argument list for a parameter pack.
3353  assert(!RetainExpansion &&
3354  "should never need to retain an expansion for UsingPackDecl");
3355 
3356  if (!Expand) {
3357  // We cannot fully expand the pack expansion now, so substitute into the
3358  // pattern and create a new pack expansion.
3359  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3360  return instantiateUnresolvedUsingDecl(D, true);
3361  }
3362 
3363  // Within a function, we don't have any normal way to check for conflicts
3364  // between shadow declarations from different using declarations in the
3365  // same pack expansion, but this is always ill-formed because all expansions
3366  // must produce (conflicting) enumerators.
3367  //
3368  // Sadly we can't just reject this in the template definition because it
3369  // could be valid if the pack is empty or has exactly one expansion.
3370  if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3371  SemaRef.Diag(D->getEllipsisLoc(),
3372  diag::err_using_decl_redeclaration_expansion);
3373  return nullptr;
3374  }
3375 
3376  // Instantiate the slices of this pack and build a UsingPackDecl.
3377  SmallVector<NamedDecl*, 8> Expansions;
3378  for (unsigned I = 0; I != *NumExpansions; ++I) {
3379  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3380  Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3381  if (!Slice)
3382  return nullptr;
3383  // Note that we can still get unresolved using declarations here, if we
3384  // had arguments for all packs but the pattern also contained other
3385  // template arguments (this only happens during partial substitution, eg
3386  // into the body of a generic lambda in a function template).
3387  Expansions.push_back(cast<NamedDecl>(Slice));
3388  }
3389 
3390  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3391  if (isDeclWithinFunction(D))
3392  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3393  return NewD;
3394  }
3395 
3396  UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3397  SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3398 
3399  NestedNameSpecifierLoc QualifierLoc
3400  = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3401  TemplateArgs);
3402  if (!QualifierLoc)
3403  return nullptr;
3404 
3405  CXXScopeSpec SS;
3406  SS.Adopt(QualifierLoc);
3407 
3408  DeclarationNameInfo NameInfo
3409  = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3410 
3411  // Produce a pack expansion only if we're not instantiating a particular
3412  // slice of a pack expansion.
3413  bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3414  SemaRef.ArgumentPackSubstitutionIndex != -1;
3415  SourceLocation EllipsisLoc =
3416  InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3417 
3418  bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3419  NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3420  /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3421  /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3423  /*IsInstantiation*/ true, IsUsingIfExists);
3424  if (UD) {
3425  SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3426  SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3427  }
3428 
3429  return UD;
3430 }
3431 
3432 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3434  return instantiateUnresolvedUsingDecl(D);
3435 }
3436 
3437 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3439  return instantiateUnresolvedUsingDecl(D);
3440 }
3441 
3442 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3444  llvm_unreachable("referring to unresolved decl out of UsingShadowDecl");
3445 }
3446 
3447 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3448  SmallVector<NamedDecl*, 8> Expansions;
3449  for (auto *UD : D->expansions()) {
3450  if (NamedDecl *NewUD =
3451  SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3452  Expansions.push_back(NewUD);
3453  else
3454  return nullptr;
3455  }
3456 
3457  auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3458  if (isDeclWithinFunction(D))
3459  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3460  return NewD;
3461 }
3462 
3463 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3465  CXXMethodDecl *OldFD = Decl->getSpecialization();
3466  return cast_or_null<CXXMethodDecl>(
3467  VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3468 }
3469 
3470 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3471  OMPThreadPrivateDecl *D) {
3473  for (auto *I : D->varlists()) {
3474  Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3475  assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
3476  Vars.push_back(Var);
3477  }
3478 
3479  OMPThreadPrivateDecl *TD =
3480  SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3481 
3482  TD->setAccess(AS_public);
3483  Owner->addDecl(TD);
3484 
3485  return TD;
3486 }
3487 
3488 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3490  for (auto *I : D->varlists()) {
3491  Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3492  assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr");
3493  Vars.push_back(Var);
3494  }
3496  // Copy map clauses from the original mapper.
3497  for (OMPClause *C : D->clauselists()) {
3498  OMPClause *IC = nullptr;
3499  if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3500  ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3501  if (!NewE.isUsable())
3502  continue;
3503  IC = SemaRef.ActOnOpenMPAllocatorClause(
3504  NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3505  } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3506  ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3507  if (!NewE.isUsable())
3508  continue;
3509  IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3510  AC->getLParenLoc(), AC->getEndLoc());
3511  // If align clause value ends up being invalid, this can end up null.
3512  if (!IC)
3513  continue;
3514  }
3515  Clauses.push_back(IC);
3516  }
3517 
3519  D->getLocation(), Vars, Clauses, Owner);
3520  if (Res.get().isNull())
3521  return nullptr;
3522  return Res.get().getSingleDecl();
3523 }
3524 
3525 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3526  llvm_unreachable(
3527  "Requires directive cannot be instantiated within a dependent context");
3528 }
3529 
3530 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3532  // Instantiate type and check if it is allowed.
3533  const bool RequiresInstantiation =
3534  D->getType()->isDependentType() ||
3537  QualType SubstReductionType;
3538  if (RequiresInstantiation) {
3539  SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3540  D->getLocation(),
3541  ParsedType::make(SemaRef.SubstType(
3542  D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3543  } else {
3544  SubstReductionType = D->getType();
3545  }
3546  if (SubstReductionType.isNull())
3547  return nullptr;
3548  Expr *Combiner = D->getCombiner();
3549  Expr *Init = D->getInitializer();
3550  bool IsCorrect = true;
3551  // Create instantiated copy.
3552  std::pair<QualType, SourceLocation> ReductionTypes[] = {
3553  std::make_pair(SubstReductionType, D->getLocation())};
3554  auto *PrevDeclInScope = D->getPrevDeclInScope();
3555  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3556  PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3557  SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3558  ->get<Decl *>());
3559  }
3560  auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3561  /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3562  PrevDeclInScope);
3563  auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3564  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3565  Expr *SubstCombiner = nullptr;
3566  Expr *SubstInitializer = nullptr;
3567  // Combiners instantiation sequence.
3568  if (Combiner) {
3570  /*S=*/nullptr, NewDRD);
3572  cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3573  cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3575  cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3576  cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3577  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3578  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3579  ThisContext);
3580  SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3581  SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3582  }
3583  // Initializers instantiation sequence.
3584  if (Init) {
3586  /*S=*/nullptr, NewDRD);
3588  cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3589  cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3591  cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3592  cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3594  SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3595  } else {
3596  auto *OldPrivParm =
3597  cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3598  IsCorrect = IsCorrect && OldPrivParm->hasInit();
3599  if (IsCorrect)
3600  SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3601  TemplateArgs);
3602  }
3603  SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3604  OmpPrivParm);
3605  }
3606  IsCorrect = IsCorrect && SubstCombiner &&
3607  (!Init ||
3609  SubstInitializer) ||
3611  !SubstInitializer));
3612 
3614  /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3615 
3616  return NewDRD;
3617 }
3618 
3619 Decl *
3620 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3621  // Instantiate type and check if it is allowed.
3622  const bool RequiresInstantiation =
3623  D->getType()->isDependentType() ||
3626  QualType SubstMapperTy;
3627  DeclarationName VN = D->getVarName();
3628  if (RequiresInstantiation) {
3629  SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3630  D->getLocation(),
3631  ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3632  D->getLocation(), VN)));
3633  } else {
3634  SubstMapperTy = D->getType();
3635  }
3636  if (SubstMapperTy.isNull())
3637  return nullptr;
3638  // Create an instantiated copy of mapper.
3639  auto *PrevDeclInScope = D->getPrevDeclInScope();
3640  if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3641  PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3642  SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3643  ->get<Decl *>());
3644  }
3645  bool IsCorrect = true;
3647  // Instantiate the mapper variable.
3648  DeclarationNameInfo DirName;
3649  SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3650  /*S=*/nullptr,
3651  (*D->clauselist_begin())->getBeginLoc());
3653  /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3655  cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3656  cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3657  auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3658  Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3659  ThisContext);
3660  // Instantiate map clauses.
3661  for (OMPClause *C : D->clauselists()) {
3662  auto *OldC = cast<OMPMapClause>(C);
3663  SmallVector<Expr *, 4> NewVars;
3664  for (Expr *OE : OldC->varlists()) {
3665  Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3666  if (!NE) {
3667  IsCorrect = false;
3668  break;
3669  }
3670  NewVars.push_back(NE);
3671  }
3672  if (!IsCorrect)
3673  break;
3674  NestedNameSpecifierLoc NewQualifierLoc =
3675  SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3676  TemplateArgs);
3677  CXXScopeSpec SS;
3678  SS.Adopt(NewQualifierLoc);
3679  DeclarationNameInfo NewNameInfo =
3680  SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3681  OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3682  OldC->getEndLoc());
3683  OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3684  OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS,
3685  NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(),
3686  OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs);
3687  Clauses.push_back(NewC);
3688  }
3689  SemaRef.EndOpenMPDSABlock(nullptr);
3690  if (!IsCorrect)
3691  return nullptr;
3693  /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3694  VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3695  Decl *NewDMD = DG.get().getSingleDecl();
3696  SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3697  return NewDMD;
3698 }
3699 
3700 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3701  OMPCapturedExprDecl * /*D*/) {
3702  llvm_unreachable("Should not be met in templates");
3703 }
3704 
3706  return VisitFunctionDecl(D, nullptr);
3707 }
3708 
3709 Decl *
3710 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3711  Decl *Inst = VisitFunctionDecl(D, nullptr);
3712  if (Inst && !D->getDescribedFunctionTemplate())
3713  Owner->addDecl(Inst);
3714  return Inst;
3715 }
3716 
3718  return VisitCXXMethodDecl(D, nullptr);
3719 }
3720 
3721 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3722  llvm_unreachable("There are only CXXRecordDecls in C++");
3723 }
3724 
3725 Decl *
3726 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3728  // As a MS extension, we permit class-scope explicit specialization
3729  // of member class templates.
3730  ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3731  assert(ClassTemplate->getDeclContext()->isRecord() &&
3733  "can only instantiate an explicit specialization "
3734  "for a member class template");
3735 
3736  // Lookup the already-instantiated declaration in the instantiation
3737  // of the class template.
3738  ClassTemplateDecl *InstClassTemplate =
3739  cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3740  D->getLocation(), ClassTemplate, TemplateArgs));
3741  if (!InstClassTemplate)
3742  return nullptr;
3743 
3744  // Substitute into the template arguments of the class template explicit
3745  // specialization.
3747  castAs<TemplateSpecializationTypeLoc>();
3748  TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3749  Loc.getRAngleLoc());
3751  for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3752  ArgLocs.push_back(Loc.getArgLoc(I));
3753  if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3754  return nullptr;
3755 
3756  // Check that the template argument list is well-formed for this
3757  // class template.
3758  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3759  if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3760  InstTemplateArgs, false,
3761  SugaredConverted, CanonicalConverted,
3762  /*UpdateArgsWithConversions=*/true))
3763  return nullptr;
3764 
3765  // Figure out where to insert this class template explicit specialization
3766  // in the member template's set of class template explicit specializations.
3767  void *InsertPos = nullptr;
3769  InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3770 
3771  // Check whether we've already seen a conflicting instantiation of this
3772  // declaration (for instance, if there was a prior implicit instantiation).
3773  bool Ignored;
3774  if (PrevDecl &&
3776  D->getSpecializationKind(),
3777  PrevDecl,
3778  PrevDecl->getSpecializationKind(),
3779  PrevDecl->getPointOfInstantiation(),
3780  Ignored))
3781  return nullptr;
3782 
3783  // If PrevDecl was a definition and D is also a definition, diagnose.
3784  // This happens in cases like:
3785  //
3786  // template<typename T, typename U>
3787  // struct Outer {
3788  // template<typename X> struct Inner;
3789  // template<> struct Inner<T> {};
3790  // template<> struct Inner<U> {};
3791  // };
3792  //
3793  // Outer<int, int> outer; // error: the explicit specializations of Inner
3794  // // have the same signature.
3795  if (PrevDecl && PrevDecl->getDefinition() &&
3797  SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3798  SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3799  diag::note_previous_definition);
3800  return nullptr;
3801  }
3802 
3803  // Create the class template partial specialization declaration.
3806  SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3807  D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3808 
3809  // Add this partial specialization to the set of class template partial
3810  // specializations.
3811  if (!PrevDecl)
3812  InstClassTemplate->AddSpecialization(InstD, InsertPos);
3813 
3814  // Substitute the nested name specifier, if any.
3815  if (SubstQualifier(D, InstD))
3816  return nullptr;
3817 
3818  // Build the canonical type that describes the converted template
3819  // arguments of the class template explicit specialization.
3820  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3821  TemplateName(InstClassTemplate), CanonicalConverted,
3822  SemaRef.Context.getRecordType(InstD));
3823 
3824  // Build the fully-sugared type for this class template
3825  // specialization as the user wrote in the specialization
3826  // itself. This means that we'll pretty-print the type retrieved
3827  // from the specialization's declaration the way that the user
3828  // actually wrote the specialization, rather than formatting the
3829  // name based on the "canonical" representation used to store the
3830  // template arguments in the specialization.
3832  TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3833  CanonType);
3834 
3835  InstD->setAccess(D->getAccess());
3838  InstD->setTypeAsWritten(WrittenTy);
3839  InstD->setExternLoc(D->getExternLoc());
3841 
3842  Owner->addDecl(InstD);
3843 
3844  // Instantiate the members of the class-scope explicit specialization eagerly.
3845  // We don't have support for lazy instantiation of an explicit specialization
3846  // yet, and MSVC eagerly instantiates in this case.
3847  // FIXME: This is wrong in standard C++.
3848  if (D->isThisDeclarationADefinition() &&
3849  SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3851  /*Complain=*/true))
3852  return nullptr;
3853 
3854  return InstD;
3855 }
3856 
3859 
3860  TemplateArgumentListInfo VarTemplateArgsInfo;
3861  VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3862  assert(VarTemplate &&
3863  "A template specialization without specialized template?");
3864 
3865  VarTemplateDecl *InstVarTemplate =
3866  cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3867  D->getLocation(), VarTemplate, TemplateArgs));
3868  if (!InstVarTemplate)
3869  return nullptr;
3870 
3871  // Substitute the current template arguments.
3872  if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3873  D->getTemplateArgsInfo()) {
3874  VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3875  VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3876 
3877  if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3878  TemplateArgs, VarTemplateArgsInfo))
3879  return nullptr;
3880  }
3881 
3882  // Check that the template argument list is well-formed for this template.
3883  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3884  if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3885  VarTemplateArgsInfo, false,
3886  SugaredConverted, CanonicalConverted,
3887  /*UpdateArgsWithConversions=*/true))
3888  return nullptr;
3889 
3890  // Check whether we've already seen a declaration of this specialization.
3891  void *InsertPos = nullptr;
3892  VarTemplateSpecializationDecl *PrevDecl =
3893  InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3894 
3895  // Check whether we've already seen a conflicting instantiation of this
3896  // declaration (for instance, if there was a prior implicit instantiation).
3897  bool Ignored;
3898  if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3899  D->getLocation(), D->getSpecializationKind(), PrevDecl,
3900  PrevDecl->getSpecializationKind(),
3901  PrevDecl->getPointOfInstantiation(), Ignored))
3902  return nullptr;
3903 
3905  InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
3906 }
3907 
3909  VarTemplateDecl *VarTemplate, VarDecl *D,
3910  const TemplateArgumentListInfo &TemplateArgsInfo,
3911  ArrayRef<TemplateArgument> Converted,
3912  VarTemplateSpecializationDecl *PrevDecl) {
3913 
3914  // Do substitution on the type of the declaration
3915  TypeSourceInfo *DI =
3916  SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3917  D->getTypeSpecStartLoc(), D->getDeclName());
3918  if (!DI)
3919  return nullptr;
3920 
3921  if (DI->getType()->isFunctionType()) {
3922  SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3923  << D->isStaticDataMember() << DI->getType();
3924  return nullptr;
3925  }
3926 
3927  // Build the instantiated declaration
3929  SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3930  VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3931  Var->setTemplateArgsInfo(TemplateArgsInfo);
3932  if (!PrevDecl) {
3933  void *InsertPos = nullptr;
3934  VarTemplate->findSpecialization(Converted, InsertPos);
3935  VarTemplate->AddSpecialization(Var, InsertPos);
3936  }
3937 
3938  if (SemaRef.getLangOpts().OpenCL)
3939  SemaRef.deduceOpenCLAddressSpace(Var);
3940 
3941  // Substitute the nested name specifier, if any.
3942  if (SubstQualifier(D, Var))
3943  return nullptr;
3944 
3945  SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3946  StartingScope, false, PrevDecl);
3947 
3948  return Var;
3949 }
3950 
3951 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3952  llvm_unreachable("@defs is not supported in Objective-C++");
3953 }
3954 
3955 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3956  // FIXME: We need to be able to instantiate FriendTemplateDecls.
3957  unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3959  "cannot instantiate %0 yet");
3960  SemaRef.Diag(D->getLocation(), DiagID)
3961  << D->getDeclKindName();
3962 
3963  return nullptr;
3964 }
3965 
3966 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3967  llvm_unreachable("Concept definitions cannot reside inside a template");
3968 }
3969 
3970 Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
3972  llvm_unreachable("Concept specializations cannot reside inside a template");
3973 }
3974 
3975 Decl *
3976 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
3978  D->getBeginLoc());
3979 }
3980 
3982  llvm_unreachable("Unexpected decl");
3983 }
3984 
3986  const MultiLevelTemplateArgumentList &TemplateArgs) {
3987  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3988  if (D->isInvalidDecl())
3989  return nullptr;
3990 
3991  Decl *SubstD;
3993  SubstD = Instantiator.Visit(D);
3994  });
3995  return SubstD;
3996 }
3997 
3999  FunctionDecl *Orig, QualType &T,
4000  TypeSourceInfo *&TInfo,
4001  DeclarationNameInfo &NameInfo) {
4003 
4004  // C++2a [class.compare.default]p3:
4005  // the return type is replaced with bool
4006  auto *FPT = T->castAs<FunctionProtoType>();
4007  T = SemaRef.Context.getFunctionType(
4008  SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4009 
4010  // Update the return type in the source info too. The most straightforward
4011  // way is to create new TypeSourceInfo for the new type. Use the location of
4012  // the '= default' as the location of the new type.
4013  //
4014  // FIXME: Set the correct return type when we initially transform the type,
4015  // rather than delaying it to now.
4016  TypeSourceInfo *NewTInfo =
4017  SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4018  auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4019  assert(OldLoc && "type of function is not a function type?");
4020  auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4021  for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4022  NewLoc.setParam(I, OldLoc.getParam(I));
4023  TInfo = NewTInfo;
4024 
4025  // and the declarator-id is replaced with operator==
4026  NameInfo.setName(
4027  SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4028 }
4029 
4032  if (Spaceship->isInvalidDecl())
4033  return nullptr;
4034 
4035  // C++2a [class.compare.default]p3:
4036  // an == operator function is declared implicitly [...] with the same
4037  // access and function-definition and in the same class scope as the
4038  // three-way comparison operator function
4039  MultiLevelTemplateArgumentList NoTemplateArgs;
4041  NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4042  TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4043  Decl *R;
4044  if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4045  R = Instantiator.VisitCXXMethodDecl(
4046  MD, nullptr, None,
4048  } else {
4049  assert(Spaceship->getFriendObjectKind() &&
4050  "defaulted spaceship is neither a member nor a friend");
4051 
4052  R = Instantiator.VisitFunctionDecl(
4053  Spaceship, nullptr,
4055  if (!R)
4056  return nullptr;
4057 
4058  FriendDecl *FD =
4059  FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4060  cast<NamedDecl>(R), Spaceship->getBeginLoc());
4061  FD->setAccess(AS_public);
4062  RD->addDecl(FD);
4063  }
4064  return cast_or_null<FunctionDecl>(R);
4065 }
4066 
4067 /// Instantiates a nested template parameter list in the current
4068 /// instantiation context.
4069 ///
4070 /// \param L The parameter list to instantiate
4071 ///
4072 /// \returns NULL if there was an error
4075  // Get errors for all the parameters before bailing out.
4076  bool Invalid = false;
4077 
4078  unsigned N = L->size();
4079  typedef SmallVector<NamedDecl *, 8> ParamVector;
4080  ParamVector Params;
4081  Params.reserve(N);
4082  for (auto &P : *L) {
4083  NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4084  Params.push_back(D);
4085  Invalid = Invalid || !D || D->isInvalidDecl();
4086  }
4087 
4088  // Clean up if we had an error.
4089  if (Invalid)
4090  return nullptr;
4091 
4092  Expr *InstRequiresClause = L->getRequiresClause();
4093 
4094  TemplateParameterList *InstL
4095  = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4096  L->getLAngleLoc(), Params,
4097  L->getRAngleLoc(), InstRequiresClause);
4098  return InstL;
4099 }
4100 
4103  const MultiLevelTemplateArgumentList &TemplateArgs,
4104  bool EvaluateConstraints) {
4105  TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4106  Instantiator.setEvaluateConstraints(EvaluateConstraints);
4107  return Instantiator.SubstTemplateParams(Params);
4108 }
4109 
4110 /// Instantiate the declaration of a class template partial
4111 /// specialization.
4112 ///
4113 /// \param ClassTemplate the (instantiated) class template that is partially
4114 // specialized by the instantiation of \p PartialSpec.
4115 ///
4116 /// \param PartialSpec the (uninstantiated) class template partial
4117 /// specialization that we are instantiating.
4118 ///
4119 /// \returns The instantiated partial specialization, if successful; otherwise,
4120 /// NULL to indicate an error.
4123  ClassTemplateDecl *ClassTemplate,
4125  // Create a local instantiation scope for this class template partial
4126  // specialization, which will contain the instantiations of the template
4127  // parameters.
4128  LocalInstantiationScope Scope(SemaRef);
4129 
4130  // Substitute into the template parameters of the class template partial
4131  // specialization.
4132  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4133  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4134  if (!InstParams)
4135  return nullptr;
4136 
4137  // Substitute into the template arguments of the class template partial
4138  // specialization.
4139  const ASTTemplateArgumentListInfo *TemplArgInfo
4140  = PartialSpec->getTemplateArgsAsWritten();
4141  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4142  TemplArgInfo->RAngleLoc);
4143  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4144  InstTemplateArgs))
4145  return nullptr;
4146 
4147  // Check that the template argument list is well-formed for this
4148  // class template.
4149  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4150  if (SemaRef.CheckTemplateArgumentList(
4151  ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4152  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4153  return nullptr;
4154 
4155  // Check these arguments are valid for a template partial specialization.
4157  PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4158  CanonicalConverted))
4159  return nullptr;
4160 
4161  // Figure out where to insert this class template partial specialization
4162  // in the member template's set of class template partial specializations.
4163  void *InsertPos = nullptr;
4165  ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4166  InsertPos);
4167 
4168  // Build the canonical type that describes the converted template
4169  // arguments of the class template partial specialization.
4170  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4171  TemplateName(ClassTemplate), CanonicalConverted);
4172 
4173  // Build the fully-sugared type for this class template
4174  // specialization as the user wrote in the specialization
4175  // itself. This means that we'll pretty-print the type retrieved
4176  // from the specialization's declaration the way that the user
4177  // actually wrote the specialization, rather than formatting the
4178  // name based on the "canonical" representation used to store the
4179  // template arguments in the specialization.
4180  TypeSourceInfo *WrittenTy
4182  TemplateName(ClassTemplate),
4183  PartialSpec->getLocation(),
4184  InstTemplateArgs,
4185  CanonType);
4186 
4187  if (PrevDecl) {
4188  // We've already seen a partial specialization with the same template
4189  // parameters and template arguments. This can happen, for example, when
4190  // substituting the outer template arguments ends up causing two
4191  // class template partial specializations of a member class template
4192  // to have identical forms, e.g.,
4193  //
4194  // template<typename T, typename U>
4195  // struct Outer {
4196  // template<typename X, typename Y> struct Inner;
4197  // template<typename Y> struct Inner<T, Y>;
4198  // template<typename Y> struct Inner<U, Y>;
4199  // };
4200  //
4201  // Outer<int, int> outer; // error: the partial specializations of Inner
4202  // // have the same signature.
4203  SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4204  << WrittenTy->getType();
4205  SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4206  << SemaRef.Context.getTypeDeclType(PrevDecl);
4207  return nullptr;
4208  }
4209 
4210 
4211  // Create the class template partial specialization declaration.
4212  ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4214  SemaRef.Context, PartialSpec->getTagKind(), Owner,
4215  PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4216  ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
4217  nullptr);
4218  // Substitute the nested name specifier, if any.
4219  if (SubstQualifier(PartialSpec, InstPartialSpec))
4220  return nullptr;
4221 
4222  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4223  InstPartialSpec->setTypeAsWritten(WrittenTy);
4224 
4225  // Check the completed partial specialization.
4226  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4227 
4228  // Add this partial specialization to the set of class template partial
4229  // specializations.
4230  ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4231  /*InsertPos=*/nullptr);
4232  return InstPartialSpec;
4233 }
4234 
4235 /// Instantiate the declaration of a variable template partial
4236 /// specialization.
4237 ///
4238 /// \param VarTemplate the (instantiated) variable template that is partially
4239 /// specialized by the instantiation of \p PartialSpec.
4240 ///
4241 /// \param PartialSpec the (uninstantiated) variable template partial
4242 /// specialization that we are instantiating.
4243 ///
4244 /// \returns The instantiated partial specialization, if successful; otherwise,
4245 /// NULL to indicate an error.
4248  VarTemplateDecl *VarTemplate,
4249  VarTemplatePartialSpecializationDecl *PartialSpec) {
4250  // Create a local instantiation scope for this variable template partial
4251  // specialization, which will contain the instantiations of the template
4252  // parameters.
4253  LocalInstantiationScope Scope(SemaRef);
4254 
4255  // Substitute into the template parameters of the variable template partial
4256  // specialization.
4257  TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4258  TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4259  if (!InstParams)
4260  return nullptr;
4261 
4262  // Substitute into the template arguments of the variable template partial
4263  // specialization.
4264  const ASTTemplateArgumentListInfo *TemplArgInfo
4265  = PartialSpec->getTemplateArgsAsWritten();
4266  TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4267  TemplArgInfo->RAngleLoc);
4268  if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4269  InstTemplateArgs))
4270  return nullptr;
4271 
4272  // Check that the template argument list is well-formed for this
4273  // class template.
4274  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4275  if (SemaRef.CheckTemplateArgumentList(
4276  VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4277  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4278  return nullptr;
4279 
4280  // Check these arguments are valid for a template partial specialization.
4282  PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4283  CanonicalConverted))
4284  return nullptr;
4285 
4286  // Figure out where to insert this variable template partial specialization
4287  // in the member template's set of variable template partial specializations.
4288  void *InsertPos = nullptr;
4289  VarTemplateSpecializationDecl *PrevDecl =
4290  VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4291  InsertPos);
4292 
4293  // Build the canonical type that describes the converted template
4294  // arguments of the variable template partial specialization.
4295  QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4296  TemplateName(VarTemplate), CanonicalConverted);
4297 
4298  // Build the fully-sugared type for this variable template
4299  // specialization as the user wrote in the specialization
4300  // itself. This means that we'll pretty-print the type retrieved
4301  // from the specialization's declaration the way that the user
4302  // actually wrote the specialization, rather than formatting the
4303  // name based on the "canonical" representation used to store the
4304  // template arguments in the specialization.
4306  TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4307  CanonType);
4308 
4309  if (PrevDecl) {
4310  // We've already seen a partial specialization with the same template
4311  // parameters and template arguments. This can happen, for example, when
4312  // substituting the outer template arguments ends up causing two
4313  // variable template partial specializations of a member variable template
4314  // to have identical forms, e.g.,
4315  //
4316  // template<typename T, typename U>
4317  // struct Outer {
4318  // template<typename X, typename Y> pair<X,Y> p;
4319  // template<typename Y> pair<T, Y> p;
4320  // template<typename Y> pair<U, Y> p;
4321  // };
4322  //
4323  // Outer<int, int> outer; // error: the partial specializations of Inner
4324  // // have the same signature.
4325  SemaRef.Diag(PartialSpec->getLocation(),
4326  diag::err_var_partial_spec_redeclared)
4327  << WrittenTy->getType();
4328  SemaRef.Diag(PrevDecl->getLocation(),
4329  diag::note_var_prev_partial_spec_here);
4330  return nullptr;
4331  }
4332 
4333  // Do substitution on the type of the declaration
4334  TypeSourceInfo *DI = SemaRef.SubstType(
4335  PartialSpec->getTypeSourceInfo(), TemplateArgs,
4336  PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4337  if (!DI)
4338  return nullptr;
4339 
4340  if (DI->getType()->isFunctionType()) {
4341  SemaRef.Diag(PartialSpec->getLocation(),
4342  diag::err_variable_instantiates_to_function)
4343  << PartialSpec->isStaticDataMember() << DI->getType();
4344  return nullptr;
4345  }
4346 
4347  // Create the variable template partial specialization declaration.
4348  VarTemplatePartialSpecializationDecl *InstPartialSpec =
4350  SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4351  PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4352  DI, PartialSpec->getStorageClass(), CanonicalConverted,
4353  InstTemplateArgs);
4354 
4355  // Substitute the nested name specifier, if any.
4356  if (SubstQualifier(PartialSpec, InstPartialSpec))
4357  return nullptr;
4358 
4359  InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4360  InstPartialSpec->setTypeAsWritten(WrittenTy);
4361 
4362  // Check the completed partial specialization.
4363  SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4364 
4365  // Add this partial specialization to the set of variable template partial
4366  // specializations. The instantiation of the initializer is not necessary.
4367  VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4368 
4369  SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4370  LateAttrs, Owner, StartingScope);
4371 
4372  return InstPartialSpec;
4373 }
4374 
4378  TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4379  assert(OldTInfo && "substituting function without type source info");
4380  assert(Params.empty() && "parameter vector is non-empty at start");
4381 
4382  CXXRecordDecl *ThisContext = nullptr;
4383  Qualifiers ThisTypeQuals;
4384  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4385  ThisContext = cast<CXXRecordDecl>(Owner);
4386  ThisTypeQuals = Method->getMethodQualifiers();
4387  }
4388 
4389  TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4390  OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4391  ThisContext, ThisTypeQuals, EvaluateConstraints);
4392  if (!NewTInfo)
4393  return nullptr;
4394 
4395  TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4396  if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4397  if (NewTInfo != OldTInfo) {
4398  // Get parameters from the new type info.
4399  TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4400  FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4401  unsigned NewIdx = 0;
4402  for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4403  OldIdx != NumOldParams; ++OldIdx) {
4404  ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4405  if (!OldParam)
4406  return nullptr;
4407 
4409 
4410  Optional<unsigned> NumArgumentsInExpansion;
4411  if (OldParam->isParameterPack())
4412  NumArgumentsInExpansion =
4413  SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4414  TemplateArgs);
4415  if (!NumArgumentsInExpansion) {
4416  // Simple case: normal parameter, or a parameter pack that's
4417  // instantiated to a (still-dependent) parameter pack.
4418  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4419  Params.push_back(NewParam);
4420  Scope->InstantiatedLocal(OldParam, NewParam);
4421  } else {
4422  // Parameter pack expansion: make the instantiation an argument pack.
4423  Scope->MakeInstantiatedLocalArgPack(OldParam);
4424  for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4425  ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4426  Params.push_back(NewParam);
4427  Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4428  }
4429  }
4430  }
4431  } else {
4432  // The function type itself was not dependent and therefore no
4433  // substitution occurred. However, we still need to instantiate
4434  // the function parameters themselves.
4435  const FunctionProtoType *OldProto =
4436  cast<FunctionProtoType>(OldProtoLoc.getType());
4437  for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4438  ++i) {
4439  ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4440  if (!OldParam) {
4441  Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4442  D, D->getLocation(), OldProto->getParamType(i)));
4443  continue;
4444  }
4445 
4446  ParmVarDecl *Parm =
4447  cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4448  if (!Parm)
4449  return nullptr;
4450  Params.push_back(Parm);
4451  }
4452  }
4453  } else {
4454  // If the type of this function, after ignoring parentheses, is not
4455  // *directly* a function type, then we're instantiating a function that
4456  // was declared via a typedef or with attributes, e.g.,
4457  //
4458  // typedef int functype(int, int);
4459  // functype func;
4460  // int __cdecl meth(int, int);
4461  //
4462  // In this case, we'll just go instantiate the ParmVarDecls that we
4463  // synthesized in the method declaration.
4464  SmallVector<QualType, 4> ParamTypes;
4465  Sema::ExtParameterInfoBuilder ExtParamInfos;
4466  if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4467  TemplateArgs, ParamTypes, &Params,
4468  ExtParamInfos))
4469  return nullptr;
4470  }
4471 
4472  return NewTInfo;
4473 }
4474 
4475 /// Introduce the instantiated function parameters into the local
4476 /// instantiation scope, and set the parameter names to those used
4477 /// in the template.
4478 bool Sema::addInstantiatedParametersToScope(
4479  FunctionDecl *Function, const FunctionDecl *PatternDecl,
4481  const MultiLevelTemplateArgumentList &TemplateArgs) {
4482  unsigned FParamIdx = 0;
4483  for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4484  const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4485  if (!PatternParam->isParameterPack()) {
4486  // Simple case: not a parameter pack.
4487  assert(FParamIdx < Function->getNumParams());
4488  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4489  FunctionParam->setDeclName(PatternParam->getDeclName());
4490  // If the parameter's type is not dependent, update it to match the type
4491  // in the pattern. They can differ in top-level cv-qualifiers, and we want
4492  // the pattern's type here. If the type is dependent, they can't differ,
4493  // per core issue 1668. Substitute into the type from the pattern, in case
4494  // it's instantiation-dependent.
4495  // FIXME: Updating the type to work around this is at best fragile.
4496  if (!PatternDecl->getType()->isDependentType()) {
4497  QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4498  FunctionParam->getLocation(),
4499  FunctionParam->getDeclName());
4500  if (T.isNull())
4501  return true;
4502  FunctionParam->setType(T);
4503  }
4504 
4505  Scope.InstantiatedLocal(PatternParam, FunctionParam);
4506  ++FParamIdx;
4507  continue;
4508  }
4509 
4510  // Expand the parameter pack.
4511  Scope.MakeInstantiatedLocalArgPack(PatternParam);
4512  Optional<unsigned> NumArgumentsInExpansion =
4513  getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4514  if (NumArgumentsInExpansion) {
4515  QualType PatternType =
4516  PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4517  for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4518  ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4519  FunctionParam->setDeclName(PatternParam->getDeclName());
4520  if (!PatternDecl->getType()->isDependentType()) {
4521  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4522  QualType T =
4523  SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4524  FunctionParam->getDeclName());
4525  if (T.isNull())
4526  return true;
4527  FunctionParam->setType(T);
4528  }
4529 
4530  Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4531  ++FParamIdx;
4532  }
4533  }
4534  }
4535 
4536  return false;
4537 }
4538 
4540  ParmVarDecl *Param) {
4541  assert(Param->hasUninstantiatedDefaultArg());
4542 
4543  // Instantiate the expression.
4544  //
4545  // FIXME: Pass in a correct Pattern argument, otherwise
4546  // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4547  //
4548  // template<typename T>
4549  // struct A {
4550  // static int FooImpl();
4551  //
4552  // template<typename Tp>
4553  // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4554  // // template argument list [[T], [Tp]], should be [[Tp]].
4555  // friend A<Tp> Foo(int a);
4556  // };
4557  //
4558  // template<typename T>
4559  // A<T> Foo(int a = A<T>::FooImpl());
4561  FD, /*Final=*/false, nullptr, /*RelativeToPrimary=*/true);
4562 
4563  if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4564  return true;
4565 
4567  L->DefaultArgumentInstantiated(Param);
4568 
4569  return false;
4570 }
4571 
4573  FunctionDecl *Decl) {
4574  const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4575  if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4576  return;
4577 
4578  InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4580  if (Inst.isInvalid()) {
4581  // We hit the instantiation depth limit. Clear the exception specification
4582  // so that our callers don't have to cope with EST_Uninstantiated.
4584  return;
4585  }
4586  if (Inst.isAlreadyInstantiating()) {
4587  // This exception specification indirectly depends on itself. Reject.
4588  // FIXME: Corresponding rule in the standard?
4589  Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4591  return;
4592  }
4593 
4594  // Enter the scope of this instantiation. We don't use
4595  // PushDeclContext because we don't have a scope.
4596  Sema::ContextRAII savedContext(*this, Decl);
4598 
4600  Decl, /*Final=*/false, nullptr, /*RelativeToPrimary*/ true);
4601 
4602  // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4603  // here, because for a non-defining friend declaration in a class template,
4604  // we don't store enough information to map back to the friend declaration in
4605  // the template.
4606  FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4607  if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4609  return;
4610  }
4611 
4613  TemplateArgs);
4614 }
4615 
4616 /// Initializes the common fields of an instantiation function
4617 /// declaration (New) from the corresponding fields of its template (Tmpl).
4618 ///
4619 /// \returns true if there was an error
4620 bool
4622  FunctionDecl *Tmpl) {
4623  New->setImplicit(Tmpl->isImplicit());
4624 
4625  // Forward the mangling number from the template to the instantiated decl.
4626  SemaRef.Context.setManglingNumber(New,
4627  SemaRef.Context.getManglingNumber(Tmpl));
4628 
4629  // If we are performing substituting explicitly-specified template arguments
4630  // or deduced template arguments into a function template and we reach this
4631  // point, we are now past the point where SFINAE applies and have committed
4632  // to keeping the new function template specialization. We therefore
4633  // convert the active template instantiation for the function template
4634  // into a template instantiation for this specific function template
4635  // specialization, which is not a SFINAE context, so that we diagnose any
4636  // further errors in the declaration itself.
4637  //
4638  // FIXME: This is a hack.
4639  typedef Sema::CodeSynthesisContext ActiveInstType;
4640  ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4641  if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4642  ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4643  if (FunctionTemplateDecl *FunTmpl
4644  = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
4645  assert(FunTmpl->getTemplatedDecl() == Tmpl &&
4646  "Deduction from the wrong function template?");
4647  (void) FunTmpl;
4648  SemaRef.InstantiatingSpecializations.erase(
4649  {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4650  atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4651  ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4652  ActiveInst.Entity = New;
4653  atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4654  }
4655  }
4656 
4657  const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4658  assert(Proto && "Function template without prototype?");
4659 
4660  if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4662 
4663  // DR1330: In C++11, defer instantiation of a non-trivial
4664  // exception specification.
4665  // DR1484: Local classes and their members are instantiated along with the
4666  // containing function.
4667  if (SemaRef.getLangOpts().CPlusPlus11 &&
4668  EPI.ExceptionSpec.Type != EST_None &&
4671  !Tmpl->isInLocalScopeForInstantiation()) {
4672  FunctionDecl *ExceptionSpecTemplate = Tmpl;
4674  ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4676  if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4677  NewEST = EST_Unevaluated;
4678 
4679  // Mark the function has having an uninstantiated exception specification.
4680  const FunctionProtoType *NewProto
4681  = New->getType()->getAs<FunctionProtoType>();
4682  assert(NewProto && "Template instantiation without function prototype?");
4683  EPI = NewProto->getExtProtoInfo();
4684  EPI.ExceptionSpec.Type = NewEST;
4685  EPI.ExceptionSpec.SourceDecl = New;
4686  EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4687  New->setType(SemaRef.Context.getFunctionType(
4688  NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4689  } else {
4690  Sema::ContextRAII SwitchContext(SemaRef, New);
4691  SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4692  }
4693  }
4694 
4695  // Get the definition. Leaves the variable unchanged if undefined.
4696  const FunctionDecl *Definition = Tmpl;
4697  Tmpl->isDefined(Definition);
4698 
4699  SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4700  LateAttrs, StartingScope);
4701 
4702  return false;
4703 }
4704 
4705 /// Initializes common fields of an instantiated method
4706 /// declaration (New) from the corresponding fields of its template
4707 /// (Tmpl).
4708 ///
4709 /// \returns true if there was an error
4710 bool
4712  CXXMethodDecl *Tmpl) {
4713  if (InitFunctionInstantiation(New, Tmpl))
4714  return true;
4715 
4716  if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4717  SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4718 
4719  New->setAccess(Tmpl->getAccess());
4720  if (Tmpl->isVirtualAsWritten())
4721  New->setVirtualAsWritten(true);
4722 
4723  // FIXME: New needs a pointer to Tmpl
4724  return false;
4725 }
4726 
4728  FunctionDecl *Tmpl) {
4729  // Transfer across any unqualified lookups.
4730  if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4732  Lookups.reserve(DFI->getUnqualifiedLookups().size());
4733  bool AnyChanged = false;
4734  for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4735  NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4736  DA.getDecl(), TemplateArgs);
4737  if (!D)
4738  return true;
4739  AnyChanged |= (D != DA.getDecl());
4740  Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4741  }
4742 
4743  // It's unlikely that substitution will change any declarations. Don't
4744  // store an unnecessary copy in that case.
4747  SemaRef.Context, Lookups)
4748  : DFI);
4749  }
4750 
4751  SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4752  return false;
4753 }
4754 
4755 /// Instantiate (or find existing instantiation of) a function template with a
4756 /// given set of template arguments.
4757 ///
4758 /// Usually this should not be used, and template argument deduction should be
4759 /// used in its place.
4760 FunctionDecl *
4762  const TemplateArgumentList *Args,
4763  SourceLocation Loc) {
4764  FunctionDecl *FD = FTD->getTemplatedDecl();
4765 
4766  sema::TemplateDeductionInfo Info(Loc);
4767  InstantiatingTemplate Inst(
4768  *this, Loc, FTD, Args->asArray(),
4770  if (Inst.isInvalid())
4771  return nullptr;
4772 
4773  ContextRAII SavedContext(*this, FD);
4774  MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4775  /*Final=*/false);
4776 
4777  return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4778 }
4779 
4780 /// Instantiate the definition of the given function from its
4781 /// template.
4782 ///
4783 /// \param PointOfInstantiation the point at which the instantiation was
4784 /// required. Note that this is not precisely a "point of instantiation"
4785 /// for the function, but it's close.
4786 ///
4787 /// \param Function the already-instantiated declaration of a
4788 /// function template specialization or member function of a class template
4789 /// specialization.
4790 ///
4791 /// \param Recursive if true, recursively instantiates any functions that
4792 /// are required by this instantiation.
4793 ///
4794 /// \param DefinitionRequired if true, then we are performing an explicit
4795 /// instantiation where the body of the function is required. Complain if
4796 /// there is no such body.
4798  FunctionDecl *Function,
4799  bool Recursive,
4800  bool DefinitionRequired,
4801  bool AtEndOfTU) {
4802  if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4803  return;
4804 
4805  // Never instantiate an explicit specialization except if it is a class scope
4806  // explicit specialization.
4808  Function->getTemplateSpecializationKindForInstantiation();
4809  if (TSK == TSK_ExplicitSpecialization)
4810  return;
4811 
4812  // Never implicitly instantiate a builtin; we don't actually need a function
4813  // body.
4814  if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4815  !DefinitionRequired)
4816  return;
4817 
4818  // Don't instantiate a definition if we already have one.
4819  const FunctionDecl *ExistingDefn = nullptr;
4820  if (Function->isDefined(ExistingDefn,
4821  /*CheckForPendingFriendDefinition=*/true)) {
4822  if (ExistingDefn->isThisDeclarationADefinition())
4823  return;
4824 
4825  // If we're asked to instantiate a function whose body comes from an
4826  // instantiated friend declaration, attach the instantiated body to the
4827  // corresponding declaration of the function.
4829  Function = const_cast<FunctionDecl*>(ExistingDefn);
4830  }
4831 
4832  // Find the function body that we'll be substituting.
4833  const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4834  assert(PatternDecl && "instantiating a non-template");
4835 
4836  const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4837  Stmt *Pattern = nullptr;
4838  if (PatternDef) {
4839  Pattern = PatternDef->getBody(PatternDef);
4840  PatternDecl = PatternDef;
4841  if (PatternDef->willHaveBody())
4842  PatternDef = nullptr;
4843  }
4844 
4845  // FIXME: We need to track the instantiation stack in order to know which
4846  // definitions should be visible within this instantiation.
4847  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4848  Function->getInstantiatedFromMemberFunction(),
4849  PatternDecl, PatternDef, TSK,
4850  /*Complain*/DefinitionRequired)) {
4851  if (DefinitionRequired)
4852  Function->setInvalidDecl();
4853  else if (TSK == TSK_ExplicitInstantiationDefinition ||
4854  (Function->isConstexpr() && !Recursive)) {
4855  // Try again at the end of the translation unit (at which point a
4856  // definition will be required).
4857  assert(!Recursive);
4858  Function->setInstantiationIsPending(true);
4859  PendingInstantiations.push_back(
4860  std::make_pair(Function, PointOfInstantiation));
4861  } else if (TSK == TSK_ImplicitInstantiation) {
4862  if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4863  !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4864  Diag(PointOfInstantiation, diag::warn_func_template_missing)
4865  << Function;
4866  Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4867  if (getLangOpts().CPlusPlus11)
4868  Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4869  << Function;
4870  }
4871  }
4872 
4873  return;
4874  }
4875 
4876  // Postpone late parsed template instantiations.
4877  if (PatternDecl->isLateTemplateParsed() &&
4878  !LateTemplateParser) {
4879  Function->setInstantiationIsPending(true);
4880  LateParsedInstantiations.push_back(
4881  std::make_pair(Function, PointOfInstantiation));
4882  return;
4883  }
4884 
4885  llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4886  std::string Name;
4887  llvm::raw_string_ostream OS(Name);
4888  Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4889  /*Qualified=*/true);
4890  return Name;
4891  });
4892 
4893  // If we're performing recursive template instantiation, create our own
4894  // queue of pending implicit instantiations that we will instantiate later,
4895  // while we're still within our own instantiation context.
4896  // This has to happen before LateTemplateParser below is called, so that
4897  // it marks vtables used in late parsed templates as used.
4898  GlobalEagerInstantiationScope GlobalInstantiations(*this,
4899  /*Enabled=*/Recursive);
4900  LocalEagerInstantiationScope LocalInstantiations(*this);
4901 
4902  // Call the LateTemplateParser callback if there is a need to late parse
4903  // a templated function definition.
4904  if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4906  // FIXME: Optimize to allow individual templates to be deserialized.
4907  if (PatternDecl->isFromASTFile())
4908  ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4909 
4910  auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4911  assert(LPTIter != LateParsedTemplateMap.end() &&
4912  "missing LateParsedTemplate");
4913  LateTemplateParser(OpaqueParser, *LPTIter->second);
4914  Pattern = PatternDecl->getBody(PatternDecl);
4915  }
4916 
4917  // Note, we should never try to instantiate a deleted function template.
4918  assert((Pattern || PatternDecl->isDefaulted() ||
4919  PatternDecl->hasSkippedBody()) &&
4920  "unexpected kind of function template definition");
4921 
4922  // C++1y [temp.explicit]p10:
4923  // Except for inline functions, declarations with types deduced from their
4924  // initializer or return value, and class template specializations, other
4925  // explicit instantiation declarations have the effect of suppressing the
4926  // implicit instantiation of the entity to which they refer.
4928  !PatternDecl->isInlined() &&
4929  !PatternDecl->getReturnType()->getContainedAutoType())
4930  return;
4931 
4932  if (PatternDecl->isInlined()) {
4933  // Function, and all later redeclarations of it (from imported modules,
4934  // for instance), are now implicitly inline.
4935  for (auto *D = Function->getMostRecentDecl(); /**/;
4936  D = D->getPreviousDecl()) {
4937  D->setImplicitlyInline();
4938  if (D == Function)
4939  break;
4940  }
4941  }
4942 
4943  InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4944  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4945  return;
4946  PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4947  "instantiating function definition");
4948 
4949  // The instantiation is visible here, even if it was first declared in an
4950  // unimported module.
4951  Function->setVisibleDespiteOwningModule();
4952 
4953  // Copy the inner loc start from the pattern.
4954  Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4955 
4958 
4959  // Introduce a new scope where local variable instantiations will be
4960  // recorded, unless we're actually a member function within a local
4961  // class, in which case we need to merge our results with the parent
4962  // scope (of the enclosing function). The exception is instantiating
4963  // a function template specialization, since the template to be
4964  // instantiated already has references to locals properly substituted.
4965  bool MergeWithParentScope = false;
4966  if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4967  MergeWithParentScope =
4968  Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
4969 
4970  LocalInstantiationScope Scope(*this, MergeWithParentScope);
4971  auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
4972  // Special members might get their TypeSourceInfo set up w.r.t the
4973  // PatternDecl context, in which case parameters could still be pointing
4974  // back to the original class, make sure arguments are bound to the
4975  // instantiated record instead.
4976  assert(PatternDecl->isDefaulted() &&
4977  "Special member needs to be defaulted");
4978  auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
4979  if (!(PatternSM == Sema::CXXCopyConstructor ||
4980  PatternSM == Sema::CXXCopyAssignment ||
4981  PatternSM == Sema::CXXMoveConstructor ||
4982  PatternSM == Sema::CXXMoveAssignment))
4983  return;
4984 
4985  auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
4986  const auto *PatternRec =
4987  dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
4988  if (!NewRec || !PatternRec)
4989  return;
4990  if (!PatternRec->isLambda())
4991  return;
4992 
4993  struct SpecialMemberTypeInfoRebuilder
4994  : TreeTransform<SpecialMemberTypeInfoRebuilder> {
4996  const CXXRecordDecl *OldDecl;
4997  CXXRecordDecl *NewDecl;
4998 
4999  SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5000  CXXRecordDecl *N)
5001  : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5002 
5003  bool TransformExceptionSpec(SourceLocation Loc,
5005  SmallVectorImpl<QualType> &Exceptions,
5006  bool &Changed) {
5007  return false;
5008  }
5009 
5010  QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5011  const RecordType *T = TL.getTypePtr();
5012  RecordDecl *Record = cast_or_null<RecordDecl>(
5013  getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5014  if (Record != OldDecl)
5015  return Base::TransformRecordType(TLB, TL);
5016 
5017  QualType Result = getDerived().RebuildRecordType(NewDecl);
5018  if (Result.isNull())
5019  return QualType();
5020 
5021  RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5022  NewTL.setNameLoc(TL.getNameLoc());
5023  return Result;
5024  }
5025  } IR{*this, PatternRec, NewRec};
5026 
5027  TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
5028  Function->setType(NewSI->getType());
5029  Function->setTypeSourceInfo(NewSI);
5030 
5031  ParmVarDecl *Parm = Function->getParamDecl(0);
5032  TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5033  Parm->setType(NewParmSI->getType());
5034  Parm->setTypeSourceInfo(NewParmSI);
5035  };
5036 
5037  if (PatternDecl->isDefaulted()) {
5038  RebuildTypeSourceInfoForDefaultSpecialMembers();
5039  SetDeclDefaulted(Function, PatternDecl->getLocation());
5040  } else {
5042  Function, /*Final=*/false, nullptr, false, PatternDecl);
5043 
5044  // Substitute into the qualifier; we can get a substitution failure here
5045  // through evil use of alias templates.
5046  // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5047  // of the) lexical context of the pattern?
5048  SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5049 
5050  ActOnStartOfFunctionDef(nullptr, Function);
5051 
5052  // Enter the scope of this instantiation. We don't use
5053  // PushDeclContext because we don't have a scope.
5054  Sema::ContextRAII savedContext(*this, Function);
5055 
5056  if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5057  TemplateArgs))
5058  return;
5059 
5060  StmtResult Body;
5061  if (PatternDecl->hasSkippedBody()) {
5062  ActOnSkippedFunctionBody(Function);
5063  Body = nullptr;
5064  } else {
5065  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5066  // If this is a constructor, instantiate the member initializers.
5067  InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5068  TemplateArgs);
5069 
5070  // If this is an MS ABI dllexport default constructor, instantiate any
5071  // default arguments.
5073  Ctor->isDefaultConstructor()) {
5075  }
5076  }
5077 
5078  // Instantiate the function body.
5079  Body = SubstStmt(Pattern, TemplateArgs);
5080 
5081  if (Body.isInvalid())
5082  Function->setInvalidDecl();
5083  }
5084  // FIXME: finishing the function body while in an expression evaluation
5085  // context seems wrong. Investigate more.
5086  ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5087 
5088  PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5089 
5090  if (auto *Listener = getASTMutationListener())
5091  Listener->FunctionDefinitionInstantiated(Function);
5092 
5093  savedContext.pop();
5094  }
5095 
5096  DeclGroupRef DG(Function);
5098 
5099  // This class may have local implicit instantiations that need to be
5100  // instantiation within this scope.
5101  LocalInstantiations.perform();
5102  Scope.Exit();
5103  GlobalInstantiations.perform();
5104 }
5105 
5107  VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5108  const TemplateArgumentList &TemplateArgList,
5109  const TemplateArgumentListInfo &TemplateArgsInfo,
5111  SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5112  LocalInstantiationScope *StartingScope) {
5113  if (FromVar->isInvalidDecl())
5114  return nullptr;
5115 
5116  InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5117  if (Inst.isInvalid())
5118  return nullptr;
5119 
5120  // Instantiate the first declaration of the variable template: for a partial
5121  // specialization of a static data member template, the first declaration may
5122  // or may not be the declaration in the class; if it's in the class, we want
5123  // to instantiate a member in the class (a declaration), and if it's outside,
5124  // we want to instantiate a definition.
5125  //
5126  // If we're instantiating an explicitly-specialized member template or member
5127  // partial specialization, don't do this. The member specialization completely
5128  // replaces the original declaration in this case.
5129  bool IsMemberSpec = false;
5130  MultiLevelTemplateArgumentList MultiLevelList;
5131  if (auto *PartialSpec =
5132  dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5133  IsMemberSpec = PartialSpec->isMemberSpecialization();
5134  MultiLevelList.addOuterTemplateArguments(
5135  PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
5136  } else {
5137  assert(VarTemplate == FromVar->getDescribedVarTemplate());
5138  IsMemberSpec = VarTemplate->isMemberSpecialization();
5139  MultiLevelList.addOuterTemplateArguments(
5140  VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
5141  }
5142  if (!IsMemberSpec)
5143  FromVar = FromVar->getFirstDecl();
5144 
5145  TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5146  MultiLevelList);
5147 
5148  // TODO: Set LateAttrs and StartingScope ...
5149 
5150  return cast_or_null<VarTemplateSpecializationDecl>(
5152  VarTemplate, FromVar, TemplateArgsInfo, Converted));
5153 }
5154 
5155 /// Instantiates a variable template specialization by completing it
5156 /// with appropriate type information and initializer.
5158  VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5159  const MultiLevelTemplateArgumentList &TemplateArgs) {
5160  assert(PatternDecl->isThisDeclarationADefinition() &&
5161  "don't have a definition to instantiate from");
5162 
5163  // Do substitution on the type of the declaration
5164  TypeSourceInfo *DI =
5165  SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5166  PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5167  if (!DI)
5168  return nullptr;
5169 
5170  // Update the type of this variable template specialization.
5171  VarSpec->setType(DI->getType());
5172 
5173  // Convert the declaration into a definition now.
5174  VarSpec->setCompleteDefinition();
5175 
5176  // Instantiate the initializer.
5177  InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5178 
5179  if (getLangOpts().OpenCL)
5180  deduceOpenCLAddressSpace(VarSpec);
5181 
5182  return VarSpec;
5183 }
5184 
5185 /// BuildVariableInstantiation - Used after a new variable has been created.
5186 /// Sets basic variable data and decides whether to postpone the
5187 /// variable instantiation.
5189  VarDecl *NewVar, VarDecl *OldVar,
5190  const MultiLevelTemplateArgumentList &TemplateArgs,
5191  LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5192  LocalInstantiationScope *StartingScope,
5193  bool InstantiatingVarTemplate,
5194  VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5195  // Instantiating a partial specialization to produce a partial
5196  // specialization.
5197  bool InstantiatingVarTemplatePartialSpec =
5198  isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5199  isa<VarTemplatePartialSpecializationDecl>(NewVar);
5200  // Instantiating from a variable template (or partial specialization) to
5201  // produce a variable template specialization.
5202  bool InstantiatingSpecFromTemplate =
5203  isa<VarTemplateSpecializationDecl>(NewVar) &&
5204  (OldVar->getDescribedVarTemplate() ||
5205  isa<VarTemplatePartialSpecializationDecl>(OldVar));
5206 
5207  // If we are instantiating a local extern declaration, the
5208  // instantiation belongs lexically to the containing function.
5209  // If we are instantiating a static data member defined
5210  // out-of-line, the instantiation will have the same lexical
5211  // context (which will be a namespace scope) as the template.
5212  if (OldVar->isLocalExternDecl()) {
5213  NewVar->setLocalExternDecl();
5214  NewVar->setLexicalDeclContext(Owner);
5215  } else if (OldVar->isOutOfLine())
5216  NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5217  NewVar->setTSCSpec(OldVar->getTSCSpec());
5218  NewVar->setInitStyle(OldVar->getInitStyle());
5219  NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5220  NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5221  NewVar->setConstexpr(OldVar->isConstexpr());
5222  NewVar->setInitCapture(OldVar->isInitCapture());
5224  OldVar->isPreviousDeclInSameBlockScope());
5225  NewVar->setAccess(OldVar->getAccess());
5226 
5227  if (!OldVar->isStaticDataMember()) {
5228  if (OldVar->isUsed(false))
5229  NewVar->setIsUsed();
5230  NewVar->setReferenced(OldVar->isReferenced());
5231  }
5232 
5233  InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5234 
5236  *this, NewVar->getDeclName(), NewVar->getLocation(),
5241 
5242  if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5244  OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5245  // We have a previous declaration. Use that one, so we merge with the
5246  // right type.
5247  if (NamedDecl *NewPrev = FindInstantiatedDecl(
5248  NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5249  Previous.addDecl(NewPrev);
5250  } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5251  OldVar->hasLinkage()) {
5252  LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5253  } else if (PrevDeclForVarTemplateSpecialization) {
5254  Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5255  }
5257 
5258  if (!InstantiatingVarTemplate) {
5259  NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5260  if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5261  NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5262  }
5263 
5264  if (!OldVar->isOutOfLine()) {
5265  if (NewVar->getDeclContext()->isFunctionOrMethod())
5267  }
5268 
5269  // Link instantiations of static data members back to the template from
5270  // which they were instantiated.
5271  //
5272  // Don't do this when instantiating a template (we link the template itself
5273  // back in that case) nor when instantiating a static data member template
5274  // (that's not a member specialization).
5275  if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5276  !InstantiatingSpecFromTemplate)
5277  NewVar->setInstantiationOfStaticDataMember(OldVar,
5279 
5280  // If the pattern is an (in-class) explicit specialization, then the result
5281  // is also an explicit specialization.
5282  if (VarTemplateSpecializationDecl *OldVTSD =
5283  dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5284  if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5285  !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5286  cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5288  }
5289 
5290  // Forward the mangling number from the template to the instantiated decl.
5293 
5294  // Figure out whether to eagerly instantiate the initializer.
5295  if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5296  // We're producing a template. Don't instantiate the initializer yet.
5297  } else if (NewVar->getType()->isUndeducedType()) {
5298  // We need the type to complete the declaration of the variable.
5299  InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5300  } else if (InstantiatingSpecFromTemplate ||
5301  (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5302  !NewVar->isThisDeclarationADefinition())) {
5303  // Delay instantiation of the initializer for variable template
5304  // specializations or inline static data members until a definition of the
5305  // variable is needed.
5306  } else {
5307  InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5308  }
5309 
5310  // Diagnose unused local variables with dependent types, where the diagnostic
5311  // will have been deferred.
5312  if (!NewVar->isInvalidDecl() &&
5313  NewVar->getDeclContext()->isFunctionOrMethod() &&
5314  OldVar->getType()->isDependentType())
5315  DiagnoseUnusedDecl(NewVar);
5316 }
5317 
5318 /// Instantiate the initializer of a variable.
5320  VarDecl *Var, VarDecl *OldVar,
5321  const MultiLevelTemplateArgumentList &TemplateArgs) {
5323  L->VariableDefinitionInstantiated(Var);
5324 
5325  // We propagate the 'inline' flag with the initializer, because it
5326  // would otherwise imply that the variable is a definition for a
5327  // non-static data member.
5328  if (OldVar->isInlineSpecified())
5329  Var->setInlineSpecified();
5330  else if (OldVar->isInline())
5331  Var->setImplicitlyInline();
5332 
5333  if (OldVar->getInit()) {
5336 
5337  // Instantiate the initializer.
5338  ExprResult Init;
5339 
5340  {
5341  ContextRAII SwitchContext(*this, Var->getDeclContext());
5342  Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5343  OldVar->getInitStyle() == VarDecl::CallInit);
5344  }
5345 
5346  if (!Init.isInvalid()) {
5347  Expr *InitExpr = Init.get();
5348 
5349  if (Var->hasAttr<DLLImportAttr>() &&
5350  (!InitExpr ||
5351  !InitExpr->isConstantInitializer(getASTContext(), false))) {
5352  // Do not dynamically initialize dllimport variables.
5353  } else if (InitExpr) {
5354  bool DirectInit = OldVar->isDirectInit();
5355  AddInitializerToDecl(Var, InitExpr, DirectInit);
5356  } else
5358  } else {
5359  // FIXME: Not too happy about invalidating the declaration
5360  // because of a bogus initializer.
5361  Var->setInvalidDecl();
5362  }
5363  } else {
5364  // `inline` variables are a definition and declaration all in one; we won't
5365  // pick up an initializer from anywhere else.
5366  if (Var->isStaticDataMember() && !Var->isInline()) {
5367  if (!Var->isOutOfLine())
5368  return;
5369 
5370  // If the declaration inside the class had an initializer, don't add
5371  // another one to the out-of-line definition.
5372  if (OldVar->getFirstDecl()->hasInit())
5373  return;
5374  }
5375 
5376  // We'll add an initializer to a for-range declaration later.
5377  if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5378  return;
5379 
5381  }
5382 
5383  if (getLangOpts().CUDA)
5385 }
5386